On this episode, we’re going to look at working with users in a Django project. We’ll see Django’s tools for identifying users and checking what those users are permitted to do on your website.
Listen at djangoriffs.com.
On the last episode, I explained the structure of Django application. We also talked why this structure is significant and how Django apps benefit the Django ecosystem as a tool for sharing code.
Authentication And Authorization
Authentication: When a user tries to prove that they are who they say they are, that is authentication. A user will typically authenticate with your site via some login form or using a social provider like Google to verify their identity.
Authentication can only prove that you are you.
Authorization: What is a user allowed to do? Authorization answers that question. We use authorization to determine what permissions or groups a user belongs to, so that we can scope what a user can do on the site.
Authorization determines what you can do.
The auth features in Django require a couple of built-in Django applications and a couple of middleware classes.
The Django apps are:
authapp depends on)
The middleware classes are:
SessionMiddlewareto store data about a user in a session
AuthenticationMiddlewareto associate users with requests
The Django docs provide additional context about these pre-requisites so check out the auth topic installation section for more details.
In the Django auth system,
identity is tracked
This model stores information
that you’d likely want
with anyone who uses your site.
The model includes:
- name fields,
- email address,
- datetime fields for when a user joins or logs in to your site,
- boolean fields for some coarse permissions that are very commonly needed,
- and password data.
Authenticating With Passwords
When a user wants to authenticate,
the user must log in
to the site.
Django includes a
LoginView class-based view
that can handle the appropriate steps.
LoginView is a form view that:
- Collects the
passwordfrom the user
- Calls the
django.contrib.auth.authenticatefunction with the
passwordto confirm that the user is who they claim to be
- Redirects to either a path that is set
as the value of the
nextparameter in the URL’s querystring or
nextparameter isn’t set
- Or, if authentication failed, re-renders the form page with appropriate error messages
authenticate function will loop through any auth backends
that are set
AUTHENTICATION_BACKENDS list setting.
Each backend can do one of three things:
- Authenticate correctly with the user and return a
- Not authenticate and return
None. In this case, the next backend is tried.
- Not authenticate and raise a
PermissionDeniedexception. In this case, no other backends are tried.
ModelBackend is named as it is
because it uses the
from the user,
the backend compares the provided data
to any existing
Django doesn’t store actual passwords.
To do so would be a major weakness
in the framework
because any leak
of the database would leak all users passwords.
And that’s totally not cool.
stores a hash
of the password.
Why is this useful?
By computing hashes,
Django can safely store
that computed value
without compromising a user’s password.
When a user wants to authenticate
with a site,
the user submits a password,
Django computes the hash
on that submitted value
and compares it to the hash stored
in the database.
If the hashes match,
then the site can conclude
that the user sent the correct password.
Only the password’s hash
would match the hash stored
Hashing is a fascinating subject. If you want to learn more about the guts of how Django manages hashes, I would suggest reading the Password management in Django docs to see the details.
Is Django going to expect you to call the
and wire together all the views yourself?
You can add the set of views
with a single
# project/urls.py from django.urls import include, path urlpatterns = [ ... path("accounts/", include("django.contrib.auth.urls")), ]
This set includes a variety of features.
- A login view
- A logout view
- Views to change a password
- Views to reset a password
The All authentication views documentation provides information about each view and the name of each template to override.
We’ve now seen how Django authenticates users
to a website
and the built-in authentication backend,
We’ve also seen how Django provides views
with login, logout, and password management.
Once a user is authenticated, what is that user allowed to do? We’ll see that next as we explore authorization in Django.
Authorization From User Attributes
User model includes an
users that have authenticated will return
AnonymousUser instances return
for the same attribute.
Django provides a
that can use this
The decorator will gate any view
that needs a user to be authenticated.
There are other boolean values
that you can use for authorization checking.
is_staffis a boolean to decide whether a user is a staff member or not. By default, this boolean is
False. Only staff-level users are allowed to use the built-in Django admin site. You can also use the
staff_member_requireddecorator if you have views that should only be used by members of your team with that permission.
is_superuseris a special flag to indicate a user that should have access to everything. This “superuser” concept is very similar to the superuser that is present in Linux permission systems. There’s no special decorator for this boolean, but you could use the
user_passes_testdecorator if you had very private views that you needed to protect.
from django.contrib.admin.views.decorators import staff_member_required from django.contrib.auth.decorators import user_passes_test from django.http import HttpResponse @staff_member_required def a_staff_view(request): return HttpResponse("You are a user with staff level permission.") def check_superuser(user): return user.is_superuser @user_passes_test(check_superuser) def special_view(request): return HttpResponse("Super special response")
Authorization From Permissions And Groups
Django comes with a flexible permission system
that can let your application control
who can see what.
The permission system includes some convenient auto-created permissions
as well as the ability to make custom permission
for whatever purpose.
These permission records are
Permission model instances
If you have a
and create a
Django would create the following permissions:
from django.contrib.auth.models import Permission, User from django.contrib.contenttypes.models import ContentType from pizzas.models import Topping content_type = ContentType.objects.get_for_model(Topping) permission = Permission.objects.get( content_type=content_type, codename="add_topping") chef_id = 42 chef = User.objects.get(id=42) chef.user_permissions.add(permission)
Django has an ability to create groups
to alleviate the problem
of adding permissions
for one user at a time.
Group model is the intersection
between a set of permissions
and a set of users.
you could create a group
like “Support Team,”
assign all the permissions
that such a team should have,
and include all your support staff
on that team.
any time that the support staff members require a new permission,
it can be added once
to the group.
A user’s groups are tracked
from django.contrib.auth.models import Group, User support_team = Group.objects.get(name="Support Team") support_sally = User.objects.get(username="sally") support_sally.groups.add(support_team)
In addition to the built-in permissions that Django creates and the group management system, you can create additional permissions for your own purposes.
from django.contrib.auth.models import Permission, User from django.contrib.contenttypes.models import ContentType from pizzas.models import Pizza content_type = ContentType.objects.get_for_model(Pizza) permission = Permission.objects.create( codename="can_bake", name="Can Bake Pizza", content_type=content_type, ) chef_id = 42 chef = User.objects.get(id=42) chef.user_permissions.add(permission)
To check on the permission in our code,
you can use the
has_perm expects an application label
and the permission codename
by a period.
>>> chef = User.objects.get(id=42) >>> chef.has_perm('pizzas.can_bake') True
You can also use a decorator
on a view
to check a permission as well.
The decorator will check the
for the proper permission.
# pizzas/views.py from django.contrib.auth.decorators import permission_required @permission_required('pizzas.can_bake') def bake_pizza(request): # Time to bake the pizza if you're allowed. ...
Working With Users In Views And Templates
The first way
to interact with users
is inside of views.
Part of configuring the auth system is to include the
# application/views.py from django.http import HttpResponse def my_view(request): if request.user.is_authenticated: return HttpResponse('You are logged in.') else: return HttpResponse('Hello guest!')
How about templates? If you had to add a user to a view’s context for every view, that would be tedious.
there is a context processor
that let’s you avoid that pain
(the processor is in
The context processor will add a
to the context
of every view
when processing a request.
AuthenticationMiddleware adds the
the context processor has the very trivial job
of creating a dictionary
There’s a bit more to the actual implementation,
and you can check out the
Django source code
if you want to see those details.
Now you’ve seen how Django leverages the auth middleware to make users easily accessible to your views and templates.
In this episode, we looked into the auth system.
- How auth is set up
- What the
- How authentication works
- Django’s built-in views for making a login system
- What levels of authorization are available
- How to access users in views and templates
On the next episode, we’ll discuss middleware in Django. As the name implies, middleware is some code that exists in the “middle” of the request and response process.
Please rate or review on Apple Podcasts, Spotify, or from wherever you listen to podcasts. Your rating will help others discover the podcast, and I would be very grateful.
Django Riffs is supported by listeners like you. If you can contribute financially to cover hosting and production costs, please check out my Patreon page to see how you can help out.
Learn about Python!
You can join my newsletter along with 1,200+ other developers to help you learn more about Django and Python.