Django, being a powerful and high-level Python web framework, comes with built-in support for authentication systems, making it relatively easy to implement secure user registration, login, and management. This article will walk you through creating a basic authentication system in Django, covering user registration, login, logout, and password management.
Step 1: Setting Up the Django Project
-
Install Django: If you haven't already installed Django, you can do so with the following command:
pip install django
-
Start a new Django project:
django-admin startproject myproject cd myproject
-
Create a new app:
python manage.py startapp accounts
-
Add the app to your project: Open
myproject/settings.py
and add'accounts'
to theINSTALLED_APPS
list:
INSTALLED_APPS = [ # Other installed apps 'accounts', ]
Step 2: Create User Registration
Django comes with a default User
model that can be used for authentication. You can extend this model or use it directly.
-
Create a registration form:
In
accounts/forms.py
, create a form for user registration:
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class RegisterForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
-
Create a registration view:
In
accounts/views.py
, create a view that handles the registration:
from django.shortcuts import render, redirect
from django.contrib.auth import login
from .forms import RegisterForm
def register(request):
if request.method == 'POST':
form = RegisterForm(request.POST)
if form.is_valid():
user = form.save()
login(request, user)
return redirect('home')
else:
form = RegisterForm()
return render(request, 'accounts/register.html', {'form': form})
-
Create a template for registration:
In
accounts/templates/accounts/register.html
:
<h2>Register</h2>
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Register</button>
</form>
-
Add URL pattern:
In
myproject/urls.py
, add a URL pattern for registration:
from django.urls import path
from accounts import views as accounts_views
urlpatterns = [
# Other URL patterns
path('register/', accounts_views.register, name='register'),
]
Step 3: Create User Login
-
Create a login view: Django provides a built-in login view that you can use.
In
myproject/urls.py
, add the following:
from django.contrib.auth import views as auth_views
urlpatterns = [
# Other URL patterns
path('login/', auth_views.LoginView.as_view(template_name='accounts/login.html'), name='login'),
]
-
Create a login template:
In
accounts/templates/accounts/login.html
:
<h2>Login</h2>
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Login</button>
</form>
-
Configure login redirect: In
myproject/settings.py
, configure where users are redirected after login:
LOGIN_REDIRECT_URL = 'home'
Step 4: Create User Logout
-
Create a logout view: Django also provides a built-in logout view.
In
myproject/urls.py
, add the following:
path('logout/', auth_views.LogoutView.as_view(), name='logout'),
- Create a logout link: You can create a link for users to log out in any template:
<a href="{% url 'logout' %}">Logout</a>
Step 5: Password Reset and Management
Django provides built-in views for handling password reset, which you can easily integrate into your project.
-
Add password reset URLs:
In
myproject/urls.py
, add the following:
from django.urls import path
from django.contrib.auth import views as auth_views
urlpatterns = [
# Other URL patterns
path('password_reset/', auth_views.PasswordResetView.as_view(), name='password_reset'),
path('password_reset/done/', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'),
path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'),
path('reset/done/', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'),
]
-
Create templates for password reset:
Django requires a few templates for the password reset process. You can create them in
accounts/templates/registration/
:password_reset_form.html
password_reset_done.html
password_reset_confirm.html
password_reset_complete.html
You can keep the forms simple for now, such as:
<h2>Password Reset</h2>
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Reset Password</button>
</form>
Step 6: Customizing Authentication (Optional)
You can customize the authentication process by extending Django's User
model or overriding the built-in views. You might also want to add features such as:
- Email verification: Send a verification link to the user’s email before activating their account.
- Social authentication: Use third-party services like Google, Facebook, or GitHub for user login.
Step 7: Final Touches
-
Login required decorator: If certain views should only be accessible to logged-in users, you can use the
login_required
decorator. Inmyproject/views.py
:
from django.contrib.auth.decorators import login_required
@login_required
def profile(request):
return render(request, 'profile.html')
- Test your application: Run your server to test the registration, login, and logout functionality:
python manage.py runserver
Conclusion
By following the steps outlined in this article, you can set up a basic authentication system in Django with user registration, login, logout, and password reset functionality. Django’s built-in authentication features allow you to implement a secure and user-friendly system, and you can easily extend it with custom features as needed.
Top comments (0)