This document explains the usage of Django’s authentication system in its
default configuration. This configuration has evolved to serve the most common
project needs, handling a reasonably wide range of tasks, and has a careful
implementation of passwords and permissions. For projects where authentication
needs differ from the default, Django supports extensive extension and
customization of authentication.

Django authentication provides both authentication and authorization together
and is generally referred to as the authentication system, as these features
are somewhat coupled.

User objects are the core of the
authentication system. They typically represent the people interacting with
your site and are used to enable things like restricting access, registering
user profiles, associating content with creators etc. Only one class of user
exists in Django’s authentication framework, i.e., 'superusers' or admin 'staff' users are just user objects with
special attributes set, not different classes of user objects.

The most direct way to create users is to use the included
create_user() helper function:

>>> fromdjango.contrib.auth.modelsimportUser>>> user=User.objects.create_user('john','lennon@thebeatles.com','johnpassword')# At this point, user is a User object that has already been saved# to the database. You can continue to change its attributes# if you want to change other fields.>>> user.last_name='Lennon'>>> user.save()

Django does not store raw (clear text) passwords on the user model, but only
a hash (see documentation of how passwords are managed for full details). Because of this, do not attempt to
manipulate the password attribute of the user directly. This is why a helper
function is used when creating a user.

To change a user’s password, you have several options:

manage.pychangepassword*username* offers a method
of changing a user’s password from the command line. It prompts you to
change the password of a given user which you must enter twice. If
they both match, the new password will be changed immediately. If you
do not supply a user, the command will attempt to change the password
whose username matches the current system user.

You can also change a password programmatically, using
set_password():

Use authenticate() to verify a set of
credentials. It takes credentials as keyword arguments, username and
password for the default case, checks them against each
authentication backend, and returns a
User object if the credentials are
valid for a backend. If the credentials aren’t valid for any backend or if
a backend raises PermissionDenied, it
returns None. For example:

fromdjango.contrib.authimportauthenticateuser=authenticate(username='john',password='secret')ifuserisnotNone:# A backend authenticated the credentialselse:# No backend authenticated the credentials

request is an optional HttpRequest which is
passed on the authenticate() method of the authentication backends.

Changed in Django 1.11:

The optional request argument was added.

Note

This is a low level way to authenticate a set of credentials; for
example, it’s used by the
RemoteUserMiddleware. Unless
you are writing your own authentication system, you probably won’t use
this. Rather if you’re looking for a way to login a user, use the
LoginView.

When django.contrib.auth is listed in your INSTALLED_APPS
setting, it will ensure that three default permissions – add, change and
delete – are created for each Django model defined in one of your installed
applications.

These permissions will be created when you run manage.pymigrate; the first time you run migrate after adding
django.contrib.auth to INSTALLED_APPS, the default permissions
will be created for all previously-installed models, as well as for any new
models being installed at that time. Afterward, it will create default
permissions for new models each time you run manage.pymigrate (the function that creates permissions is connected to the
post_migrate signal).

Assuming you have an application with an
app_labelfoo and a model named Bar,
to test for basic permissions you should use:

django.contrib.auth.models.Group models are a generic way of
categorizing users so you can apply permissions, or some other label, to those
users. A user can belong to any number of groups.

A user in a group automatically has the permissions granted to that group. For
example, if the group Siteeditors has the permission
can_edit_home_page, any user in that group will have that permission.

Beyond permissions, groups are a convenient way to categorize users to give
them some label, or extended functionality. For example, you could create a
group 'Specialusers', and you could write code that could, say, give them
access to a members-only portion of your site, or send them members-only email
messages.

The ModelBackend caches permissions on
the user object after the first time they need to be fetched for a permissions
check. This is typically fine for the request-response cycle since permissions
aren’t typically checked immediately after they are added (in the admin, for
example). If you are adding permissions and checking them immediately
afterward, in a test or view for example, the easiest solution is to re-fetch
the user from the database. For example:

