Django uses sessions and middleware to hook the authentication system into request
objects. These provide a request.user
attribute on every request which represents the current user. If the current user has not logged in, this attribute will be set to an instance of AnonymousUser
, otherwise it will be an instance of User
. You can tell them apart with is_authenticated()
, like so:
if request.user.is_authenticated(): # Do something for authenticated users. else: # Do something for anonymous users.
To log a user in, from a view, use login()
. It takes an HttpRequest
object and a User
object. login()
saves the user's ID in the session, using Django's session framework. Note that any data set during the anonymous session is retained in the session after a user logs in. This example shows how you might use both authenticate()
and login()
:
from Django.contrib.auth import authenticate, login def my_view(request...