In this lesson, we will explore how to implement user authentication and authorization in your Django application. Authentication is the process of verifying who a user is, while authorization determines what an authenticated user is allowed to do.
Django comes with a built-in authentication system that handles user accounts, groups, permissions, and cookie-based user sessions. To use this system, you need to ensure that the django.contrib.auth app is included in your INSTALLED_APPS setting (this is typically done by default).
Make sure your settings.py has the following:
# settings.py
INSTALLED_APPS = [
...
'django.contrib.auth',
'django.contrib.contenttypes',
...
]
You can create user accounts using the Django admin interface or programmatically using the User model. Here’s how to create a user programmatically:
from django.contrib.auth.models import User
# Create a new user
user = User.objects.create_user('username', 'user@example.com', 'password')
user.first_name = 'First'
user.last_name = 'Last'
user.save()
Django provides built-in views for user authentication. You can use these views to handle user login and logout.
To use the login view, you need to set up a URL pattern and a template:
# urls.py
from django.urls import path
from django.contrib.auth import views as auth_views
urlpatterns = [
path('login/', auth_views.LoginView.as_view(), name='login'),
]
Create a template registration/login.html:
<!-- registration/login.html -->
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Login</button>
</form>
To handle logout, add the following URL pattern:
# urls.py
urlpatterns += [
path('logout/', auth_views.LogoutView.as_view(), name='logout'),
]
Django's authorization system allows you to manage user permissions. You can assign permissions to users or groups and check permissions in your views.
You can check if a user has a specific permission using the user.has_perm() method:
# views.py
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
@login_required
def my_view(request):
if request.user.has_perm('app_name.permission_name'):
# Do something for users with permission
return render(request, 'template.html')
else:
return render(request, 'no_permission.html')
You can also use decorators to restrict access to views:
# views.py
from django.contrib.auth.decorators import user_passes_test
@user_passes_test(lambda u: u.is_superuser)
def admin_view(request):
return render(request, 'admin_template.html')
Note: Always use HTTPS in production to protect user credentials during login.
Note: Ensure that your login forms include CSRF tokens to prevent CSRF attacks.
Note: Use Django's built-in user management features instead of rolling your own authentication system.
In this lesson, we covered how to implement user authentication and authorization in your Django application. We learned how to set up user accounts, use built-in authentication views, and manage user permissions effectively.