fromdjango.contrib.auth.modelsimportPermission,Userfromdjango.contrib.contenttypes.modelsimportContentTypefromdjango.shortcutsimportget_object_or_404frommyapp.modelsimportBlogPostdefuser_gains_perms(request,user_id):user=get_object_or_404(User,pk=user_id)# any permission check will cache the current set of permissionsuser.has_perm('myapp.change_blogpost')content_type=ContentType.objects.get_for_model(BlogPost)permission=Permission.objects.get(codename='change_blogpost',content_type=content_type,)user.user_permissions.add(permission)# Checking the cached permission setuser.has_perm('myapp.change_blogpost')# False# Request new instance of User# Be aware that user.refresh_from_db() won't clear the cache.user=get_object_or_404(User,pk=user_id)# Permission cache is repopulated from the databaseuser.has_perm('myapp.change_blogpost')# True...

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.

When a user logs in, the user’s ID and the backend that was used for
authentication are saved in the user’s session. This allows the same
authentication backend to fetch the user’s
details on a future request. The authentication backend to save in the session
is selected as follows:

Use the value of the optional backend argument, if provided.

Use the value of the user.backend attribute, if present. This allows
pairing authenticate() and
login():
authenticate()
sets the user.backend attribute on the user object it returns.

fromdjango.contrib.authimportlogoutdeflogout_view(request):logout(request)# Redirect to a success page.

Note that logout() doesn’t throw any errors if
the user wasn’t logged in.

When you call logout(), the session data for
the current request is completely cleaned out. All existing data is
removed. This is to prevent another person from using the same Web browser
to log in and have access to the previous user’s session data. If you want
to put anything into the session that will be available to the user
immediately after logging out, do that after calling
django.contrib.auth.logout().

If the user isn’t logged in, redirect to
settings.LOGIN_URL, passing the current absolute
path in the query string. Example: /accounts/login/?next=/polls/3/.

If the user is logged in, execute the view normally. The view code is
free to assume the user is logged in.

By default, the path that the user should be redirected to upon
successful authentication is stored in a query string parameter called
"next". If you would prefer to use a different name for this parameter,
login_required() takes an
optional redirect_field_name parameter:

Note that if you provide a value to redirect_field_name, you will most
likely need to customize your login template as well, since the template
context variable which stores the redirect path will use the value of
redirect_field_name as its key rather than "next" (the default).

Note that if you don’t specify the login_url parameter, you’ll need to
ensure that the settings.LOGIN_URL and your login
view are properly associated. For example, using the defaults, add the
following lines to your URLconf:

user_passes_test() takes a required
argument: a callable that takes a
User object and returns True if
the user is allowed to view the page. Note that
user_passes_test() does not
automatically check that the User is
not anonymous.

Lets you specify the URL that users who don’t pass the test will be
redirected to. It may be a login page and defaults to
settings.LOGIN_URL if you don’t specify one.

redirect_field_name

Same as for login_required().
Setting it to None removes it from the URL, which you may want to do
if you are redirecting users that don’t pass the test to a non-login
page where there’s no “next page”.

You have to override the test_func() method of the class to
provide the test that is performed. Furthermore, you can set any of the
parameters of AccessMixin to
customize the handling of unauthorized users:

This mixin, just like the permission_required
decorator, checks whether the user accessing a view has all given
permissions. You should specify the permission (or an iterable of
permissions) using the permission_required parameter:

fromdjango.contrib.auth.mixinsimportPermissionRequiredMixinclassMyView(PermissionRequiredMixin,View):permission_required='polls.can_vote'# Or multiple of permissions:permission_required=('polls.can_open','polls.can_edit')

You can set any of the parameters of
AccessMixin to customize the handling
of unauthorized users.

Returns a boolean denoting whether the current user has permission to
execute the decorated view. By default, this returns the result of
calling has_perms() with the
list of permissions returned by get_permission_required().

