Here are additional resources about Django Middleware and sessions:
Detecting Logged-in Users
Detecting Logged-in Users and Their Roles in a View. Every Django view takes at least one argument, an
HttpRequest. The request contains state information about the user and the page they’re visiting. Here are some key pieces of information in the request.
Django has the ability to run code on every single request through a plugin mechanism called middleware. The
user attribute is added to the
HttpRequest object by the
00:33 This middleware is enabled by default when you create a new project, so you don’t have to do anything special to take advantage of it. If you’re interested in middleware, then the article Building a Django Middleware introduces these concepts.
With that in place, you can visit the address seen onscreen and see some of the request parameters. If you add a query string to the end of the URL, then you can also see how
GET works. For example, using the address seen onscreen shows that the parameters are passed as a
QueryDict in the
GET part of the request.
AnonymousUser?” you ask. The
HttpRequest.user object is always populated with something. If the visitor to your website hasn’t authenticated, then
HttpRequest.user will contain an
AnonymousUser object as seen here.
If you logged in earlier to create some data, then you might see what’s seen onscreen at the moment with details of the superuser instead. If you are logged in, then visit the address seen onscreen at the moment to log out of the admin and then revisit the page to see the difference. All user objects, including
AnonymousUser, have some attributes that give you more information about the user. To see how these work, add the following code to
With a logged-in user,
is_anonymous changes from
username attribute tells you who the user is. In this case, you’re logged in with a superuser account you created using the
manage.py createsuperuser command.
04:18 You can read more about sessions and middleware at the Django documentation site URLs seen onscreen now. Now that you can detect users and information about them, in the next section you’ll see how to start restricting access to views.
Become a Member to join the conversation.