Returns the name of the query parameter that will contain the URL the
user should be redirected to after a successful login. If you set this
to None, a query parameter won’t be added. Returns the
redirect_field_name attribute by default.

If your AUTH_USER_MODEL inherits from
AbstractBaseUser or implements its own
get_session_auth_hash()
method, authenticated sessions will include the hash returned by this function.
In the AbstractBaseUser case, this is an
HMAC of the password field. Django verifies that the hash in the session for
each request matches the one that’s computed during the request. This allows a
user to log out all of their sessions by changing their password.

The default password change views included with Django,
PasswordChangeView and the
user_change_password view in the django.contrib.auth admin, update
the session with the new password hash so that a user changing their own
password won’t log themselves out. If you have a custom password change view
and wish to have similar behavior, use the update_session_auth_hash()
function.

This function takes the current request and the updated user object from
which the new session hash will be derived and updates the session hash
appropriately. It also rotates the session key so that a stolen session
cookie will be invalidated.

Django provides several views that you can use for handling login, logout, and
password management. These make use of the stock auth forms but you can pass in your own forms as well.

Django provides no default template for the authentication views. You should
create your own templates for the views you want to use. The template context
is documented in each view, see All authentication views.

The views have optional arguments you can use to alter the behavior of the
view. For example, if you want to change the template name a view uses, you can
provide the template_name argument. A way to do this is to provide keyword
arguments in the URLconf, these will be passed on to the view. For example:

template_name: The name of a template to display for the view used to
log the user in. Defaults to registration/login.html.

redirect_field_name: The name of a GET field containing the
URL to redirect to after login. Defaults to next.

authentication_form: A callable (typically just a form class) to
use for authentication. Defaults to
AuthenticationForm.

extra_context: A dictionary of context data that will be added to the
default context data passed to the template.

redirect_authenticated_user: A boolean that controls whether or not
authenticated users accessing the login page will be redirected as if
they had just successfully logged in. Defaults to False.

Warning

If you enable redirect_authenticated_user, other websites will be
able to determine if their visitors are authenticated on your site by
requesting redirect URLs to image files on your website. To avoid
this “social media fingerprinting” information
leakage, host all images and your favicon on a separate domain.

success_url_allowed_hosts: A set of hosts, in addition to
request.get_host(), that are
safe for redirecting after login. Defaults to an empty set.

Here’s what LoginView does:

If called via GET, it displays a login form that POSTs to the
same URL. More on this in a bit.

If called via POST with user submitted credentials, it tries to log
the user in. If login is successful, the view redirects to the URL
specified in next. If next isn’t provided, it redirects to
settings.LOGIN_REDIRECT_URL (which
defaults to /accounts/profile/). If login isn’t successful, it
redisplays the login form.

It’s your responsibility to provide the html for the login template
, called registration/login.html by default. This template gets passed
four template context variables:

next: The URL to redirect to after successful login. This may
contain a query string, too.

site: The current Site,
according to the SITE_ID setting. If you don’t have the
site framework installed, this will be set to an instance of
RequestSite, which derives the
site name and domain from the current
HttpRequest.

If you’d prefer not to call the template registration/login.html,
you can pass the template_name parameter via the extra arguments to
the as_view method in your URLconf. For example, this URLconf line would
use myapp/login.html instead:

You can also specify the name of the GET field which contains the URL
to redirect to after login using redirect_field_name. By default, the
field is called next.

Here’s a sample registration/login.html template you can use as a
starting point. It assumes you have a base.html template that
defines a content block:

{%extends"base.html"%}{%blockcontent%}{%ifform.errors%}<p>Your username and password didn't match. Please try again.</p>{%endif%}{%ifnext%}{%ifuser.is_authenticated%}<p>Your account doesn't have access to this page. To proceed,
please login with an account that has access.</p>{%else%}<p>Please login to see this page.</p>{%endif%}{%endif%}<formmethod="post"action="{%url'login'%}">{%csrf_token%}<table><tr><td>{{form.username.label_tag}}</td><td>{{form.username}}</td></tr><tr><td>{{form.password.label_tag}}</td><td>{{form.password}}</td></tr></table><inputtype="submit"value="login"/><inputtype="hidden"name="next"value="{{next}}"/></form>{# Assumes you setup the password_reset view in your URLconf #}<p><ahref="{%url'password_reset'%}">Lost password?</a></p>{%endblock%}

If you have customized authentication (see Customizing Authentication) you can use a custom authentication form by
setting the authentication_form attribute. This form must accept a
request keyword argument in its __init__() method and provide a
get_user() method which returns the authenticated user object (this
method is only ever called after successful form validation).

template_name: The full name of a template to display after
logging the user out. Defaults to registration/logged_out.html.

redirect_field_name: The name of a GET field containing the
URL to redirect to after log out. Defaults to next. Overrides the
next_page URL if the given GET parameter is passed.

extra_context: A dictionary of context data that will be added to the
default context data passed to the template.

success_url_allowed_hosts: A set of hosts, in addition to
request.get_host(), that are
safe for redirecting after logout. Defaults to an empty set.

Template context:

title: The string “Logged out”, localized.

site: The current Site,
according to the SITE_ID setting. If you don’t have the
site framework installed, this will be set to an instance of
RequestSite, which derives the
site name and domain from the current
HttpRequest.

Deprecated since version 1.11: The password_change function-based view should be replaced by the
class-based PasswordChangeView.

The optional arguments of this view are similar to the class-based
PasswordChangeView attributes, except the post_change_redirect and
password_change_form arguments which map to the success_url and
form_class attributes of the class-based view.

Deprecated since version 1.11: The password_reset function-based view should be replaced by the
class-based PasswordResetView.

The optional arguments of this view are similar to the class-based
PasswordResetView attributes, except the post_reset_redirect and
password_reset_form arguments which map to the success_url and
form_class attributes of the class-based view.

Allows a user to reset their password by generating a one-time use link
that can be used to reset the password, and sending that link to the
user’s registered email address.

If the email address provided does not exist in the system, this view
won’t send an email, but the user won’t receive any error message either.
This prevents information leaking to potential attackers. If you want to
provide an error message in this case, you can subclass
PasswordResetForm and use the
form_class attribute.

Users flagged with an unusable password (see
set_unusable_password() aren’t
allowed to request a password reset to prevent misuse when using an
external authentication source like LDAP. Note that they won’t receive any
error message since this would expose their account’s existence but no
mail will be sent either.

Attributes:

template_name: The full name of a template to use for
displaying the password reset form. Defaults to
registration/password_reset_form.html if not supplied.

form_class: Form that will be used to get the email of
the user to reset the password for. Defaults to
PasswordResetForm.

email_template_name: The full name of a template to use for
generating the email with the reset password link. Defaults to
registration/password_reset_email.html if not supplied.

subject_template_name: The full name of a template to use for
the subject of the email with the reset password link. Defaults
to registration/password_reset_subject.txt if not supplied.

token_generator: Instance of the class to check the one time link.
This will default to default_token_generator, it’s an instance of
django.contrib.auth.tokens.PasswordResetTokenGenerator.

success_url: The URL to redirect to after a successful password reset
request.

Deprecated since version 1.11: The password_reset_confirm function-based view should be replaced by
the class-based PasswordResetConfirmView.

The optional arguments of this view are similar to the class-based
PasswordResetConfirmView attributes, except the post_reset_redirect
and set_password_form arguments which map to the success_url and
form_class attributes of the class-based view.

template_name: The full name of a template to display the confirm
password view. Default value is
registration/password_reset_confirm.html.

token_generator: Instance of the class to check the password. This
will default to default_token_generator, it’s an instance of
django.contrib.auth.tokens.PasswordResetTokenGenerator.

post_reset_login: A boolean indicating if the user should be
automatically authenticated after a successful password reset. Defaults
to False.

post_reset_login_backend: A dotted path to the authentication
backend to use when authenticating a user if post_reset_login is
True. Required only if you have multiple
AUTHENTICATION_BACKENDS configured. Defaults to None.

form_class: Form that will be used to set the password. Defaults to
SetPasswordForm.

success_url: URL to redirect after the password reset done. Defaults
to 'password_reset_complete'.

extra_context: A dictionary of context data that will be added to the
default context data passed to the template.

Template context:

form: The form (see set_password_form above) for setting the
new user’s password.

validlink: Boolean, True if the link (combination of uidb64 and
token) is valid or unused yet.

If you don’t want to use the built-in views, but want the convenience of not
having to write forms for this functionality, the authentication system
provides several built-in forms located in django.contrib.auth.forms:

By default, AuthenticationForm rejects users whose is_active
flag is set to False. You may override this behavior with a custom
policy to determine which users can log in. Do this with a custom form
that subclasses AuthenticationForm and overrides the
confirm_login_allowed() method. This method should raise a
ValidationError if the given user may
not log in.

For example, to allow all users to log in regardless of “active”
status:

It has three fields: username (from the user model), password1,
and password2. It verifies that password1 and password2 match,
validates the password using
validate_password(), and
sets the user’s password using
set_password().

Technically, these variables are only made available in the template
context if you use RequestContext and the
'django.contrib.auth.context_processors.auth' context processor is
enabled. It is in the default generated settings file. For more, see the
RequestContext docs.

The currently logged-in user’s permissions are stored in the template variable
{{perms}}. This is an instance of
django.contrib.auth.context_processors.PermWrapper, which is a
template-friendly proxy of permissions.

Evaluating a single-attribute lookup of {{perms}} as a boolean is a proxy
to User.has_module_perms(). For example, to check if
the logged-in user has any permissions in the foo app:

{%ifperms.foo%}

Evaluating a two-level-attribute lookup as a boolean is a proxy to
User.has_perm(). For example,
to check if the logged-in user has the permission foo.can_vote:

{%ifperms.foo.can_vote%}

Here’s a more complete example of checking permissions in a template:

{%ifperms.foo%}<p>You have permission to do something in the foo app.</p>{%ifperms.foo.can_vote%}<p>You can vote!</p>{%endif%}{%ifperms.foo.can_drive%}<p>You can drive!</p>{%endif%}{%else%}<p>You don't have permission to do anything in the foo app.</p>{%endif%}

It is possible to also look permissions up by {%ifin%} statements.
For example:

When you have both django.contrib.admin and django.contrib.auth
installed, the admin provides a convenient way to view and manage users,
groups, and permissions. Users can be created and deleted like any Django
model. Groups can be created, and permissions can be assigned to users or
groups. A log of user edits to models made within the admin is also stored and
displayed.

You should see a link to “Users” in the “Auth”
section of the main admin index page. The “Add user” admin page is different
than standard admin pages in that it requires you to choose a username and
password before allowing you to edit the rest of the user’s fields.

Also note: if you want a user account to be able to create users using the
Django admin site, you’ll need to give them permission to add users and
change users (i.e., the “Add user” and “Change user” permissions). If an
account has permission to add users but not to change them, that account won’t
be able to add users. Why? Because if you have permission to add users, you
have the power to create superusers, which can then, in turn, change other
users. So Django requires add and change permissions as a slight security
measure.

Be thoughtful about how you allow users to manage permissions. If you give a
non-superuser the ability to edit users, this is ultimately the same as giving
them superuser status because they will be able to elevate permissions of
users including themselves!

User passwords are not displayed in the admin (nor stored in the database), but
the password storage details are displayed.
Included in the display of this information is a link to
a password change form that allows admins to change user passwords.