<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang=""> <head> <meta http-equiv="X-UA-Compatible" content="IE=Edge" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Using the Django authentication system — Django 1.11.20 documentation</title> <link rel="stylesheet" href="../../_static/default.css" type="text/css" /> <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" /> <script type="text/javascript" id="documentation_options" data-url_root="../../" src="../../_static/documentation_options.js"></script> <script type="text/javascript" src="../../_static/jquery.js"></script> <script type="text/javascript" src="../../_static/underscore.js"></script> <script type="text/javascript" src="../../_static/doctools.js"></script> <script type="text/javascript" src="../../_static/language_data.js"></script> <link rel="index" title="Index" href="../../genindex.html" /> <link rel="search" title="Search" href="../../search.html" /> <link rel="next" title="Password management in Django" href="passwords.html" /> <link rel="prev" title="User authentication in Django" href="index.html" /> <script type="text/javascript" src="../../templatebuiltins.js"></script> <script type="text/javascript"> (function($) { if (!django_template_builtins) { // templatebuiltins.js missing, do nothing. return; } $(document).ready(function() { // Hyperlink Django template tags and filters var base = "../../ref/templates/builtins.html"; if (base == "#") { // Special case for builtins.html itself base = ""; } // Tags are keywords, class '.k' $("div.highlight\\-html\\+django span.k").each(function(i, elem) { var tagname = $(elem).text(); if ($.inArray(tagname, django_template_builtins.ttags) != -1) { var fragment = tagname.replace(/_/, '-'); $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>"); } }); // Filters are functions, class '.nf' $("div.highlight\\-html\\+django span.nf").each(function(i, elem) { var filtername = $(elem).text(); if ($.inArray(filtername, django_template_builtins.tfilters) != -1) { var fragment = filtername.replace(/_/, '-'); $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>"); } }); }); })(jQuery); </script> </head><body> <div class="document"> <div id="custom-doc" class="yui-t6"> <div id="hd"> <h1><a href="../../index.html">Django 1.11.20 documentation</a></h1> <div id="global-nav"> <a title="Home page" href="../../index.html">Home</a> | <a title="Table of contents" href="../../contents.html">Table of contents</a> | <a title="Global index" href="../../genindex.html">Index</a> | <a title="Module index" href="../../py-modindex.html">Modules</a> </div> <div class="nav"> « <a href="index.html" title="User authentication in Django">previous</a> | <a href="../index.html" title="Using Django" accesskey="U">up</a> | <a href="passwords.html" title="Password management in Django">next</a> »</div> </div> <div id="bd"> <div id="yui-main"> <div class="yui-b"> <div class="yui-g" id="topics-auth-default"> <div class="section" id="s-using-the-django-authentication-system"> <span id="using-the-django-authentication-system"></span><h1>Using the Django authentication system<a class="headerlink" href="#using-the-django-authentication-system" title="Permalink to this headline">¶</a></h1> <p>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 <a class="reference internal" href="customizing.html"><span class="doc">extension and customization</span></a> of authentication.</p> <p>Django authentication provides both authentication and authorization together and is generally referred to as the authentication system, as these features are somewhat coupled.</p> <div class="section" id="s-user-objects"> <span id="s-id1"></span><span id="user-objects"></span><span id="id1"></span><h2><code class="docutils literal notranslate"><span class="pre">User</span></code> objects<a class="headerlink" href="#user-objects" title="Permalink to this headline">¶</a></h2> <p><a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User" title="django.contrib.auth.models.User"><code class="xref py py-class docutils literal notranslate"><span class="pre">User</span></code></a> 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., <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User.is_superuser" title="django.contrib.auth.models.User.is_superuser"><code class="xref py py-attr docutils literal notranslate"><span class="pre">'superusers'</span></code></a> or admin <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User.is_staff" title="django.contrib.auth.models.User.is_staff"><code class="xref py py-attr docutils literal notranslate"><span class="pre">'staff'</span></code></a> users are just user objects with special attributes set, not different classes of user objects.</p> <p>The primary attributes of the default user are:</p> <ul class="simple"> <li><a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User.username" title="django.contrib.auth.models.User.username"><code class="xref py py-attr docutils literal notranslate"><span class="pre">username</span></code></a></li> <li><a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User.password" title="django.contrib.auth.models.User.password"><code class="xref py py-attr docutils literal notranslate"><span class="pre">password</span></code></a></li> <li><a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User.email" title="django.contrib.auth.models.User.email"><code class="xref py py-attr docutils literal notranslate"><span class="pre">email</span></code></a></li> <li><a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User.first_name" title="django.contrib.auth.models.User.first_name"><code class="xref py py-attr docutils literal notranslate"><span class="pre">first_name</span></code></a></li> <li><a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User.last_name" title="django.contrib.auth.models.User.last_name"><code class="xref py py-attr docutils literal notranslate"><span class="pre">last_name</span></code></a></li> </ul> <p>See the <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User" title="django.contrib.auth.models.User"><code class="xref py py-class docutils literal notranslate"><span class="pre">full</span> <span class="pre">API</span> <span class="pre">documentation</span></code></a> for full reference, the documentation that follows is more task oriented.</p> <div class="section" id="s-creating-users"> <span id="s-topics-auth-creating-users"></span><span id="creating-users"></span><span id="topics-auth-creating-users"></span><h3>Creating users<a class="headerlink" href="#creating-users" title="Permalink to this headline">¶</a></h3> <p>The most direct way to create users is to use the included <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.UserManager.create_user" title="django.contrib.auth.models.UserManager.create_user"><code class="xref py py-meth docutils literal notranslate"><span class="pre">create_user()</span></code></a> helper function:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">django.contrib.auth.models</span> <span class="k">import</span> <span class="n">User</span> <span class="gp">>>> </span><span class="n">user</span> <span class="o">=</span> <span class="n">User</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create_user</span><span class="p">(</span><span class="s1">'john'</span><span class="p">,</span> <span class="s1">'lennon@thebeatles.com'</span><span class="p">,</span> <span class="s1">'johnpassword'</span><span class="p">)</span> <span class="go"># At this point, user is a User object that has already been saved</span> <span class="go"># to the database. You can continue to change its attributes</span> <span class="go"># if you want to change other fields.</span> <span class="gp">>>> </span><span class="n">user</span><span class="o">.</span><span class="n">last_name</span> <span class="o">=</span> <span class="s1">'Lennon'</span> <span class="gp">>>> </span><span class="n">user</span><span class="o">.</span><span class="n">save</span><span class="p">()</span> </pre></div> </div> <p>If you have the Django admin installed, you can also <a class="reference internal" href="#auth-admin"><span class="std std-ref">create users interactively</span></a>.</p> </div> <div class="section" id="s-creating-superusers"> <span id="s-topics-auth-creating-superusers"></span><span id="creating-superusers"></span><span id="topics-auth-creating-superusers"></span><h3>Creating superusers<a class="headerlink" href="#creating-superusers" title="Permalink to this headline">¶</a></h3> <p>Create superusers using the <a class="reference internal" href="../../ref/django-admin.html#django-admin-createsuperuser"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">createsuperuser</span></code></a> command:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span>$ python manage.py createsuperuser --username=joe --email=joe@example.com </pre></div> </div> <p>You will be prompted for a password. After you enter one, the user will be created immediately. If you leave off the <a class="reference internal" href="../../ref/django-admin.html#cmdoption-createsuperuser-username"><code class="xref std std-option docutils literal notranslate"><span class="pre">--username</span></code></a> or <a class="reference internal" href="../../ref/django-admin.html#cmdoption-createsuperuser-email"><code class="xref std std-option docutils literal notranslate"><span class="pre">--email</span></code></a> options, it will prompt you for those values.</p> </div> <div class="section" id="s-changing-passwords"> <span id="changing-passwords"></span><h3>Changing passwords<a class="headerlink" href="#changing-passwords" title="Permalink to this headline">¶</a></h3> <p>Django does not store raw (clear text) passwords on the user model, but only a hash (see <a class="reference internal" href="passwords.html"><span class="doc">documentation of how passwords are managed</span></a> 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.</p> <p>To change a user’s password, you have several options:</p> <p><a class="reference internal" href="../../ref/django-admin.html#django-admin-changepassword"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">manage.py</span> <span class="pre">changepassword</span> <span class="pre">*username*</span></code></a> 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.</p> <p>You can also change a password programmatically, using <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User.set_password" title="django.contrib.auth.models.User.set_password"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_password()</span></code></a>:</p> <div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span> <span class="nn">django.contrib.auth.models</span> <span class="kn">import</span> <span class="n">User</span> <span class="gp">>>> </span><span class="n">u</span> <span class="o">=</span> <span class="n">User</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">username</span><span class="o">=</span><span class="s1">'john'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">u</span><span class="o">.</span><span class="n">set_password</span><span class="p">(</span><span class="s1">'new password'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">u</span><span class="o">.</span><span class="n">save</span><span class="p">()</span> </pre></div> </div> <p>If you have the Django admin installed, you can also change user’s passwords on the <a class="reference internal" href="#auth-admin"><span class="std std-ref">authentication system’s admin pages</span></a>.</p> <p>Django also provides <a class="reference internal" href="#built-in-auth-views"><span class="std std-ref">views</span></a> and <a class="reference internal" href="#built-in-auth-forms"><span class="std std-ref">forms</span></a> that may be used to allow users to change their own passwords.</p> <p>Changing a user’s password will log out all their sessions. See <a class="reference internal" href="#session-invalidation-on-password-change"><span class="std std-ref">Session invalidation on password change</span></a> for details.</p> </div> <div class="section" id="s-authenticating-users"> <span id="authenticating-users"></span><h3>Authenticating users<a class="headerlink" href="#authenticating-users" title="Permalink to this headline">¶</a></h3> <dl class="function"> <dt id="django.contrib.auth.authenticate"> <code class="descname">authenticate</code>(<em>request=None</em>, <em>**credentials</em>)<a class="reference internal" href="../../_modules/django/contrib/auth.html#authenticate"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.contrib.auth.authenticate" title="Permalink to this definition">¶</a></dt> <dd><p>Use <a class="reference internal" href="#django.contrib.auth.authenticate" title="django.contrib.auth.authenticate"><code class="xref py py-func docutils literal notranslate"><span class="pre">authenticate()</span></code></a> to verify a set of credentials. It takes credentials as keyword arguments, <code class="docutils literal notranslate"><span class="pre">username</span></code> and <code class="docutils literal notranslate"><span class="pre">password</span></code> for the default case, checks them against each <a class="reference internal" href="customizing.html#authentication-backends"><span class="std std-ref">authentication backend</span></a>, and returns a <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User" title="django.contrib.auth.models.User"><code class="xref py py-class docutils literal notranslate"><span class="pre">User</span></code></a> object if the credentials are valid for a backend. If the credentials aren’t valid for any backend or if a backend raises <a class="reference internal" href="../../ref/exceptions.html#django.core.exceptions.PermissionDenied" title="django.core.exceptions.PermissionDenied"><code class="xref py py-class docutils literal notranslate"><span class="pre">PermissionDenied</span></code></a>, it returns <code class="docutils literal notranslate"><span class="pre">None</span></code>. For example:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.contrib.auth</span> <span class="k">import</span> <span class="n">authenticate</span> <span class="n">user</span> <span class="o">=</span> <span class="n">authenticate</span><span class="p">(</span><span class="n">username</span><span class="o">=</span><span class="s1">'john'</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="s1">'secret'</span><span class="p">)</span> <span class="k">if</span> <span class="n">user</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span> <span class="c1"># A backend authenticated the credentials</span> <span class="k">else</span><span class="p">:</span> <span class="c1"># No backend authenticated the credentials</span> </pre></div> </div> <p><code class="docutils literal notranslate"><span class="pre">request</span></code> is an optional <a class="reference internal" href="../../ref/request-response.html#django.http.HttpRequest" title="django.http.HttpRequest"><code class="xref py py-class docutils literal notranslate"><span class="pre">HttpRequest</span></code></a> which is passed on the <code class="docutils literal notranslate"><span class="pre">authenticate()</span></code> method of the authentication backends.</p> <div class="versionchanged"> <span class="title">Changed in Django 1.11:</span> <p>The optional <code class="docutils literal notranslate"><span class="pre">request</span></code> argument was added.</p> </div> <div class="admonition note"> <p class="first admonition-title">Note</p> <p class="last">This is a low level way to authenticate a set of credentials; for example, it’s used by the <a class="reference internal" href="../../ref/middleware.html#django.contrib.auth.middleware.RemoteUserMiddleware" title="django.contrib.auth.middleware.RemoteUserMiddleware"><code class="xref py py-class docutils literal notranslate"><span class="pre">RemoteUserMiddleware</span></code></a>. Unless you are writing your own authentication system, you probably won’t use this. Rather if you are looking for a way to limit access to logged in users, see the <a class="reference internal" href="#django.contrib.auth.decorators.login_required" title="django.contrib.auth.decorators.login_required"><code class="xref py py-func docutils literal notranslate"><span class="pre">login_required()</span></code></a> decorator.</p> </div> </dd></dl> </div> </div> <div class="section" id="s-permissions-and-authorization"> <span id="s-topic-authorization"></span><span id="permissions-and-authorization"></span><span id="topic-authorization"></span><h2>Permissions and Authorization<a class="headerlink" href="#permissions-and-authorization" title="Permalink to this headline">¶</a></h2> <p>Django comes with a simple permissions system. It provides a way to assign permissions to specific users and groups of users.</p> <p>It’s used by the Django admin site, but you’re welcome to use it in your own code.</p> <p>The Django admin site uses permissions as follows:</p> <ul class="simple"> <li>Access to view the “add” form and add an object is limited to users with the “add” permission for that type of object.</li> <li>Access to view the change list, view the “change” form and change an object is limited to users with the “change” permission for that type of object.</li> <li>Access to delete an object is limited to users with the “delete” permission for that type of object.</li> </ul> <p>Permissions can be set not only per type of object, but also per specific object instance. By using the <a class="reference internal" href="../../ref/contrib/admin/index.html#django.contrib.admin.ModelAdmin.has_add_permission" title="django.contrib.admin.ModelAdmin.has_add_permission"><code class="xref py py-meth docutils literal notranslate"><span class="pre">has_add_permission()</span></code></a>, <a class="reference internal" href="../../ref/contrib/admin/index.html#django.contrib.admin.ModelAdmin.has_change_permission" title="django.contrib.admin.ModelAdmin.has_change_permission"><code class="xref py py-meth docutils literal notranslate"><span class="pre">has_change_permission()</span></code></a> and <a class="reference internal" href="../../ref/contrib/admin/index.html#django.contrib.admin.ModelAdmin.has_delete_permission" title="django.contrib.admin.ModelAdmin.has_delete_permission"><code class="xref py py-meth docutils literal notranslate"><span class="pre">has_delete_permission()</span></code></a> methods provided by the <a class="reference internal" href="../../ref/contrib/admin/index.html#django.contrib.admin.ModelAdmin" title="django.contrib.admin.ModelAdmin"><code class="xref py py-class docutils literal notranslate"><span class="pre">ModelAdmin</span></code></a> class, it is possible to customize permissions for different object instances of the same type.</p> <p><a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User" title="django.contrib.auth.models.User"><code class="xref py py-class docutils literal notranslate"><span class="pre">User</span></code></a> objects have two many-to-many fields: <code class="docutils literal notranslate"><span class="pre">groups</span></code> and <code class="docutils literal notranslate"><span class="pre">user_permissions</span></code>. <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User" title="django.contrib.auth.models.User"><code class="xref py py-class docutils literal notranslate"><span class="pre">User</span></code></a> objects can access their related objects in the same way as any other <a class="reference internal" href="../db/models.html"><span class="doc">Django model</span></a>:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">myuser</span><span class="o">.</span><span class="n">groups</span><span class="o">.</span><span class="n">set</span><span class="p">([</span><span class="n">group_list</span><span class="p">])</span> <span class="n">myuser</span><span class="o">.</span><span class="n">groups</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">group</span><span class="p">,</span> <span class="n">group</span><span class="p">,</span> <span class="o">...</span><span class="p">)</span> <span class="n">myuser</span><span class="o">.</span><span class="n">groups</span><span class="o">.</span><span class="n">remove</span><span class="p">(</span><span class="n">group</span><span class="p">,</span> <span class="n">group</span><span class="p">,</span> <span class="o">...</span><span class="p">)</span> <span class="n">myuser</span><span class="o">.</span><span class="n">groups</span><span class="o">.</span><span class="n">clear</span><span class="p">()</span> <span class="n">myuser</span><span class="o">.</span><span class="n">user_permissions</span><span class="o">.</span><span class="n">set</span><span class="p">([</span><span class="n">permission_list</span><span class="p">])</span> <span class="n">myuser</span><span class="o">.</span><span class="n">user_permissions</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">permission</span><span class="p">,</span> <span class="n">permission</span><span class="p">,</span> <span class="o">...</span><span class="p">)</span> <span class="n">myuser</span><span class="o">.</span><span class="n">user_permissions</span><span class="o">.</span><span class="n">remove</span><span class="p">(</span><span class="n">permission</span><span class="p">,</span> <span class="n">permission</span><span class="p">,</span> <span class="o">...</span><span class="p">)</span> <span class="n">myuser</span><span class="o">.</span><span class="n">user_permissions</span><span class="o">.</span><span class="n">clear</span><span class="p">()</span> </pre></div> </div> <div class="section" id="s-default-permissions"> <span id="default-permissions"></span><h3>Default permissions<a class="headerlink" href="#default-permissions" title="Permalink to this headline">¶</a></h3> <p>When <code class="docutils literal notranslate"><span class="pre">django.contrib.auth</span></code> is listed in your <a class="reference internal" href="../../ref/settings.html#std:setting-INSTALLED_APPS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">INSTALLED_APPS</span></code></a> 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.</p> <p>These permissions will be created when you run <a class="reference internal" href="../../ref/django-admin.html#django-admin-migrate"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">manage.py</span> <span class="pre">migrate</span></code></a>; the first time you run <code class="docutils literal notranslate"><span class="pre">migrate</span></code> after adding <code class="docutils literal notranslate"><span class="pre">django.contrib.auth</span></code> to <a class="reference internal" href="../../ref/settings.html#std:setting-INSTALLED_APPS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">INSTALLED_APPS</span></code></a>, 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 <a class="reference internal" href="../../ref/django-admin.html#django-admin-migrate"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">manage.py</span> <span class="pre">migrate</span></code></a> (the function that creates permissions is connected to the <a class="reference internal" href="../../ref/signals.html#django.db.models.signals.post_migrate" title="django.db.models.signals.post_migrate"><code class="xref py py-data docutils literal notranslate"><span class="pre">post_migrate</span></code></a> signal).</p> <p>Assuming you have an application with an <a class="reference internal" href="../../ref/models/options.html#django.db.models.Options.app_label" title="django.db.models.Options.app_label"><code class="xref py py-attr docutils literal notranslate"><span class="pre">app_label</span></code></a> <code class="docutils literal notranslate"><span class="pre">foo</span></code> and a model named <code class="docutils literal notranslate"><span class="pre">Bar</span></code>, to test for basic permissions you should use:</p> <ul class="simple"> <li>add: <code class="docutils literal notranslate"><span class="pre">user.has_perm('foo.add_bar')</span></code></li> <li>change: <code class="docutils literal notranslate"><span class="pre">user.has_perm('foo.change_bar')</span></code></li> <li>delete: <code class="docutils literal notranslate"><span class="pre">user.has_perm('foo.delete_bar')</span></code></li> </ul> <p>The <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.Permission" title="django.contrib.auth.models.Permission"><code class="xref py py-class docutils literal notranslate"><span class="pre">Permission</span></code></a> model is rarely accessed directly.</p> </div> <div class="section" id="s-groups"> <span id="groups"></span><h3>Groups<a class="headerlink" href="#groups" title="Permalink to this headline">¶</a></h3> <p><a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.Group" title="django.contrib.auth.models.Group"><code class="xref py py-class docutils literal notranslate"><span class="pre">django.contrib.auth.models.Group</span></code></a> 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.</p> <p>A user in a group automatically has the permissions granted to that group. For example, if the group <code class="docutils literal notranslate"><span class="pre">Site</span> <span class="pre">editors</span></code> has the permission <code class="docutils literal notranslate"><span class="pre">can_edit_home_page</span></code>, any user in that group will have that permission.</p> <p>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 <code class="docutils literal notranslate"><span class="pre">'Special</span> <span class="pre">users'</span></code>, 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.</p> </div> <div class="section" id="s-programmatically-creating-permissions"> <span id="programmatically-creating-permissions"></span><h3>Programmatically creating permissions<a class="headerlink" href="#programmatically-creating-permissions" title="Permalink to this headline">¶</a></h3> <p>While <a class="reference internal" href="customizing.html#custom-permissions"><span class="std std-ref">custom permissions</span></a> can be defined within a model’s <code class="docutils literal notranslate"><span class="pre">Meta</span></code> class, you can also create permissions directly. For example, you can create the <code class="docutils literal notranslate"><span class="pre">can_publish</span></code> permission for a <code class="docutils literal notranslate"><span class="pre">BlogPost</span></code> model in <code class="docutils literal notranslate"><span class="pre">myapp</span></code>:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">myapp.models</span> <span class="k">import</span> <span class="n">BlogPost</span> <span class="kn">from</span> <span class="nn">django.contrib.auth.models</span> <span class="k">import</span> <span class="n">Permission</span> <span class="kn">from</span> <span class="nn">django.contrib.contenttypes.models</span> <span class="k">import</span> <span class="n">ContentType</span> <span class="n">content_type</span> <span class="o">=</span> <span class="n">ContentType</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get_for_model</span><span class="p">(</span><span class="n">BlogPost</span><span class="p">)</span> <span class="n">permission</span> <span class="o">=</span> <span class="n">Permission</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span> <span class="n">codename</span><span class="o">=</span><span class="s1">'can_publish'</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s1">'Can Publish Posts'</span><span class="p">,</span> <span class="n">content_type</span><span class="o">=</span><span class="n">content_type</span><span class="p">,</span> <span class="p">)</span> </pre></div> </div> <p>The permission can then be assigned to a <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User" title="django.contrib.auth.models.User"><code class="xref py py-class docutils literal notranslate"><span class="pre">User</span></code></a> via its <code class="docutils literal notranslate"><span class="pre">user_permissions</span></code> attribute or to a <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.Group" title="django.contrib.auth.models.Group"><code class="xref py py-class docutils literal notranslate"><span class="pre">Group</span></code></a> via its <code class="docutils literal notranslate"><span class="pre">permissions</span></code> attribute.</p> </div> <div class="section" id="s-permission-caching"> <span id="permission-caching"></span><h3>Permission caching<a class="headerlink" href="#permission-caching" title="Permalink to this headline">¶</a></h3> <p>The <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.backends.ModelBackend" title="django.contrib.auth.backends.ModelBackend"><code class="xref py py-class docutils literal notranslate"><span class="pre">ModelBackend</span></code></a> 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:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.contrib.auth.models</span> <span class="k">import</span> <span class="n">Permission</span><span class="p">,</span> <span class="n">User</span> <span class="kn">from</span> <span class="nn">django.contrib.contenttypes.models</span> <span class="k">import</span> <span class="n">ContentType</span> <span class="kn">from</span> <span class="nn">django.shortcuts</span> <span class="k">import</span> <span class="n">get_object_or_404</span> <span class="kn">from</span> <span class="nn">myapp.models</span> <span class="k">import</span> <span class="n">BlogPost</span> <span class="k">def</span> <span class="nf">user_gains_perms</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="n">user_id</span><span class="p">):</span> <span class="n">user</span> <span class="o">=</span> <span class="n">get_object_or_404</span><span class="p">(</span><span class="n">User</span><span class="p">,</span> <span class="n">pk</span><span class="o">=</span><span class="n">user_id</span><span class="p">)</span> <span class="c1"># any permission check will cache the current set of permissions</span> <span class="n">user</span><span class="o">.</span><span class="n">has_perm</span><span class="p">(</span><span class="s1">'myapp.change_blogpost'</span><span class="p">)</span> <span class="n">content_type</span> <span class="o">=</span> <span class="n">ContentType</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get_for_model</span><span class="p">(</span><span class="n">BlogPost</span><span class="p">)</span> <span class="n">permission</span> <span class="o">=</span> <span class="n">Permission</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span> <span class="n">codename</span><span class="o">=</span><span class="s1">'change_blogpost'</span><span class="p">,</span> <span class="n">content_type</span><span class="o">=</span><span class="n">content_type</span><span class="p">,</span> <span class="p">)</span> <span class="n">user</span><span class="o">.</span><span class="n">user_permissions</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">permission</span><span class="p">)</span> <span class="c1"># Checking the cached permission set</span> <span class="n">user</span><span class="o">.</span><span class="n">has_perm</span><span class="p">(</span><span class="s1">'myapp.change_blogpost'</span><span class="p">)</span> <span class="c1"># False</span> <span class="c1"># Request new instance of User</span> <span class="c1"># Be aware that user.refresh_from_db() won't clear the cache.</span> <span class="n">user</span> <span class="o">=</span> <span class="n">get_object_or_404</span><span class="p">(</span><span class="n">User</span><span class="p">,</span> <span class="n">pk</span><span class="o">=</span><span class="n">user_id</span><span class="p">)</span> <span class="c1"># Permission cache is repopulated from the database</span> <span class="n">user</span><span class="o">.</span><span class="n">has_perm</span><span class="p">(</span><span class="s1">'myapp.change_blogpost'</span><span class="p">)</span> <span class="c1"># True</span> <span class="o">...</span> </pre></div> </div> </div> </div> <div class="section" id="s-authentication-in-web-requests"> <span id="s-auth-web-requests"></span><span id="authentication-in-web-requests"></span><span id="auth-web-requests"></span><h2>Authentication in Web requests<a class="headerlink" href="#authentication-in-web-requests" title="Permalink to this headline">¶</a></h2> <p>Django uses <a class="reference internal" href="../http/sessions.html"><span class="doc">sessions</span></a> and middleware to hook the authentication system into <a class="reference internal" href="../../ref/request-response.html#django.http.HttpRequest" title="django.http.HttpRequest"><code class="xref py py-class docutils literal notranslate"><span class="pre">request</span> <span class="pre">objects</span></code></a>.</p> <p>These provide a <a class="reference internal" href="../../ref/request-response.html#django.http.HttpRequest.user" title="django.http.HttpRequest.user"><code class="xref py py-attr docutils literal notranslate"><span class="pre">request.user</span></code></a> 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 <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.AnonymousUser" title="django.contrib.auth.models.AnonymousUser"><code class="xref py py-class docutils literal notranslate"><span class="pre">AnonymousUser</span></code></a>, otherwise it will be an instance of <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User" title="django.contrib.auth.models.User"><code class="xref py py-class docutils literal notranslate"><span class="pre">User</span></code></a>.</p> <p>You can tell them apart with <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User.is_authenticated" title="django.contrib.auth.models.User.is_authenticated"><code class="xref py py-attr docutils literal notranslate"><span class="pre">is_authenticated</span></code></a>, like so:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">request</span><span class="o">.</span><span class="n">user</span><span class="o">.</span><span class="n">is_authenticated</span><span class="p">:</span> <span class="c1"># Do something for authenticated users.</span> <span class="o">...</span> <span class="k">else</span><span class="p">:</span> <span class="c1"># Do something for anonymous users.</span> <span class="o">...</span> </pre></div> </div> <div class="section" id="s-how-to-log-a-user-in"> <span id="s-id2"></span><span id="how-to-log-a-user-in"></span><span id="id2"></span><h3>How to log a user in<a class="headerlink" href="#how-to-log-a-user-in" title="Permalink to this headline">¶</a></h3> <p>If you have an authenticated user you want to attach to the current session - this is done with a <a class="reference internal" href="#django.contrib.auth.login" title="django.contrib.auth.login"><code class="xref py py-func docutils literal notranslate"><span class="pre">login()</span></code></a> function.</p> <dl class="function"> <dt id="django.contrib.auth.login"> <code class="descname">login</code>(<em>request</em>, <em>user</em>, <em>backend=None</em>)<a class="reference internal" href="../../_modules/django/contrib/auth.html#login"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.contrib.auth.login" title="Permalink to this definition">¶</a></dt> <dd><p>To log a user in, from a view, use <a class="reference internal" href="#django.contrib.auth.login" title="django.contrib.auth.login"><code class="xref py py-func docutils literal notranslate"><span class="pre">login()</span></code></a>. It takes an <a class="reference internal" href="../../ref/request-response.html#django.http.HttpRequest" title="django.http.HttpRequest"><code class="xref py py-class docutils literal notranslate"><span class="pre">HttpRequest</span></code></a> object and a <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User" title="django.contrib.auth.models.User"><code class="xref py py-class docutils literal notranslate"><span class="pre">User</span></code></a> object. <a class="reference internal" href="#django.contrib.auth.login" title="django.contrib.auth.login"><code class="xref py py-func docutils literal notranslate"><span class="pre">login()</span></code></a> saves the user’s ID in the session, using Django’s session framework.</p> <p>Note that any data set during the anonymous session is retained in the session after a user logs in.</p> <p>This example shows how you might use both <a class="reference internal" href="#django.contrib.auth.authenticate" title="django.contrib.auth.authenticate"><code class="xref py py-func docutils literal notranslate"><span class="pre">authenticate()</span></code></a> and <a class="reference internal" href="#django.contrib.auth.login" title="django.contrib.auth.login"><code class="xref py py-func docutils literal notranslate"><span class="pre">login()</span></code></a>:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.contrib.auth</span> <span class="k">import</span> <span class="n">authenticate</span><span class="p">,</span> <span class="n">login</span> <span class="k">def</span> <span class="nf">my_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span> <span class="n">username</span> <span class="o">=</span> <span class="n">request</span><span class="o">.</span><span class="n">POST</span><span class="p">[</span><span class="s1">'username'</span><span class="p">]</span> <span class="n">password</span> <span class="o">=</span> <span class="n">request</span><span class="o">.</span><span class="n">POST</span><span class="p">[</span><span class="s1">'password'</span><span class="p">]</span> <span class="n">user</span> <span class="o">=</span> <span class="n">authenticate</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="n">username</span><span class="o">=</span><span class="n">username</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="n">password</span><span class="p">)</span> <span class="k">if</span> <span class="n">user</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span> <span class="n">login</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="n">user</span><span class="p">)</span> <span class="c1"># Redirect to a success page.</span> <span class="o">...</span> <span class="k">else</span><span class="p">:</span> <span class="c1"># Return an 'invalid login' error message.</span> <span class="o">...</span> </pre></div> </div> <div class="versionchanged"> <span class="title">Changed in Django 1.10:</span> <p>In older versions, when you’re manually logging a user in, you <em>must</em> successfully authenticate the user with <a class="reference internal" href="#django.contrib.auth.authenticate" title="django.contrib.auth.authenticate"><code class="xref py py-func docutils literal notranslate"><span class="pre">authenticate()</span></code></a> before you call <a class="reference internal" href="#django.contrib.auth.login" title="django.contrib.auth.login"><code class="xref py py-func docutils literal notranslate"><span class="pre">login()</span></code></a>. Now you can set the backend using the new <code class="docutils literal notranslate"><span class="pre">backend</span></code> argument.</p> </div> </dd></dl> <div class="section" id="s-selecting-the-authentication-backend"> <span id="selecting-the-authentication-backend"></span><h4>Selecting the authentication backend<a class="headerlink" href="#selecting-the-authentication-backend" title="Permalink to this headline">¶</a></h4> <p>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 <a class="reference internal" href="customizing.html#authentication-backends"><span class="std std-ref">authentication backend</span></a> to fetch the user’s details on a future request. The authentication backend to save in the session is selected as follows:</p> <ol class="arabic simple"> <li>Use the value of the optional <code class="docutils literal notranslate"><span class="pre">backend</span></code> argument, if provided.</li> <li>Use the value of the <code class="docutils literal notranslate"><span class="pre">user.backend</span></code> attribute, if present. This allows pairing <a class="reference internal" href="#django.contrib.auth.authenticate" title="django.contrib.auth.authenticate"><code class="xref py py-func docutils literal notranslate"><span class="pre">authenticate()</span></code></a> and <a class="reference internal" href="#django.contrib.auth.login" title="django.contrib.auth.login"><code class="xref py py-func docutils literal notranslate"><span class="pre">login()</span></code></a>: <a class="reference internal" href="#django.contrib.auth.authenticate" title="django.contrib.auth.authenticate"><code class="xref py py-func docutils literal notranslate"><span class="pre">authenticate()</span></code></a> sets the <code class="docutils literal notranslate"><span class="pre">user.backend</span></code> attribute on the user object it returns.</li> <li>Use the <code class="docutils literal notranslate"><span class="pre">backend</span></code> in <a class="reference internal" href="../../ref/settings.html#std:setting-AUTHENTICATION_BACKENDS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">AUTHENTICATION_BACKENDS</span></code></a>, if there is only one.</li> <li>Otherwise, raise an exception.</li> </ol> <p>In cases 1 and 2, the value of the <code class="docutils literal notranslate"><span class="pre">backend</span></code> argument or the <code class="docutils literal notranslate"><span class="pre">user.backend</span></code> attribute should be a dotted import path string (like that found in <a class="reference internal" href="../../ref/settings.html#std:setting-AUTHENTICATION_BACKENDS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">AUTHENTICATION_BACKENDS</span></code></a>), not the actual backend class.</p> </div> </div> <div class="section" id="s-how-to-log-a-user-out"> <span id="how-to-log-a-user-out"></span><h3>How to log a user out<a class="headerlink" href="#how-to-log-a-user-out" title="Permalink to this headline">¶</a></h3> <dl class="function"> <dt id="django.contrib.auth.logout"> <code class="descname">logout</code>(<em>request</em>)<a class="reference internal" href="../../_modules/django/contrib/auth.html#logout"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.contrib.auth.logout" title="Permalink to this definition">¶</a></dt> <dd><p>To log out a user who has been logged in via <a class="reference internal" href="#django.contrib.auth.login" title="django.contrib.auth.login"><code class="xref py py-func docutils literal notranslate"><span class="pre">django.contrib.auth.login()</span></code></a>, use <a class="reference internal" href="#django.contrib.auth.logout" title="django.contrib.auth.logout"><code class="xref py py-func docutils literal notranslate"><span class="pre">django.contrib.auth.logout()</span></code></a> within your view. It takes an <a class="reference internal" href="../../ref/request-response.html#django.http.HttpRequest" title="django.http.HttpRequest"><code class="xref py py-class docutils literal notranslate"><span class="pre">HttpRequest</span></code></a> object and has no return value. Example:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.contrib.auth</span> <span class="k">import</span> <span class="n">logout</span> <span class="k">def</span> <span class="nf">logout_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span> <span class="n">logout</span><span class="p">(</span><span class="n">request</span><span class="p">)</span> <span class="c1"># Redirect to a success page.</span> </pre></div> </div> <p>Note that <a class="reference internal" href="#django.contrib.auth.logout" title="django.contrib.auth.logout"><code class="xref py py-func docutils literal notranslate"><span class="pre">logout()</span></code></a> doesn’t throw any errors if the user wasn’t logged in.</p> <p>When you call <a class="reference internal" href="#django.contrib.auth.logout" title="django.contrib.auth.logout"><code class="xref py py-func docutils literal notranslate"><span class="pre">logout()</span></code></a>, 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 <em>after</em> calling <a class="reference internal" href="#django.contrib.auth.logout" title="django.contrib.auth.logout"><code class="xref py py-func docutils literal notranslate"><span class="pre">django.contrib.auth.logout()</span></code></a>.</p> </dd></dl> </div> <div class="section" id="s-limiting-access-to-logged-in-users"> <span id="limiting-access-to-logged-in-users"></span><h3>Limiting access to logged-in users<a class="headerlink" href="#limiting-access-to-logged-in-users" title="Permalink to this headline">¶</a></h3> <div class="section" id="s-the-raw-way"> <span id="the-raw-way"></span><h4>The raw way<a class="headerlink" href="#the-raw-way" title="Permalink to this headline">¶</a></h4> <p>The simple, raw way to limit access to pages is to check <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User.is_authenticated" title="django.contrib.auth.models.User.is_authenticated"><code class="xref py py-attr docutils literal notranslate"><span class="pre">request.user.is_authenticated</span></code></a> and either redirect to a login page:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.conf</span> <span class="k">import</span> <span class="n">settings</span> <span class="kn">from</span> <span class="nn">django.shortcuts</span> <span class="k">import</span> <span class="n">redirect</span> <span class="k">def</span> <span class="nf">my_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span> <span class="k">if</span> <span class="ow">not</span> <span class="n">request</span><span class="o">.</span><span class="n">user</span><span class="o">.</span><span class="n">is_authenticated</span><span class="p">:</span> <span class="k">return</span> <span class="n">redirect</span><span class="p">(</span><span class="s1">'</span><span class="si">%s</span><span class="s1">?next=</span><span class="si">%s</span><span class="s1">'</span> <span class="o">%</span> <span class="p">(</span><span class="n">settings</span><span class="o">.</span><span class="n">LOGIN_URL</span><span class="p">,</span> <span class="n">request</span><span class="o">.</span><span class="n">path</span><span class="p">))</span> <span class="c1"># ...</span> </pre></div> </div> <p>…or display an error message:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.shortcuts</span> <span class="k">import</span> <span class="n">render</span> <span class="k">def</span> <span class="nf">my_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span> <span class="k">if</span> <span class="ow">not</span> <span class="n">request</span><span class="o">.</span><span class="n">user</span><span class="o">.</span><span class="n">is_authenticated</span><span class="p">:</span> <span class="k">return</span> <span class="n">render</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="s1">'myapp/login_error.html'</span><span class="p">)</span> <span class="c1"># ...</span> </pre></div> </div> </div> <div class="section" id="s-the-login-required-decorator"> <span id="the-login-required-decorator"></span><h4>The <code class="docutils literal notranslate"><span class="pre">login_required</span></code> decorator<a class="headerlink" href="#the-login-required-decorator" title="Permalink to this headline">¶</a></h4> <dl class="function"> <dt id="django.contrib.auth.decorators.login_required"> <code class="descname">login_required</code>(<em>redirect_field_name='next'</em>, <em>login_url=None</em>)<a class="reference internal" href="../../_modules/django/contrib/auth/decorators.html#login_required"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.contrib.auth.decorators.login_required" title="Permalink to this definition">¶</a></dt> <dd><p>As a shortcut, you can use the convenient <a class="reference internal" href="#django.contrib.auth.decorators.login_required" title="django.contrib.auth.decorators.login_required"><code class="xref py py-func docutils literal notranslate"><span class="pre">login_required()</span></code></a> decorator:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.contrib.auth.decorators</span> <span class="k">import</span> <span class="n">login_required</span> <span class="nd">@login_required</span> <span class="k">def</span> <span class="nf">my_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span> <span class="o">...</span> </pre></div> </div> <p><a class="reference internal" href="#django.contrib.auth.decorators.login_required" title="django.contrib.auth.decorators.login_required"><code class="xref py py-func docutils literal notranslate"><span class="pre">login_required()</span></code></a> does the following:</p> <ul class="simple"> <li>If the user isn’t logged in, redirect to <a class="reference internal" href="../../ref/settings.html#std:setting-LOGIN_URL"><code class="xref std std-setting docutils literal notranslate"><span class="pre">settings.LOGIN_URL</span></code></a>, passing the current absolute path in the query string. Example: <code class="docutils literal notranslate"><span class="pre">/accounts/login/?next=/polls/3/</span></code>.</li> <li>If the user is logged in, execute the view normally. The view code is free to assume the user is logged in.</li> </ul> <p>By default, the path that the user should be redirected to upon successful authentication is stored in a query string parameter called <code class="docutils literal notranslate"><span class="pre">"next"</span></code>. If you would prefer to use a different name for this parameter, <a class="reference internal" href="#django.contrib.auth.decorators.login_required" title="django.contrib.auth.decorators.login_required"><code class="xref py py-func docutils literal notranslate"><span class="pre">login_required()</span></code></a> takes an optional <code class="docutils literal notranslate"><span class="pre">redirect_field_name</span></code> parameter:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.contrib.auth.decorators</span> <span class="k">import</span> <span class="n">login_required</span> <span class="nd">@login_required</span><span class="p">(</span><span class="n">redirect_field_name</span><span class="o">=</span><span class="s1">'my_redirect_field'</span><span class="p">)</span> <span class="k">def</span> <span class="nf">my_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span> <span class="o">...</span> </pre></div> </div> <p>Note that if you provide a value to <code class="docutils literal notranslate"><span class="pre">redirect_field_name</span></code>, 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 <code class="docutils literal notranslate"><span class="pre">redirect_field_name</span></code> as its key rather than <code class="docutils literal notranslate"><span class="pre">"next"</span></code> (the default).</p> <p><a class="reference internal" href="#django.contrib.auth.decorators.login_required" title="django.contrib.auth.decorators.login_required"><code class="xref py py-func docutils literal notranslate"><span class="pre">login_required()</span></code></a> also takes an optional <code class="docutils literal notranslate"><span class="pre">login_url</span></code> parameter. Example:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.contrib.auth.decorators</span> <span class="k">import</span> <span class="n">login_required</span> <span class="nd">@login_required</span><span class="p">(</span><span class="n">login_url</span><span class="o">=</span><span class="s1">'/accounts/login/'</span><span class="p">)</span> <span class="k">def</span> <span class="nf">my_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span> <span class="o">...</span> </pre></div> </div> <p>Note that if you don’t specify the <code class="docutils literal notranslate"><span class="pre">login_url</span></code> parameter, you’ll need to ensure that the <a class="reference internal" href="../../ref/settings.html#std:setting-LOGIN_URL"><code class="xref std std-setting docutils literal notranslate"><span class="pre">settings.LOGIN_URL</span></code></a> and your login view are properly associated. For example, using the defaults, add the following lines to your URLconf:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.contrib.auth</span> <span class="k">import</span> <span class="n">views</span> <span class="k">as</span> <span class="n">auth_views</span> <span class="n">url</span><span class="p">(</span><span class="sa">r</span><span class="s1">'^accounts/login/$'</span><span class="p">,</span> <span class="n">auth_views</span><span class="o">.</span><span class="n">LoginView</span><span class="o">.</span><span class="n">as_view</span><span class="p">()),</span> </pre></div> </div> <p>The <a class="reference internal" href="../../ref/settings.html#std:setting-LOGIN_URL"><code class="xref std std-setting docutils literal notranslate"><span class="pre">settings.LOGIN_URL</span></code></a> also accepts view function names and <a class="reference internal" href="../http/urls.html#naming-url-patterns"><span class="std std-ref">named URL patterns</span></a>. This allows you to freely remap your login view within your URLconf without having to update the setting.</p> </dd></dl> <div class="admonition note"> <p class="first admonition-title">Note</p> <p class="last">The <code class="docutils literal notranslate"><span class="pre">login_required</span></code> decorator does NOT check the <code class="docutils literal notranslate"><span class="pre">is_active</span></code> flag on a user, but the default <a class="reference internal" href="../../ref/settings.html#std:setting-AUTHENTICATION_BACKENDS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">AUTHENTICATION_BACKENDS</span></code></a> reject inactive users.</p> </div> <div class="admonition seealso"> <p class="first admonition-title">See also</p> <p class="last">If you are writing custom views for Django’s admin (or need the same authorization check that the built-in views use), you may find the <a class="reference internal" href="../../ref/contrib/admin/index.html#django.contrib.admin.views.decorators.staff_member_required" title="django.contrib.admin.views.decorators.staff_member_required"><code class="xref py py-func docutils literal notranslate"><span class="pre">django.contrib.admin.views.decorators.staff_member_required()</span></code></a> decorator a useful alternative to <code class="docutils literal notranslate"><span class="pre">login_required()</span></code>.</p> </div> </div> <div class="section" id="s-the-loginrequired-mixin"> <span id="the-loginrequired-mixin"></span><h4>The <code class="docutils literal notranslate"><span class="pre">LoginRequired</span></code> mixin<a class="headerlink" href="#the-loginrequired-mixin" title="Permalink to this headline">¶</a></h4> <p>When using <a class="reference internal" href="../class-based-views/index.html"><span class="doc">class-based views</span></a>, you can achieve the same behavior as with <code class="docutils literal notranslate"><span class="pre">login_required</span></code> by using the <code class="docutils literal notranslate"><span class="pre">LoginRequiredMixin</span></code>. This mixin should be at the leftmost position in the inheritance list.</p> <dl class="class"> <dt id="django.contrib.auth.mixins.LoginRequiredMixin"> <em class="property">class </em><code class="descname">LoginRequiredMixin</code><a class="headerlink" href="#django.contrib.auth.mixins.LoginRequiredMixin" title="Permalink to this definition">¶</a></dt> <dd><p>If a view is using this mixin, all requests by non-authenticated users will be redirected to the login page or shown an HTTP 403 Forbidden error, depending on the <a class="reference internal" href="#django.contrib.auth.mixins.AccessMixin.raise_exception" title="django.contrib.auth.mixins.AccessMixin.raise_exception"><code class="xref py py-attr docutils literal notranslate"><span class="pre">raise_exception</span></code></a> parameter.</p> <p>You can set any of the parameters of <a class="reference internal" href="#django.contrib.auth.mixins.AccessMixin" title="django.contrib.auth.mixins.AccessMixin"><code class="xref py py-class docutils literal notranslate"><span class="pre">AccessMixin</span></code></a> to customize the handling of unauthorized users:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.contrib.auth.mixins</span> <span class="k">import</span> <span class="n">LoginRequiredMixin</span> <span class="k">class</span> <span class="nc">MyView</span><span class="p">(</span><span class="n">LoginRequiredMixin</span><span class="p">,</span> <span class="n">View</span><span class="p">):</span> <span class="n">login_url</span> <span class="o">=</span> <span class="s1">'/login/'</span> <span class="n">redirect_field_name</span> <span class="o">=</span> <span class="s1">'redirect_to'</span> </pre></div> </div> </dd></dl> <div class="admonition note"> <p class="first admonition-title">Note</p> <p class="last">Just as the <code class="docutils literal notranslate"><span class="pre">login_required</span></code> decorator, this mixin does NOT check the <code class="docutils literal notranslate"><span class="pre">is_active</span></code> flag on a user, but the default <a class="reference internal" href="../../ref/settings.html#std:setting-AUTHENTICATION_BACKENDS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">AUTHENTICATION_BACKENDS</span></code></a> reject inactive users.</p> </div> </div> <div class="section" id="s-limiting-access-to-logged-in-users-that-pass-a-test"> <span id="limiting-access-to-logged-in-users-that-pass-a-test"></span><h4>Limiting access to logged-in users that pass a test<a class="headerlink" href="#limiting-access-to-logged-in-users-that-pass-a-test" title="Permalink to this headline">¶</a></h4> <p>To limit access based on certain permissions or some other test, you’d do essentially the same thing as described in the previous section.</p> <p>The simple way is to run your test on <a class="reference internal" href="../../ref/request-response.html#django.http.HttpRequest.user" title="django.http.HttpRequest.user"><code class="xref py py-attr docutils literal notranslate"><span class="pre">request.user</span></code></a> in the view directly. For example, this view checks to make sure the user has an email in the desired domain and if not, redirects to the login page:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.shortcuts</span> <span class="k">import</span> <span class="n">redirect</span> <span class="k">def</span> <span class="nf">my_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span> <span class="k">if</span> <span class="ow">not</span> <span class="n">request</span><span class="o">.</span><span class="n">user</span><span class="o">.</span><span class="n">email</span><span class="o">.</span><span class="n">endswith</span><span class="p">(</span><span class="s1">'@example.com'</span><span class="p">):</span> <span class="k">return</span> <span class="n">redirect</span><span class="p">(</span><span class="s1">'/login/?next=</span><span class="si">%s</span><span class="s1">'</span> <span class="o">%</span> <span class="n">request</span><span class="o">.</span><span class="n">path</span><span class="p">)</span> <span class="c1"># ...</span> </pre></div> </div> <dl class="function"> <dt id="django.contrib.auth.decorators.user_passes_test"> <code class="descname">user_passes_test</code>(<em>test_func</em>, <em>login_url=None</em>, <em>redirect_field_name='next'</em>)<a class="reference internal" href="../../_modules/django/contrib/auth/decorators.html#user_passes_test"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.contrib.auth.decorators.user_passes_test" title="Permalink to this definition">¶</a></dt> <dd><p>As a shortcut, you can use the convenient <code class="docutils literal notranslate"><span class="pre">user_passes_test</span></code> decorator which performs a redirect when the callable returns <code class="docutils literal notranslate"><span class="pre">False</span></code>:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.contrib.auth.decorators</span> <span class="k">import</span> <span class="n">user_passes_test</span> <span class="k">def</span> <span class="nf">email_check</span><span class="p">(</span><span class="n">user</span><span class="p">):</span> <span class="k">return</span> <span class="n">user</span><span class="o">.</span><span class="n">email</span><span class="o">.</span><span class="n">endswith</span><span class="p">(</span><span class="s1">'@example.com'</span><span class="p">)</span> <span class="nd">@user_passes_test</span><span class="p">(</span><span class="n">email_check</span><span class="p">)</span> <span class="k">def</span> <span class="nf">my_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span> <span class="o">...</span> </pre></div> </div> <p><a class="reference internal" href="#django.contrib.auth.decorators.user_passes_test" title="django.contrib.auth.decorators.user_passes_test"><code class="xref py py-func docutils literal notranslate"><span class="pre">user_passes_test()</span></code></a> takes a required argument: a callable that takes a <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User" title="django.contrib.auth.models.User"><code class="xref py py-class docutils literal notranslate"><span class="pre">User</span></code></a> object and returns <code class="docutils literal notranslate"><span class="pre">True</span></code> if the user is allowed to view the page. Note that <a class="reference internal" href="#django.contrib.auth.decorators.user_passes_test" title="django.contrib.auth.decorators.user_passes_test"><code class="xref py py-func docutils literal notranslate"><span class="pre">user_passes_test()</span></code></a> does not automatically check that the <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User" title="django.contrib.auth.models.User"><code class="xref py py-class docutils literal notranslate"><span class="pre">User</span></code></a> is not anonymous.</p> <p><a class="reference internal" href="#django.contrib.auth.decorators.user_passes_test" title="django.contrib.auth.decorators.user_passes_test"><code class="xref py py-func docutils literal notranslate"><span class="pre">user_passes_test()</span></code></a> takes two optional arguments:</p> <dl class="docutils"> <dt><code class="docutils literal notranslate"><span class="pre">login_url</span></code></dt> <dd>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 <a class="reference internal" href="../../ref/settings.html#std:setting-LOGIN_URL"><code class="xref std std-setting docutils literal notranslate"><span class="pre">settings.LOGIN_URL</span></code></a> if you don’t specify one.</dd> <dt><code class="docutils literal notranslate"><span class="pre">redirect_field_name</span></code></dt> <dd>Same as for <a class="reference internal" href="#django.contrib.auth.decorators.login_required" title="django.contrib.auth.decorators.login_required"><code class="xref py py-func docutils literal notranslate"><span class="pre">login_required()</span></code></a>. Setting it to <code class="docutils literal notranslate"><span class="pre">None</span></code> 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”.</dd> </dl> <p>For example:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="nd">@user_passes_test</span><span class="p">(</span><span class="n">email_check</span><span class="p">,</span> <span class="n">login_url</span><span class="o">=</span><span class="s1">'/login/'</span><span class="p">)</span> <span class="k">def</span> <span class="nf">my_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span> <span class="o">...</span> </pre></div> </div> </dd></dl> <dl class="class"> <dt id="django.contrib.auth.mixins.UserPassesTestMixin"> <em class="property">class </em><code class="descname">UserPassesTestMixin</code><a class="headerlink" href="#django.contrib.auth.mixins.UserPassesTestMixin" title="Permalink to this definition">¶</a></dt> <dd><p>When using <a class="reference internal" href="../class-based-views/index.html"><span class="doc">class-based views</span></a>, you can use the <code class="docutils literal notranslate"><span class="pre">UserPassesTestMixin</span></code> to do this.</p> <dl class="method"> <dt id="django.contrib.auth.mixins.UserPassesTestMixin.test_func"> <code class="descname">test_func</code>()<a class="headerlink" href="#django.contrib.auth.mixins.UserPassesTestMixin.test_func" title="Permalink to this definition">¶</a></dt> <dd><p>You have to override the <code class="docutils literal notranslate"><span class="pre">test_func()</span></code> method of the class to provide the test that is performed. Furthermore, you can set any of the parameters of <a class="reference internal" href="#django.contrib.auth.mixins.AccessMixin" title="django.contrib.auth.mixins.AccessMixin"><code class="xref py py-class docutils literal notranslate"><span class="pre">AccessMixin</span></code></a> to customize the handling of unauthorized users:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.contrib.auth.mixins</span> <span class="k">import</span> <span class="n">UserPassesTestMixin</span> <span class="k">class</span> <span class="nc">MyView</span><span class="p">(</span><span class="n">UserPassesTestMixin</span><span class="p">,</span> <span class="n">View</span><span class="p">):</span> <span class="k">def</span> <span class="nf">test_func</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">user</span><span class="o">.</span><span class="n">email</span><span class="o">.</span><span class="n">endswith</span><span class="p">(</span><span class="s1">'@example.com'</span><span class="p">)</span> </pre></div> </div> </dd></dl> <dl class="method"> <dt id="django.contrib.auth.mixins.UserPassesTestMixin.get_test_func"> <code class="descname">get_test_func</code>()<a class="headerlink" href="#django.contrib.auth.mixins.UserPassesTestMixin.get_test_func" title="Permalink to this definition">¶</a></dt> <dd><p>You can also override the <code class="docutils literal notranslate"><span class="pre">get_test_func()</span></code> method to have the mixin use a differently named function for its checks (instead of <a class="reference internal" href="#django.contrib.auth.mixins.UserPassesTestMixin.test_func" title="django.contrib.auth.mixins.UserPassesTestMixin.test_func"><code class="xref py py-meth docutils literal notranslate"><span class="pre">test_func()</span></code></a>).</p> </dd></dl> <div class="admonition-stacking-userpassestestmixin admonition"> <p class="first admonition-title">Stacking <code class="docutils literal notranslate"><span class="pre">UserPassesTestMixin</span></code></p> <p>Due to the way <code class="docutils literal notranslate"><span class="pre">UserPassesTestMixin</span></code> is implemented, you cannot stack them in your inheritance list. The following does NOT work:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">TestMixin1</span><span class="p">(</span><span class="n">UserPassesTestMixin</span><span class="p">):</span> <span class="k">def</span> <span class="nf">test_func</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">user</span><span class="o">.</span><span class="n">email</span><span class="o">.</span><span class="n">endswith</span><span class="p">(</span><span class="s1">'@example.com'</span><span class="p">)</span> <span class="k">class</span> <span class="nc">TestMixin2</span><span class="p">(</span><span class="n">UserPassesTestMixin</span><span class="p">):</span> <span class="k">def</span> <span class="nf">test_func</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">user</span><span class="o">.</span><span class="n">username</span><span class="o">.</span><span class="n">startswith</span><span class="p">(</span><span class="s1">'django'</span><span class="p">)</span> <span class="k">class</span> <span class="nc">MyView</span><span class="p">(</span><span class="n">TestMixin1</span><span class="p">,</span> <span class="n">TestMixin2</span><span class="p">,</span> <span class="n">View</span><span class="p">):</span> <span class="o">...</span> </pre></div> </div> <p class="last">If <code class="docutils literal notranslate"><span class="pre">TestMixin1</span></code> would call <code class="docutils literal notranslate"><span class="pre">super()</span></code> and take that result into account, <code class="docutils literal notranslate"><span class="pre">TestMixin1</span></code> wouldn’t work standalone anymore.</p> </div> </dd></dl> </div> <div class="section" id="s-the-permission-required-decorator"> <span id="the-permission-required-decorator"></span><h4>The <code class="docutils literal notranslate"><span class="pre">permission_required</span></code> decorator<a class="headerlink" href="#the-permission-required-decorator" title="Permalink to this headline">¶</a></h4> <dl class="function"> <dt id="django.contrib.auth.decorators.permission_required"> <code class="descname">permission_required</code>(<em>perm</em>, <em>login_url=None</em>, <em>raise_exception=False</em>)<a class="reference internal" href="../../_modules/django/contrib/auth/decorators.html#permission_required"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.contrib.auth.decorators.permission_required" title="Permalink to this definition">¶</a></dt> <dd><p>It’s a relatively common task to check whether a user has a particular permission. For that reason, Django provides a shortcut for that case: the <a class="reference internal" href="#django.contrib.auth.decorators.permission_required" title="django.contrib.auth.decorators.permission_required"><code class="xref py py-func docutils literal notranslate"><span class="pre">permission_required()</span></code></a> decorator.:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.contrib.auth.decorators</span> <span class="k">import</span> <span class="n">permission_required</span> <span class="nd">@permission_required</span><span class="p">(</span><span class="s1">'polls.can_vote'</span><span class="p">)</span> <span class="k">def</span> <span class="nf">my_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span> <span class="o">...</span> </pre></div> </div> <p>Just like the <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User.has_perm" title="django.contrib.auth.models.User.has_perm"><code class="xref py py-meth docutils literal notranslate"><span class="pre">has_perm()</span></code></a> method, permission names take the form <code class="docutils literal notranslate"><span class="pre">"<app</span> <span class="pre">label>.<permission</span> <span class="pre">codename>"</span></code> (i.e. <code class="docutils literal notranslate"><span class="pre">polls.can_vote</span></code> for a permission on a model in the <code class="docutils literal notranslate"><span class="pre">polls</span></code> application).</p> <p>The decorator may also take an iterable of permissions, in which case the user must have all of the permissions in order to access the view.</p> <p>Note that <a class="reference internal" href="#django.contrib.auth.decorators.permission_required" title="django.contrib.auth.decorators.permission_required"><code class="xref py py-func docutils literal notranslate"><span class="pre">permission_required()</span></code></a> also takes an optional <code class="docutils literal notranslate"><span class="pre">login_url</span></code> parameter:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.contrib.auth.decorators</span> <span class="k">import</span> <span class="n">permission_required</span> <span class="nd">@permission_required</span><span class="p">(</span><span class="s1">'polls.can_vote'</span><span class="p">,</span> <span class="n">login_url</span><span class="o">=</span><span class="s1">'/loginpage/'</span><span class="p">)</span> <span class="k">def</span> <span class="nf">my_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span> <span class="o">...</span> </pre></div> </div> <p>As in the <a class="reference internal" href="#django.contrib.auth.decorators.login_required" title="django.contrib.auth.decorators.login_required"><code class="xref py py-func docutils literal notranslate"><span class="pre">login_required()</span></code></a> decorator, <code class="docutils literal notranslate"><span class="pre">login_url</span></code> defaults to <a class="reference internal" href="../../ref/settings.html#std:setting-LOGIN_URL"><code class="xref std std-setting docutils literal notranslate"><span class="pre">settings.LOGIN_URL</span></code></a>.</p> <p>If the <code class="docutils literal notranslate"><span class="pre">raise_exception</span></code> parameter is given, the decorator will raise <a class="reference internal" href="../../ref/exceptions.html#django.core.exceptions.PermissionDenied" title="django.core.exceptions.PermissionDenied"><code class="xref py py-exc docutils literal notranslate"><span class="pre">PermissionDenied</span></code></a>, prompting <a class="reference internal" href="../../ref/views.html#http-forbidden-view"><span class="std std-ref">the 403 (HTTP Forbidden) view</span></a> instead of redirecting to the login page.</p> <p>If you want to use <code class="docutils literal notranslate"><span class="pre">raise_exception</span></code> but also give your users a chance to login first, you can add the <a class="reference internal" href="#django.contrib.auth.decorators.login_required" title="django.contrib.auth.decorators.login_required"><code class="xref py py-func docutils literal notranslate"><span class="pre">login_required()</span></code></a> decorator:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.contrib.auth.decorators</span> <span class="k">import</span> <span class="n">login_required</span><span class="p">,</span> <span class="n">permission_required</span> <span class="nd">@login_required</span> <span class="nd">@permission_required</span><span class="p">(</span><span class="s1">'polls.can_vote'</span><span class="p">,</span> <span class="n">raise_exception</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span> <span class="k">def</span> <span class="nf">my_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span> <span class="o">...</span> </pre></div> </div> </dd></dl> </div> <div class="section" id="s-the-permissionrequiredmixin-mixin"> <span id="the-permissionrequiredmixin-mixin"></span><h4>The <code class="docutils literal notranslate"><span class="pre">PermissionRequiredMixin</span></code> mixin<a class="headerlink" href="#the-permissionrequiredmixin-mixin" title="Permalink to this headline">¶</a></h4> <p>To apply permission checks to <a class="reference internal" href="../../ref/class-based-views/index.html"><span class="doc">class-based views</span></a>, you can use the <code class="docutils literal notranslate"><span class="pre">PermissionRequiredMixin</span></code>:</p> <dl class="class"> <dt id="django.contrib.auth.mixins.PermissionRequiredMixin"> <em class="property">class </em><code class="descname">PermissionRequiredMixin</code><a class="headerlink" href="#django.contrib.auth.mixins.PermissionRequiredMixin" title="Permalink to this definition">¶</a></dt> <dd><p>This mixin, just like the <code class="docutils literal notranslate"><span class="pre">permission_required</span></code> decorator, checks whether the user accessing a view has all given permissions. You should specify the permission (or an iterable of permissions) using the <code class="docutils literal notranslate"><span class="pre">permission_required</span></code> parameter:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.contrib.auth.mixins</span> <span class="k">import</span> <span class="n">PermissionRequiredMixin</span> <span class="k">class</span> <span class="nc">MyView</span><span class="p">(</span><span class="n">PermissionRequiredMixin</span><span class="p">,</span> <span class="n">View</span><span class="p">):</span> <span class="n">permission_required</span> <span class="o">=</span> <span class="s1">'polls.can_vote'</span> <span class="c1"># Or multiple of permissions:</span> <span class="n">permission_required</span> <span class="o">=</span> <span class="p">(</span><span class="s1">'polls.can_open'</span><span class="p">,</span> <span class="s1">'polls.can_edit'</span><span class="p">)</span> </pre></div> </div> <p>You can set any of the parameters of <a class="reference internal" href="#django.contrib.auth.mixins.AccessMixin" title="django.contrib.auth.mixins.AccessMixin"><code class="xref py py-class docutils literal notranslate"><span class="pre">AccessMixin</span></code></a> to customize the handling of unauthorized users.</p> <p>You may also override these methods:</p> <dl class="method"> <dt id="django.contrib.auth.mixins.PermissionRequiredMixin.get_permission_required"> <code class="descname">get_permission_required</code>()<a class="headerlink" href="#django.contrib.auth.mixins.PermissionRequiredMixin.get_permission_required" title="Permalink to this definition">¶</a></dt> <dd><p>Returns an iterable of permission names used by the mixin. Defaults to the <code class="docutils literal notranslate"><span class="pre">permission_required</span></code> attribute, converted to a tuple if necessary.</p> </dd></dl> <dl class="method"> <dt id="django.contrib.auth.mixins.PermissionRequiredMixin.has_permission"> <code class="descname">has_permission</code>()<a class="headerlink" href="#django.contrib.auth.mixins.PermissionRequiredMixin.has_permission" title="Permalink to this definition">¶</a></dt> <dd><p>Returns a boolean denoting whether the current user has permission to execute the decorated view. By default, this returns the result of calling <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User.has_perms" title="django.contrib.auth.models.User.has_perms"><code class="xref py py-meth docutils literal notranslate"><span class="pre">has_perms()</span></code></a> with the list of permissions returned by <a class="reference internal" href="#django.contrib.auth.mixins.PermissionRequiredMixin.get_permission_required" title="django.contrib.auth.mixins.PermissionRequiredMixin.get_permission_required"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_permission_required()</span></code></a>.</p> </dd></dl> </dd></dl> </div> </div> <div class="section" id="s-redirecting-unauthorized-requests-in-class-based-views"> <span id="redirecting-unauthorized-requests-in-class-based-views"></span><h3>Redirecting unauthorized requests in class-based views<a class="headerlink" href="#redirecting-unauthorized-requests-in-class-based-views" title="Permalink to this headline">¶</a></h3> <p>To ease the handling of access restrictions in <a class="reference internal" href="../../ref/class-based-views/index.html"><span class="doc">class-based views</span></a>, the <code class="docutils literal notranslate"><span class="pre">AccessMixin</span></code> can be used to redirect a user to the login page or issue an HTTP 403 Forbidden response.</p> <dl class="class"> <dt id="django.contrib.auth.mixins.AccessMixin"> <em class="property">class </em><code class="descname">AccessMixin</code><a class="headerlink" href="#django.contrib.auth.mixins.AccessMixin" title="Permalink to this definition">¶</a></dt> <dd><dl class="attribute"> <dt id="django.contrib.auth.mixins.AccessMixin.login_url"> <code class="descname">login_url</code><a class="headerlink" href="#django.contrib.auth.mixins.AccessMixin.login_url" title="Permalink to this definition">¶</a></dt> <dd><p>Default return value for <a class="reference internal" href="#django.contrib.auth.mixins.AccessMixin.get_login_url" title="django.contrib.auth.mixins.AccessMixin.get_login_url"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_login_url()</span></code></a>. Defaults to <code class="docutils literal notranslate"><span class="pre">None</span></code> in which case <a class="reference internal" href="#django.contrib.auth.mixins.AccessMixin.get_login_url" title="django.contrib.auth.mixins.AccessMixin.get_login_url"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_login_url()</span></code></a> falls back to <a class="reference internal" href="../../ref/settings.html#std:setting-LOGIN_URL"><code class="xref std std-setting docutils literal notranslate"><span class="pre">settings.LOGIN_URL</span></code></a>.</p> </dd></dl> <dl class="attribute"> <dt id="django.contrib.auth.mixins.AccessMixin.permission_denied_message"> <code class="descname">permission_denied_message</code><a class="headerlink" href="#django.contrib.auth.mixins.AccessMixin.permission_denied_message" title="Permalink to this definition">¶</a></dt> <dd><p>Default return value for <a class="reference internal" href="#django.contrib.auth.mixins.AccessMixin.get_permission_denied_message" title="django.contrib.auth.mixins.AccessMixin.get_permission_denied_message"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_permission_denied_message()</span></code></a>. Defaults to an empty string.</p> </dd></dl> <dl class="attribute"> <dt id="django.contrib.auth.mixins.AccessMixin.redirect_field_name"> <code class="descname">redirect_field_name</code><a class="headerlink" href="#django.contrib.auth.mixins.AccessMixin.redirect_field_name" title="Permalink to this definition">¶</a></dt> <dd><p>Default return value for <a class="reference internal" href="#django.contrib.auth.mixins.AccessMixin.get_redirect_field_name" title="django.contrib.auth.mixins.AccessMixin.get_redirect_field_name"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_redirect_field_name()</span></code></a>. Defaults to <code class="docutils literal notranslate"><span class="pre">"next"</span></code>.</p> </dd></dl> <dl class="attribute"> <dt id="django.contrib.auth.mixins.AccessMixin.raise_exception"> <code class="descname">raise_exception</code><a class="headerlink" href="#django.contrib.auth.mixins.AccessMixin.raise_exception" title="Permalink to this definition">¶</a></dt> <dd><p>If this attribute is set to <code class="docutils literal notranslate"><span class="pre">True</span></code>, a <a class="reference internal" href="../../ref/exceptions.html#django.core.exceptions.PermissionDenied" title="django.core.exceptions.PermissionDenied"><code class="xref py py-class docutils literal notranslate"><span class="pre">PermissionDenied</span></code></a> exception will be raised instead of the redirect. Defaults to <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p> </dd></dl> <dl class="method"> <dt id="django.contrib.auth.mixins.AccessMixin.get_login_url"> <code class="descname">get_login_url</code>()<a class="headerlink" href="#django.contrib.auth.mixins.AccessMixin.get_login_url" title="Permalink to this definition">¶</a></dt> <dd><p>Returns the URL that users who don’t pass the test will be redirected to. Returns <a class="reference internal" href="#django.contrib.auth.mixins.AccessMixin.login_url" title="django.contrib.auth.mixins.AccessMixin.login_url"><code class="xref py py-attr docutils literal notranslate"><span class="pre">login_url</span></code></a> if set, or <a class="reference internal" href="../../ref/settings.html#std:setting-LOGIN_URL"><code class="xref std std-setting docutils literal notranslate"><span class="pre">settings.LOGIN_URL</span></code></a> otherwise.</p> </dd></dl> <dl class="method"> <dt id="django.contrib.auth.mixins.AccessMixin.get_permission_denied_message"> <code class="descname">get_permission_denied_message</code>()<a class="headerlink" href="#django.contrib.auth.mixins.AccessMixin.get_permission_denied_message" title="Permalink to this definition">¶</a></dt> <dd><p>When <a class="reference internal" href="#django.contrib.auth.mixins.AccessMixin.raise_exception" title="django.contrib.auth.mixins.AccessMixin.raise_exception"><code class="xref py py-attr docutils literal notranslate"><span class="pre">raise_exception</span></code></a> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, this method can be used to control the error message passed to the error handler for display to the user. Returns the <a class="reference internal" href="#django.contrib.auth.mixins.AccessMixin.permission_denied_message" title="django.contrib.auth.mixins.AccessMixin.permission_denied_message"><code class="xref py py-attr docutils literal notranslate"><span class="pre">permission_denied_message</span></code></a> attribute by default.</p> </dd></dl> <dl class="method"> <dt id="django.contrib.auth.mixins.AccessMixin.get_redirect_field_name"> <code class="descname">get_redirect_field_name</code>()<a class="headerlink" href="#django.contrib.auth.mixins.AccessMixin.get_redirect_field_name" title="Permalink to this definition">¶</a></dt> <dd><p>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 <code class="docutils literal notranslate"><span class="pre">None</span></code>, a query parameter won’t be added. Returns the <a class="reference internal" href="#django.contrib.auth.mixins.AccessMixin.redirect_field_name" title="django.contrib.auth.mixins.AccessMixin.redirect_field_name"><code class="xref py py-attr docutils literal notranslate"><span class="pre">redirect_field_name</span></code></a> attribute by default.</p> </dd></dl> <dl class="method"> <dt id="django.contrib.auth.mixins.AccessMixin.handle_no_permission"> <code class="descname">handle_no_permission</code>()<a class="headerlink" href="#django.contrib.auth.mixins.AccessMixin.handle_no_permission" title="Permalink to this definition">¶</a></dt> <dd><p>Depending on the value of <code class="docutils literal notranslate"><span class="pre">raise_exception</span></code>, the method either raises a <a class="reference internal" href="../../ref/exceptions.html#django.core.exceptions.PermissionDenied" title="django.core.exceptions.PermissionDenied"><code class="xref py py-exc docutils literal notranslate"><span class="pre">PermissionDenied</span></code></a> exception or redirects the user to the <code class="docutils literal notranslate"><span class="pre">login_url</span></code>, optionally including the <code class="docutils literal notranslate"><span class="pre">redirect_field_name</span></code> if it is set.</p> </dd></dl> </dd></dl> <div class="section" id="s-session-invalidation-on-password-change"> <span id="s-id3"></span><span id="session-invalidation-on-password-change"></span><span id="id3"></span><h4>Session invalidation on password change<a class="headerlink" href="#session-invalidation-on-password-change" title="Permalink to this headline">¶</a></h4> <div class="versionchanged"> <span class="title">Changed in Django 1.10:</span> <p>Session verification is enabled and mandatory in Django 1.10 (there’s no way to disable it) regardless of whether or not <code class="docutils literal notranslate"><span class="pre">SessionAuthenticationMiddleware</span></code> is enabled. In older versions, this protection only applies if <code class="docutils literal notranslate"><span class="pre">django.contrib.auth.middleware.SessionAuthenticationMiddleware</span></code> is enabled in <a class="reference internal" href="../../ref/settings.html#std:setting-MIDDLEWARE"><code class="xref std std-setting docutils literal notranslate"><span class="pre">MIDDLEWARE</span></code></a>.</p> </div> <p>If your <a class="reference internal" href="../../ref/settings.html#std:setting-AUTH_USER_MODEL"><code class="xref std std-setting docutils literal notranslate"><span class="pre">AUTH_USER_MODEL</span></code></a> inherits from <a class="reference internal" href="customizing.html#django.contrib.auth.models.AbstractBaseUser" title="django.contrib.auth.models.AbstractBaseUser"><code class="xref py py-class docutils literal notranslate"><span class="pre">AbstractBaseUser</span></code></a> or implements its own <a class="reference internal" href="customizing.html#django.contrib.auth.models.AbstractBaseUser.get_session_auth_hash" title="django.contrib.auth.models.AbstractBaseUser.get_session_auth_hash"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_session_auth_hash()</span></code></a> method, authenticated sessions will include the hash returned by this function. In the <a class="reference internal" href="customizing.html#django.contrib.auth.models.AbstractBaseUser" title="django.contrib.auth.models.AbstractBaseUser"><code class="xref py py-class docutils literal notranslate"><span class="pre">AbstractBaseUser</span></code></a> 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.</p> <p>The default password change views included with Django, <a class="reference internal" href="#django.contrib.auth.views.PasswordChangeView" title="django.contrib.auth.views.PasswordChangeView"><code class="xref py py-class docutils literal notranslate"><span class="pre">PasswordChangeView</span></code></a> and the <code class="docutils literal notranslate"><span class="pre">user_change_password</span></code> view in the <a class="reference internal" href="index.html#module-django.contrib.auth" title="django.contrib.auth: Django's authentication framework."><code class="xref py py-mod docutils literal notranslate"><span class="pre">django.contrib.auth</span></code></a> 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 <a class="reference internal" href="#django.contrib.auth.update_session_auth_hash" title="django.contrib.auth.update_session_auth_hash"><code class="xref py py-func docutils literal notranslate"><span class="pre">update_session_auth_hash()</span></code></a> function.</p> <dl class="function"> <dt id="django.contrib.auth.update_session_auth_hash"> <code class="descname">update_session_auth_hash</code>(<em>request</em>, <em>user</em>)<a class="reference internal" href="../../_modules/django/contrib/auth.html#update_session_auth_hash"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.contrib.auth.update_session_auth_hash" title="Permalink to this definition">¶</a></dt> <dd><p>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.</p> <p>Example usage:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.contrib.auth</span> <span class="k">import</span> <span class="n">update_session_auth_hash</span> <span class="k">def</span> <span class="nf">password_change</span><span class="p">(</span><span class="n">request</span><span class="p">):</span> <span class="k">if</span> <span class="n">request</span><span class="o">.</span><span class="n">method</span> <span class="o">==</span> <span class="s1">'POST'</span><span class="p">:</span> <span class="n">form</span> <span class="o">=</span> <span class="n">PasswordChangeForm</span><span class="p">(</span><span class="n">user</span><span class="o">=</span><span class="n">request</span><span class="o">.</span><span class="n">user</span><span class="p">,</span> <span class="n">data</span><span class="o">=</span><span class="n">request</span><span class="o">.</span><span class="n">POST</span><span class="p">)</span> <span class="k">if</span> <span class="n">form</span><span class="o">.</span><span class="n">is_valid</span><span class="p">():</span> <span class="n">form</span><span class="o">.</span><span class="n">save</span><span class="p">()</span> <span class="n">update_session_auth_hash</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="n">form</span><span class="o">.</span><span class="n">user</span><span class="p">)</span> <span class="k">else</span><span class="p">:</span> <span class="o">...</span> </pre></div> </div> <div class="versionchanged"> <span class="title">Changed in Django 1.11:</span> <p>Rotating of the session key was added.</p> </div> </dd></dl> <div class="admonition note"> <p class="first admonition-title">Note</p> <p class="last">Since <a class="reference internal" href="customizing.html#django.contrib.auth.models.AbstractBaseUser.get_session_auth_hash" title="django.contrib.auth.models.AbstractBaseUser.get_session_auth_hash"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_session_auth_hash()</span></code></a> is based on <a class="reference internal" href="../../ref/settings.html#std:setting-SECRET_KEY"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SECRET_KEY</span></code></a>, updating your site to use a new secret will invalidate all existing sessions.</p> </div> </div> </div> <div class="section" id="s-module-django.contrib.auth.views"> <span id="s-authentication-views"></span><span id="s-built-in-auth-views"></span><span id="module-django.contrib.auth.views"></span><span id="authentication-views"></span><span id="built-in-auth-views"></span><h3>Authentication Views<a class="headerlink" href="#module-django.contrib.auth.views" title="Permalink to this headline">¶</a></h3> <p>Django provides several views that you can use for handling login, logout, and password management. These make use of the <a class="reference internal" href="#built-in-auth-forms"><span class="std std-ref">stock auth forms</span></a> but you can pass in your own forms as well.</p> <p>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 <a class="reference internal" href="#all-authentication-views"><span class="std std-ref">All authentication views</span></a>.</p> <div class="section" id="s-using-the-views"> <span id="s-id4"></span><span id="using-the-views"></span><span id="id4"></span><h4>Using the views<a class="headerlink" href="#using-the-views" title="Permalink to this headline">¶</a></h4> <p>There are different methods to implement these views in your project. The easiest way is to include the provided URLconf in <code class="docutils literal notranslate"><span class="pre">django.contrib.auth.urls</span></code> in your own URLconf, for example:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">urlpatterns</span> <span class="o">=</span> <span class="p">[</span> <span class="n">url</span><span class="p">(</span><span class="s1">'^'</span><span class="p">,</span> <span class="n">include</span><span class="p">(</span><span class="s1">'django.contrib.auth.urls'</span><span class="p">)),</span> <span class="p">]</span> </pre></div> </div> <p>This will include the following URL patterns:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span>^login/$ [name='login'] ^logout/$ [name='logout'] ^password_change/$ [name='password_change'] ^password_change/done/$ [name='password_change_done'] ^password_reset/$ [name='password_reset'] ^password_reset/done/$ [name='password_reset_done'] ^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$ [name='password_reset_confirm'] ^reset/done/$ [name='password_reset_complete'] </pre></div> </div> <p>The views provide a URL name for easier reference. See <a class="reference internal" href="../http/urls.html"><span class="doc">the URL documentation</span></a> for details on using named URL patterns.</p> <p>If you want more control over your URLs, you can reference a specific view in your URLconf:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.contrib.auth</span> <span class="k">import</span> <span class="n">views</span> <span class="k">as</span> <span class="n">auth_views</span> <span class="n">urlpatterns</span> <span class="o">=</span> <span class="p">[</span> <span class="n">url</span><span class="p">(</span><span class="s1">'^change-password/$'</span><span class="p">,</span> <span class="n">auth_views</span><span class="o">.</span><span class="n">PasswordChangeView</span><span class="o">.</span><span class="n">as_view</span><span class="p">()),</span> <span class="p">]</span> </pre></div> </div> <p>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 <code class="docutils literal notranslate"><span class="pre">template_name</span></code> argument. A way to do this is to provide keyword arguments in the URLconf, these will be passed on to the view. For example:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">urlpatterns</span> <span class="o">=</span> <span class="p">[</span> <span class="n">url</span><span class="p">(</span> <span class="s1">'^change-password/$'</span><span class="p">,</span> <span class="n">auth_views</span><span class="o">.</span><span class="n">PasswordChangeView</span><span class="o">.</span><span class="n">as_view</span><span class="p">(</span><span class="n">template_name</span><span class="o">=</span><span class="s1">'change-password.html'</span><span class="p">),</span> <span class="p">),</span> <span class="p">]</span> </pre></div> </div> <p>All views are <a class="reference internal" href="../class-based-views/index.html"><span class="doc">class-based</span></a>, which allows you to easily customize them by subclassing.</p> </div> <div class="section" id="s-all-authentication-views"> <span id="s-id5"></span><span id="all-authentication-views"></span><span id="id5"></span><h4>All authentication views<a class="headerlink" href="#all-authentication-views" title="Permalink to this headline">¶</a></h4> <p>This is a list with all the views <code class="docutils literal notranslate"><span class="pre">django.contrib.auth</span></code> provides. For implementation details see <a class="reference internal" href="#using-the-views"><span class="std std-ref">Using the views</span></a>.</p> <dl class="function"> <dt id="django.contrib.auth.views.login"> <code class="descname">login</code>(<em>request</em>, <em>template_name=`registration/login.html`</em>, <em>redirect_field_name='next'</em>, <em>authentication_form=AuthenticationForm</em>, <em>current_app=None</em>, <em>extra_context=None</em>, <em>redirect_authenticated_user=False</em>)<a class="headerlink" href="#django.contrib.auth.views.login" title="Permalink to this definition">¶</a></dt> <dd><div class="deprecated"> <p><span class="versionmodified">Deprecated since version 1.11: </span>The <code class="docutils literal notranslate"><span class="pre">login</span></code> function-based view should be replaced by the class-based <a class="reference internal" href="#django.contrib.auth.views.LoginView" title="django.contrib.auth.views.LoginView"><code class="xref py py-class docutils literal notranslate"><span class="pre">LoginView</span></code></a>.</p> </div> <p>The optional arguments of this view are similar to the class-based <code class="docutils literal notranslate"><span class="pre">LoginView</span></code> attributes. In addition, it has:</p> <ul class="simple"> <li><code class="docutils literal notranslate"><span class="pre">current_app</span></code>: A hint indicating which application contains the current view. See the <a class="reference internal" href="../http/urls.html#topics-http-reversing-url-namespaces"><span class="std std-ref">namespaced URL resolution strategy</span></a> for more information.</li> </ul> <div class="deprecated"> <p><span class="versionmodified">Deprecated since version 1.9: </span>The <code class="docutils literal notranslate"><span class="pre">current_app</span></code> attribute is deprecated and will be removed in Django 2.0. Callers should set <code class="docutils literal notranslate"><span class="pre">request.current_app</span></code> instead.</p> </div> <div class="versionadded"> <span class="title">New in Django 1.10:</span> <p>The <code class="docutils literal notranslate"><span class="pre">redirect_authenticated_user</span></code> parameter was added.</p> </div> </dd></dl> <dl class="class"> <dt id="django.contrib.auth.views.LoginView"> <em class="property">class </em><code class="descname">LoginView</code><a class="headerlink" href="#django.contrib.auth.views.LoginView" title="Permalink to this definition">¶</a></dt> <dd><div class="versionadded"> <span class="title">New in Django 1.11.</span> </div> <p><strong>URL name:</strong> <code class="docutils literal notranslate"><span class="pre">login</span></code></p> <p>See <a class="reference internal" href="../http/urls.html"><span class="doc">the URL documentation</span></a> for details on using named URL patterns.</p> <p><strong>Attributes:</strong></p> <ul> <li><p class="first"><code class="docutils literal notranslate"><span class="pre">template_name</span></code>: The name of a template to display for the view used to log the user in. Defaults to <code class="file docutils literal notranslate"><span class="pre">registration/login.html</span></code>.</p> </li> <li><p class="first"><code class="docutils literal notranslate"><span class="pre">redirect_field_name</span></code>: The name of a <code class="docutils literal notranslate"><span class="pre">GET</span></code> field containing the URL to redirect to after login. Defaults to <code class="docutils literal notranslate"><span class="pre">next</span></code>.</p> </li> <li><p class="first"><code class="docutils literal notranslate"><span class="pre">authentication_form</span></code>: A callable (typically just a form class) to use for authentication. Defaults to <a class="reference internal" href="#django.contrib.auth.forms.AuthenticationForm" title="django.contrib.auth.forms.AuthenticationForm"><code class="xref py py-class docutils literal notranslate"><span class="pre">AuthenticationForm</span></code></a>.</p> </li> <li><p class="first"><code class="docutils literal notranslate"><span class="pre">extra_context</span></code>: A dictionary of context data that will be added to the default context data passed to the template.</p> </li> <li><p class="first"><code class="docutils literal notranslate"><span class="pre">redirect_authenticated_user</span></code>: 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 <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p> <div class="admonition warning"> <p class="first admonition-title">Warning</p> <p class="last">If you enable <code class="docutils literal notranslate"><span class="pre">redirect_authenticated_user</span></code>, 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 “<a class="reference external" href="https://robinlinus.github.io/socialmedia-leak/">social media fingerprinting</a>” information leakage, host all images and your favicon on a separate domain.</p> </div> </li> <li><p class="first"><code class="docutils literal notranslate"><span class="pre">success_url_allowed_hosts</span></code>: A <code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code> of hosts, in addition to <a class="reference internal" href="../../ref/request-response.html#django.http.HttpRequest.get_host" title="django.http.HttpRequest.get_host"><code class="xref py py-meth docutils literal notranslate"><span class="pre">request.get_host()</span></code></a>, that are safe for redirecting after login. Defaults to an empty <code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code>.</p> </li> </ul> <p>Here’s what <code class="docutils literal notranslate"><span class="pre">LoginView</span></code> does:</p> <ul class="simple"> <li>If called via <code class="docutils literal notranslate"><span class="pre">GET</span></code>, it displays a login form that POSTs to the same URL. More on this in a bit.</li> <li>If called via <code class="docutils literal notranslate"><span class="pre">POST</span></code> with user submitted credentials, it tries to log the user in. If login is successful, the view redirects to the URL specified in <code class="docutils literal notranslate"><span class="pre">next</span></code>. If <code class="docutils literal notranslate"><span class="pre">next</span></code> isn’t provided, it redirects to <a class="reference internal" href="../../ref/settings.html#std:setting-LOGIN_REDIRECT_URL"><code class="xref std std-setting docutils literal notranslate"><span class="pre">settings.LOGIN_REDIRECT_URL</span></code></a> (which defaults to <code class="docutils literal notranslate"><span class="pre">/accounts/profile/</span></code>). If login isn’t successful, it redisplays the login form.</li> </ul> <p>It’s your responsibility to provide the html for the login template , called <code class="docutils literal notranslate"><span class="pre">registration/login.html</span></code> by default. This template gets passed four template context variables:</p> <ul class="simple"> <li><code class="docutils literal notranslate"><span class="pre">form</span></code>: A <a class="reference internal" href="../../ref/forms/api.html#django.forms.Form" title="django.forms.Form"><code class="xref py py-class docutils literal notranslate"><span class="pre">Form</span></code></a> object representing the <a class="reference internal" href="#django.contrib.auth.forms.AuthenticationForm" title="django.contrib.auth.forms.AuthenticationForm"><code class="xref py py-class docutils literal notranslate"><span class="pre">AuthenticationForm</span></code></a>.</li> <li><code class="docutils literal notranslate"><span class="pre">next</span></code>: The URL to redirect to after successful login. This may contain a query string, too.</li> <li><code class="docutils literal notranslate"><span class="pre">site</span></code>: The current <a class="reference internal" href="../../ref/contrib/sites.html#django.contrib.sites.models.Site" title="django.contrib.sites.models.Site"><code class="xref py py-class docutils literal notranslate"><span class="pre">Site</span></code></a>, according to the <a class="reference internal" href="../../ref/settings.html#std:setting-SITE_ID"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SITE_ID</span></code></a> setting. If you don’t have the site framework installed, this will be set to an instance of <a class="reference internal" href="../../ref/contrib/sites.html#django.contrib.sites.requests.RequestSite" title="django.contrib.sites.requests.RequestSite"><code class="xref py py-class docutils literal notranslate"><span class="pre">RequestSite</span></code></a>, which derives the site name and domain from the current <a class="reference internal" href="../../ref/request-response.html#django.http.HttpRequest" title="django.http.HttpRequest"><code class="xref py py-class docutils literal notranslate"><span class="pre">HttpRequest</span></code></a>.</li> <li><code class="docutils literal notranslate"><span class="pre">site_name</span></code>: An alias for <code class="docutils literal notranslate"><span class="pre">site.name</span></code>. If you don’t have the site framework installed, this will be set to the value of <a class="reference internal" href="../../ref/request-response.html#django.http.HttpRequest.META" title="django.http.HttpRequest.META"><code class="xref py py-attr docutils literal notranslate"><span class="pre">request.META['SERVER_NAME']</span></code></a>. For more on sites, see <a class="reference internal" href="../../ref/contrib/sites.html"><span class="doc">The “sites” framework</span></a>.</li> </ul> <p>If you’d prefer not to call the template <code class="file docutils literal notranslate"><span class="pre">registration/login.html</span></code>, you can pass the <code class="docutils literal notranslate"><span class="pre">template_name</span></code> parameter via the extra arguments to the <code class="docutils literal notranslate"><span class="pre">as_view</span></code> method in your URLconf. For example, this URLconf line would use <code class="file docutils literal notranslate"><span class="pre">myapp/login.html</span></code> instead:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">url</span><span class="p">(</span><span class="sa">r</span><span class="s1">'^accounts/login/$'</span><span class="p">,</span> <span class="n">auth_views</span><span class="o">.</span><span class="n">LoginView</span><span class="o">.</span><span class="n">as_view</span><span class="p">(</span><span class="n">template_name</span><span class="o">=</span><span class="s1">'myapp/login.html'</span><span class="p">)),</span> </pre></div> </div> <p>You can also specify the name of the <code class="docutils literal notranslate"><span class="pre">GET</span></code> field which contains the URL to redirect to after login using <code class="docutils literal notranslate"><span class="pre">redirect_field_name</span></code>. By default, the field is called <code class="docutils literal notranslate"><span class="pre">next</span></code>.</p> <p>Here’s a sample <code class="file docutils literal notranslate"><span class="pre">registration/login.html</span></code> template you can use as a starting point. It assumes you have a <code class="file docutils literal notranslate"><span class="pre">base.html</span></code> template that defines a <code class="docutils literal notranslate"><span class="pre">content</span></code> block:</p> <div class="highlight-html+django notranslate"><div class="highlight"><pre><span></span><span class="cp">{%</span> <span class="k">extends</span> <span class="s2">"base.html"</span> <span class="cp">%}</span> <span class="cp">{%</span> <span class="k">block</span> <span class="nv">content</span> <span class="cp">%}</span> <span class="cp">{%</span> <span class="k">if</span> <span class="nv">form.errors</span> <span class="cp">%}</span> <span class="p"><</span><span class="nt">p</span><span class="p">></span>Your username and password didn't match. Please try again.<span class="p"></</span><span class="nt">p</span><span class="p">></span> <span class="cp">{%</span> <span class="k">endif</span> <span class="cp">%}</span> <span class="cp">{%</span> <span class="k">if</span> <span class="nv">next</span> <span class="cp">%}</span> <span class="cp">{%</span> <span class="k">if</span> <span class="nv">user.is_authenticated</span> <span class="cp">%}</span> <span class="p"><</span><span class="nt">p</span><span class="p">></span>Your account doesn't have access to this page. To proceed, please login with an account that has access.<span class="p"></</span><span class="nt">p</span><span class="p">></span> <span class="cp">{%</span> <span class="k">else</span> <span class="cp">%}</span> <span class="p"><</span><span class="nt">p</span><span class="p">></span>Please login to see this page.<span class="p"></</span><span class="nt">p</span><span class="p">></span> <span class="cp">{%</span> <span class="k">endif</span> <span class="cp">%}</span> <span class="cp">{%</span> <span class="k">endif</span> <span class="cp">%}</span> <span class="p"><</span><span class="nt">form</span> <span class="na">method</span><span class="o">=</span><span class="s">"post"</span> <span class="na">action</span><span class="o">=</span><span class="s">"</span><span class="cp">{%</span> <span class="k">url</span> <span class="s1">'login'</span> <span class="cp">%}</span><span class="s">"</span><span class="p">></span> <span class="cp">{%</span> <span class="k">csrf_token</span> <span class="cp">%}</span> <span class="p"><</span><span class="nt">table</span><span class="p">></span> <span class="p"><</span><span class="nt">tr</span><span class="p">></span> <span class="p"><</span><span class="nt">td</span><span class="p">></span><span class="cp">{{</span> <span class="nv">form.username.label_tag</span> <span class="cp">}}</span><span class="p"></</span><span class="nt">td</span><span class="p">></span> <span class="p"><</span><span class="nt">td</span><span class="p">></span><span class="cp">{{</span> <span class="nv">form.username</span> <span class="cp">}}</span><span class="p"></</span><span class="nt">td</span><span class="p">></span> <span class="p"></</span><span class="nt">tr</span><span class="p">></span> <span class="p"><</span><span class="nt">tr</span><span class="p">></span> <span class="p"><</span><span class="nt">td</span><span class="p">></span><span class="cp">{{</span> <span class="nv">form.password.label_tag</span> <span class="cp">}}</span><span class="p"></</span><span class="nt">td</span><span class="p">></span> <span class="p"><</span><span class="nt">td</span><span class="p">></span><span class="cp">{{</span> <span class="nv">form.password</span> <span class="cp">}}</span><span class="p"></</span><span class="nt">td</span><span class="p">></span> <span class="p"></</span><span class="nt">tr</span><span class="p">></span> <span class="p"></</span><span class="nt">table</span><span class="p">></span> <span class="p"><</span><span class="nt">input</span> <span class="na">type</span><span class="o">=</span><span class="s">"submit"</span> <span class="na">value</span><span class="o">=</span><span class="s">"login"</span> <span class="p">/></span> <span class="p"><</span><span class="nt">input</span> <span class="na">type</span><span class="o">=</span><span class="s">"hidden"</span> <span class="na">name</span><span class="o">=</span><span class="s">"next"</span> <span class="na">value</span><span class="o">=</span><span class="s">"</span><span class="cp">{{</span> <span class="nv">next</span> <span class="cp">}}</span><span class="s">"</span> <span class="p">/></span> <span class="p"></</span><span class="nt">form</span><span class="p">></span> <span class="c">{# Assumes you setup the password_reset view in your URLconf #}</span> <span class="p"><</span><span class="nt">p</span><span class="p">><</span><span class="nt">a</span> <span class="na">href</span><span class="o">=</span><span class="s">"</span><span class="cp">{%</span> <span class="k">url</span> <span class="s1">'password_reset'</span> <span class="cp">%}</span><span class="s">"</span><span class="p">></span>Lost password?<span class="p"></</span><span class="nt">a</span><span class="p">></</span><span class="nt">p</span><span class="p">></span> <span class="cp">{%</span> <span class="k">endblock</span> <span class="cp">%}</span> </pre></div> </div> <p>If you have customized authentication (see <a class="reference internal" href="customizing.html"><span class="doc">Customizing Authentication</span></a>) you can use a custom authentication form by setting the <code class="docutils literal notranslate"><span class="pre">authentication_form</span></code> attribute. This form must accept a <code class="docutils literal notranslate"><span class="pre">request</span></code> keyword argument in its <code class="docutils literal notranslate"><span class="pre">__init__()</span></code> method and provide a <code class="docutils literal notranslate"><span class="pre">get_user()</span></code> method which returns the authenticated user object (this method is only ever called after successful form validation).</p> </dd></dl> <dl class="function"> <dt id="django.contrib.auth.views.logout"> <code class="descname">logout</code>(<em>request</em>, <em>next_page=None</em>, <em>template_name='registration/logged_out.html'</em>, <em>redirect_field_name='next'</em>, <em>current_app=None</em>, <em>extra_context=None</em>)<a class="headerlink" href="#django.contrib.auth.views.logout" title="Permalink to this definition">¶</a></dt> <dd><div class="deprecated"> <p><span class="versionmodified">Deprecated since version 1.11: </span>The <code class="docutils literal notranslate"><span class="pre">logout</span></code> function-based view should be replaced by the class-based <a class="reference internal" href="#django.contrib.auth.views.LogoutView" title="django.contrib.auth.views.LogoutView"><code class="xref py py-class docutils literal notranslate"><span class="pre">LogoutView</span></code></a>.</p> </div> <p>The optional arguments of this view are similar to the class-based <code class="docutils literal notranslate"><span class="pre">LogoutView</span></code> attributes. In addition, it has:</p> <ul class="simple"> <li><code class="docutils literal notranslate"><span class="pre">current_app</span></code>: A hint indicating which application contains the current view. See the <a class="reference internal" href="../http/urls.html#topics-http-reversing-url-namespaces"><span class="std std-ref">namespaced URL resolution strategy</span></a> for more information.</li> </ul> <div class="deprecated"> <p><span class="versionmodified">Deprecated since version 1.9: </span>The <code class="docutils literal notranslate"><span class="pre">current_app</span></code> attribute is deprecated and will be removed in Django 2.0. Callers should set <code class="docutils literal notranslate"><span class="pre">request.current_app</span></code> instead.</p> </div> </dd></dl> <dl class="class"> <dt id="django.contrib.auth.views.LogoutView"> <em class="property">class </em><code class="descname">LogoutView</code><a class="headerlink" href="#django.contrib.auth.views.LogoutView" title="Permalink to this definition">¶</a></dt> <dd><div class="versionadded"> <span class="title">New in Django 1.11.</span> </div> <p>Logs a user out.</p> <p><strong>URL name:</strong> <code class="docutils literal notranslate"><span class="pre">logout</span></code></p> <p><strong>Attributes:</strong></p> <ul class="simple"> <li><code class="docutils literal notranslate"><span class="pre">next_page</span></code>: The URL to redirect to after logout. Defaults to <a class="reference internal" href="../../ref/settings.html#std:setting-LOGOUT_REDIRECT_URL"><code class="xref std std-setting docutils literal notranslate"><span class="pre">settings.LOGOUT_REDIRECT_URL</span></code></a>.</li> <li><code class="docutils literal notranslate"><span class="pre">template_name</span></code>: The full name of a template to display after logging the user out. Defaults to <code class="file docutils literal notranslate"><span class="pre">registration/logged_out.html</span></code>.</li> <li><code class="docutils literal notranslate"><span class="pre">redirect_field_name</span></code>: The name of a <code class="docutils literal notranslate"><span class="pre">GET</span></code> field containing the URL to redirect to after log out. Defaults to <code class="docutils literal notranslate"><span class="pre">next</span></code>. Overrides the <code class="docutils literal notranslate"><span class="pre">next_page</span></code> URL if the given <code class="docutils literal notranslate"><span class="pre">GET</span></code> parameter is passed.</li> <li><code class="docutils literal notranslate"><span class="pre">extra_context</span></code>: A dictionary of context data that will be added to the default context data passed to the template.</li> <li><code class="docutils literal notranslate"><span class="pre">success_url_allowed_hosts</span></code>: A <code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code> of hosts, in addition to <a class="reference internal" href="../../ref/request-response.html#django.http.HttpRequest.get_host" title="django.http.HttpRequest.get_host"><code class="xref py py-meth docutils literal notranslate"><span class="pre">request.get_host()</span></code></a>, that are safe for redirecting after logout. Defaults to an empty <code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code>.</li> </ul> <p><strong>Template context:</strong></p> <ul class="simple"> <li><code class="docutils literal notranslate"><span class="pre">title</span></code>: The string “Logged out”, localized.</li> <li><code class="docutils literal notranslate"><span class="pre">site</span></code>: The current <a class="reference internal" href="../../ref/contrib/sites.html#django.contrib.sites.models.Site" title="django.contrib.sites.models.Site"><code class="xref py py-class docutils literal notranslate"><span class="pre">Site</span></code></a>, according to the <a class="reference internal" href="../../ref/settings.html#std:setting-SITE_ID"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SITE_ID</span></code></a> setting. If you don’t have the site framework installed, this will be set to an instance of <a class="reference internal" href="../../ref/contrib/sites.html#django.contrib.sites.requests.RequestSite" title="django.contrib.sites.requests.RequestSite"><code class="xref py py-class docutils literal notranslate"><span class="pre">RequestSite</span></code></a>, which derives the site name and domain from the current <a class="reference internal" href="../../ref/request-response.html#django.http.HttpRequest" title="django.http.HttpRequest"><code class="xref py py-class docutils literal notranslate"><span class="pre">HttpRequest</span></code></a>.</li> <li><code class="docutils literal notranslate"><span class="pre">site_name</span></code>: An alias for <code class="docutils literal notranslate"><span class="pre">site.name</span></code>. If you don’t have the site framework installed, this will be set to the value of <a class="reference internal" href="../../ref/request-response.html#django.http.HttpRequest.META" title="django.http.HttpRequest.META"><code class="xref py py-attr docutils literal notranslate"><span class="pre">request.META['SERVER_NAME']</span></code></a>. For more on sites, see <a class="reference internal" href="../../ref/contrib/sites.html"><span class="doc">The “sites” framework</span></a>.</li> </ul> </dd></dl> <dl class="function"> <dt id="django.contrib.auth.views.logout_then_login"> <code class="descname">logout_then_login</code>(<em>request</em>, <em>login_url=None</em>, <em>current_app=None</em>, <em>extra_context=None</em>)<a class="headerlink" href="#django.contrib.auth.views.logout_then_login" title="Permalink to this definition">¶</a></dt> <dd><p>Logs a user out, then redirects to the login page.</p> <p><strong>URL name:</strong> No default URL provided</p> <p><strong>Optional arguments:</strong></p> <ul class="simple"> <li><code class="docutils literal notranslate"><span class="pre">login_url</span></code>: The URL of the login page to redirect to. Defaults to <a class="reference internal" href="../../ref/settings.html#std:setting-LOGIN_URL"><code class="xref std std-setting docutils literal notranslate"><span class="pre">settings.LOGIN_URL</span></code></a> if not supplied.</li> <li><code class="docutils literal notranslate"><span class="pre">current_app</span></code>: A hint indicating which application contains the current view. See the <a class="reference internal" href="../http/urls.html#topics-http-reversing-url-namespaces"><span class="std std-ref">namespaced URL resolution strategy</span></a> for more information.</li> <li><code class="docutils literal notranslate"><span class="pre">extra_context</span></code>: A dictionary of context data that will be added to the default context data passed to the template.</li> </ul> <div class="deprecated"> <p><span class="versionmodified">Deprecated since version 1.9: </span>The <code class="docutils literal notranslate"><span class="pre">current_app</span></code> parameter is deprecated and will be removed in Django 2.0. Callers should set <code class="docutils literal notranslate"><span class="pre">request.current_app</span></code> instead.</p> </div> <div class="deprecated"> <p><span class="versionmodified">Deprecated since version 1.11: </span>The unused <code class="docutils literal notranslate"><span class="pre">extra_context</span></code> parameter is deprecated and will be removed in Django 2.1.</p> </div> </dd></dl> <dl class="function"> <dt id="django.contrib.auth.views.password_change"> <code class="descname">password_change</code>(<em>request</em>, <em>template_name='registration/password_change_form.html'</em>, <em>post_change_redirect=None</em>, <em>password_change_form=PasswordChangeForm</em>, <em>current_app=None</em>, <em>extra_context=None</em>)<a class="headerlink" href="#django.contrib.auth.views.password_change" title="Permalink to this definition">¶</a></dt> <dd><div class="deprecated"> <p><span class="versionmodified">Deprecated since version 1.11: </span>The <code class="docutils literal notranslate"><span class="pre">password_change</span></code> function-based view should be replaced by the class-based <a class="reference internal" href="#django.contrib.auth.views.PasswordChangeView" title="django.contrib.auth.views.PasswordChangeView"><code class="xref py py-class docutils literal notranslate"><span class="pre">PasswordChangeView</span></code></a>.</p> </div> <p>The optional arguments of this view are similar to the class-based <code class="docutils literal notranslate"><span class="pre">PasswordChangeView</span></code> attributes, except the <code class="docutils literal notranslate"><span class="pre">post_change_redirect</span></code> and <code class="docutils literal notranslate"><span class="pre">password_change_form</span></code> arguments which map to the <code class="docutils literal notranslate"><span class="pre">success_url</span></code> and <code class="docutils literal notranslate"><span class="pre">form_class</span></code> attributes of the class-based view. In addition, it has:</p> <ul class="simple"> <li><code class="docutils literal notranslate"><span class="pre">current_app</span></code>: A hint indicating which application contains the current view. See the <a class="reference internal" href="../http/urls.html#topics-http-reversing-url-namespaces"><span class="std std-ref">namespaced URL resolution strategy</span></a> for more information.</li> </ul> <div class="deprecated"> <p><span class="versionmodified">Deprecated since version 1.9: </span>The <code class="docutils literal notranslate"><span class="pre">current_app</span></code> parameter is deprecated and will be removed in Django 2.0. Callers should set <code class="docutils literal notranslate"><span class="pre">request.current_app</span></code> instead.</p> </div> </dd></dl> <dl class="class"> <dt id="django.contrib.auth.views.PasswordChangeView"> <em class="property">class </em><code class="descname">PasswordChangeView</code><a class="headerlink" href="#django.contrib.auth.views.PasswordChangeView" title="Permalink to this definition">¶</a></dt> <dd><div class="versionadded"> <span class="title">New in Django 1.11.</span> </div> <p><strong>URL name:</strong> <code class="docutils literal notranslate"><span class="pre">password_change</span></code></p> <p>Allows a user to change their password.</p> <p><strong>Attributes:</strong></p> <ul class="simple"> <li><code class="docutils literal notranslate"><span class="pre">template_name</span></code>: The full name of a template to use for displaying the password change form. Defaults to <code class="file docutils literal notranslate"><span class="pre">registration/password_change_form.html</span></code> if not supplied.</li> <li><code class="docutils literal notranslate"><span class="pre">success_url</span></code>: The URL to redirect to after a successful password change.</li> <li><code class="docutils literal notranslate"><span class="pre">form_class</span></code>: A custom “change password” form which must accept a <code class="docutils literal notranslate"><span class="pre">user</span></code> keyword argument. The form is responsible for actually changing the user’s password. Defaults to <a class="reference internal" href="#django.contrib.auth.forms.PasswordChangeForm" title="django.contrib.auth.forms.PasswordChangeForm"><code class="xref py py-class docutils literal notranslate"><span class="pre">PasswordChangeForm</span></code></a>.</li> <li><code class="docutils literal notranslate"><span class="pre">extra_context</span></code>: A dictionary of context data that will be added to the default context data passed to the template.</li> </ul> <p><strong>Template context:</strong></p> <ul class="simple"> <li><code class="docutils literal notranslate"><span class="pre">form</span></code>: The password change form (see <code class="docutils literal notranslate"><span class="pre">form_class</span></code> above).</li> </ul> </dd></dl> <dl class="function"> <dt id="django.contrib.auth.views.password_change_done"> <code class="descname">password_change_done</code>(<em>request</em>, <em>template_name='registration/password_change_done.html'</em>, <em>current_app=None</em>, <em>extra_context=None</em>)<a class="headerlink" href="#django.contrib.auth.views.password_change_done" title="Permalink to this definition">¶</a></dt> <dd><div class="deprecated"> <p><span class="versionmodified">Deprecated since version 1.11: </span>The <code class="docutils literal notranslate"><span class="pre">password_change_done</span></code> function-based view should be replaced by the class-based <a class="reference internal" href="#django.contrib.auth.views.PasswordChangeDoneView" title="django.contrib.auth.views.PasswordChangeDoneView"><code class="xref py py-class docutils literal notranslate"><span class="pre">PasswordChangeDoneView</span></code></a>.</p> </div> <p>The optional arguments of this view are similar to the class-based <code class="docutils literal notranslate"><span class="pre">PasswordChangeDoneView</span></code> attributes. In addition, it has:</p> <ul class="simple"> <li><code class="docutils literal notranslate"><span class="pre">current_app</span></code>: A hint indicating which application contains the current view. See the <a class="reference internal" href="../http/urls.html#topics-http-reversing-url-namespaces"><span class="std std-ref">namespaced URL resolution strategy</span></a> for more information.</li> </ul> <div class="deprecated"> <p><span class="versionmodified">Deprecated since version 1.9: </span>The <code class="docutils literal notranslate"><span class="pre">current_app</span></code> parameter is deprecated and will be removed in Django 2.0. Callers should set <code class="docutils literal notranslate"><span class="pre">request.current_app</span></code> instead.</p> </div> </dd></dl> <dl class="class"> <dt id="django.contrib.auth.views.PasswordChangeDoneView"> <em class="property">class </em><code class="descname">PasswordChangeDoneView</code><a class="headerlink" href="#django.contrib.auth.views.PasswordChangeDoneView" title="Permalink to this definition">¶</a></dt> <dd><div class="versionadded"> <span class="title">New in Django 1.11.</span> </div> <p><strong>URL name:</strong> <code class="docutils literal notranslate"><span class="pre">password_change_done</span></code></p> <p>The page shown after a user has changed their password.</p> <p><strong>Attributes:</strong></p> <ul class="simple"> <li><code class="docutils literal notranslate"><span class="pre">template_name</span></code>: The full name of a template to use. Defaults to <code class="file docutils literal notranslate"><span class="pre">registration/password_change_done.html</span></code> if not supplied.</li> <li><code class="docutils literal notranslate"><span class="pre">extra_context</span></code>: A dictionary of context data that will be added to the default context data passed to the template.</li> </ul> </dd></dl> <dl class="function"> <dt id="django.contrib.auth.views.password_reset"> <code class="descname">password_reset</code>(<em>request</em>, <em>template_name='registration/password_reset_form.html'</em>, <em>email_template_name='registration/password_reset_email.html'</em>, <em>subject_template_name='registration/password_reset_subject.txt'</em>, <em>password_reset_form=PasswordResetForm</em>, <em>token_generator=default_token_generator</em>, <em>post_reset_redirect=None</em>, <em>from_email=None</em>, <em>current_app=None</em>, <em>extra_context=None</em>, <em>html_email_template_name=None</em>, <em>extra_email_context=None</em>)<a class="headerlink" href="#django.contrib.auth.views.password_reset" title="Permalink to this definition">¶</a></dt> <dd><div class="deprecated"> <p><span class="versionmodified">Deprecated since version 1.11: </span>The <code class="docutils literal notranslate"><span class="pre">password_reset</span></code> function-based view should be replaced by the class-based <a class="reference internal" href="#django.contrib.auth.views.PasswordResetView" title="django.contrib.auth.views.PasswordResetView"><code class="xref py py-class docutils literal notranslate"><span class="pre">PasswordResetView</span></code></a>.</p> </div> <p>The optional arguments of this view are similar to the class-based <code class="docutils literal notranslate"><span class="pre">PasswordResetView</span></code> attributes, except the <code class="docutils literal notranslate"><span class="pre">post_reset_redirect</span></code> and <code class="docutils literal notranslate"><span class="pre">password_reset_form</span></code> arguments which map to the <code class="docutils literal notranslate"><span class="pre">success_url</span></code> and <code class="docutils literal notranslate"><span class="pre">form_class</span></code> attributes of the class-based view. In addition, it has:</p> <ul class="simple"> <li><code class="docutils literal notranslate"><span class="pre">current_app</span></code>: A hint indicating which application contains the current view. See the <a class="reference internal" href="../http/urls.html#topics-http-reversing-url-namespaces"><span class="std std-ref">namespaced URL resolution strategy</span></a> for more information.</li> </ul> <div class="deprecated"> <p><span class="versionmodified">Deprecated since version 1.9: </span>The <code class="docutils literal notranslate"><span class="pre">current_app</span></code> parameter is deprecated and will be removed in Django 2.0. Callers should set <code class="docutils literal notranslate"><span class="pre">request.current_app</span></code> instead.</p> </div> </dd></dl> <dl class="class"> <dt id="django.contrib.auth.views.PasswordResetView"> <em class="property">class </em><code class="descname">PasswordResetView</code><a class="headerlink" href="#django.contrib.auth.views.PasswordResetView" title="Permalink to this definition">¶</a></dt> <dd><div class="versionadded"> <span class="title">New in Django 1.11.</span> </div> <p><strong>URL name:</strong> <code class="docutils literal notranslate"><span class="pre">password_reset</span></code></p> <p>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.</p> <p>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 <a class="reference internal" href="#django.contrib.auth.forms.PasswordResetForm" title="django.contrib.auth.forms.PasswordResetForm"><code class="xref py py-class docutils literal notranslate"><span class="pre">PasswordResetForm</span></code></a> and use the <code class="docutils literal notranslate"><span class="pre">form_class</span></code> attribute.</p> <p>Users flagged with an unusable password (see <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User.set_unusable_password" title="django.contrib.auth.models.User.set_unusable_password"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_unusable_password()</span></code></a> 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.</p> <p><strong>Attributes:</strong></p> <ul class="simple"> <li><code class="docutils literal notranslate"><span class="pre">template_name</span></code>: The full name of a template to use for displaying the password reset form. Defaults to <code class="file docutils literal notranslate"><span class="pre">registration/password_reset_form.html</span></code> if not supplied.</li> <li><code class="docutils literal notranslate"><span class="pre">form_class</span></code>: Form that will be used to get the email of the user to reset the password for. Defaults to <a class="reference internal" href="#django.contrib.auth.forms.PasswordResetForm" title="django.contrib.auth.forms.PasswordResetForm"><code class="xref py py-class docutils literal notranslate"><span class="pre">PasswordResetForm</span></code></a>.</li> <li><code class="docutils literal notranslate"><span class="pre">email_template_name</span></code>: The full name of a template to use for generating the email with the reset password link. Defaults to <code class="file docutils literal notranslate"><span class="pre">registration/password_reset_email.html</span></code> if not supplied.</li> <li><code class="docutils literal notranslate"><span class="pre">subject_template_name</span></code>: The full name of a template to use for the subject of the email with the reset password link. Defaults to <code class="file docutils literal notranslate"><span class="pre">registration/password_reset_subject.txt</span></code> if not supplied.</li> <li><code class="docutils literal notranslate"><span class="pre">token_generator</span></code>: Instance of the class to check the one time link. This will default to <code class="docutils literal notranslate"><span class="pre">default_token_generator</span></code>, it’s an instance of <code class="docutils literal notranslate"><span class="pre">django.contrib.auth.tokens.PasswordResetTokenGenerator</span></code>.</li> <li><code class="docutils literal notranslate"><span class="pre">success_url</span></code>: The URL to redirect to after a successful password reset request.</li> <li><code class="docutils literal notranslate"><span class="pre">from_email</span></code>: A valid email address. By default Django uses the <a class="reference internal" href="../../ref/settings.html#std:setting-DEFAULT_FROM_EMAIL"><code class="xref std std-setting docutils literal notranslate"><span class="pre">DEFAULT_FROM_EMAIL</span></code></a>.</li> <li><code class="docutils literal notranslate"><span class="pre">extra_context</span></code>: A dictionary of context data that will be added to the default context data passed to the template.</li> <li><code class="docutils literal notranslate"><span class="pre">html_email_template_name</span></code>: The full name of a template to use for generating a <code class="docutils literal notranslate"><span class="pre">text/html</span></code> multipart email with the password reset link. By default, HTML email is not sent.</li> <li><code class="docutils literal notranslate"><span class="pre">extra_email_context</span></code>: A dictionary of context data that will be available in the email template.</li> </ul> <p><strong>Template context:</strong></p> <ul class="simple"> <li><code class="docutils literal notranslate"><span class="pre">form</span></code>: The form (see <code class="docutils literal notranslate"><span class="pre">form_class</span></code> above) for resetting the user’s password.</li> </ul> <p><strong>Email template context:</strong></p> <ul class="simple"> <li><code class="docutils literal notranslate"><span class="pre">email</span></code>: An alias for <code class="docutils literal notranslate"><span class="pre">user.email</span></code></li> <li><code class="docutils literal notranslate"><span class="pre">user</span></code>: The current <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User" title="django.contrib.auth.models.User"><code class="xref py py-class docutils literal notranslate"><span class="pre">User</span></code></a>, according to the <code class="docutils literal notranslate"><span class="pre">email</span></code> form field. Only active users are able to reset their passwords (<code class="docutils literal notranslate"><span class="pre">User.is_active</span> <span class="pre">is</span> <span class="pre">True</span></code>).</li> <li><code class="docutils literal notranslate"><span class="pre">site_name</span></code>: An alias for <code class="docutils literal notranslate"><span class="pre">site.name</span></code>. If you don’t have the site framework installed, this will be set to the value of <a class="reference internal" href="../../ref/request-response.html#django.http.HttpRequest.META" title="django.http.HttpRequest.META"><code class="xref py py-attr docutils literal notranslate"><span class="pre">request.META['SERVER_NAME']</span></code></a>. For more on sites, see <a class="reference internal" href="../../ref/contrib/sites.html"><span class="doc">The “sites” framework</span></a>.</li> <li><code class="docutils literal notranslate"><span class="pre">domain</span></code>: An alias for <code class="docutils literal notranslate"><span class="pre">site.domain</span></code>. If you don’t have the site framework installed, this will be set to the value of <code class="docutils literal notranslate"><span class="pre">request.get_host()</span></code>.</li> <li><code class="docutils literal notranslate"><span class="pre">protocol</span></code>: http or https</li> <li><code class="docutils literal notranslate"><span class="pre">uid</span></code>: The user’s primary key encoded in base 64.</li> <li><code class="docutils literal notranslate"><span class="pre">token</span></code>: Token to check that the reset link is valid.</li> </ul> <p>Sample <code class="docutils literal notranslate"><span class="pre">registration/password_reset_email.html</span></code> (email body template):</p> <div class="highlight-html+django notranslate"><div class="highlight"><pre><span></span>Someone asked for password reset for email <span class="cp">{{</span> <span class="nv">email</span> <span class="cp">}}</span>. Follow the link below: <span class="cp">{{</span> <span class="nv">protocol</span><span class="cp">}}</span>://<span class="cp">{{</span> <span class="nv">domain</span> <span class="cp">}}{%</span> <span class="k">url</span> <span class="s1">'password_reset_confirm'</span> <span class="nv">uidb64</span><span class="o">=</span><span class="nv">uid</span> <span class="nv">token</span><span class="o">=</span><span class="nv">token</span> <span class="cp">%}</span> </pre></div> </div> <p>The same template context is used for subject template. Subject must be single line plain text string.</p> </dd></dl> <dl class="function"> <dt id="django.contrib.auth.views.password_reset_done"> <code class="descname">password_reset_done</code>(<em>request</em>, <em>template_name='registration/password_reset_done.html'</em>, <em>current_app=None</em>, <em>extra_context=None</em>)<a class="headerlink" href="#django.contrib.auth.views.password_reset_done" title="Permalink to this definition">¶</a></dt> <dd><div class="deprecated"> <p><span class="versionmodified">Deprecated since version 1.11: </span>The <code class="docutils literal notranslate"><span class="pre">password_reset_done</span></code> function-based view should be replaced by the class-based <a class="reference internal" href="#django.contrib.auth.views.PasswordResetDoneView" title="django.contrib.auth.views.PasswordResetDoneView"><code class="xref py py-class docutils literal notranslate"><span class="pre">PasswordResetDoneView</span></code></a>.</p> </div> <p>The optional arguments of this view are similar to the class-based <code class="docutils literal notranslate"><span class="pre">PasswordResetDoneView</span></code> attributes. In addition, it has:</p> <ul class="simple"> <li><code class="docutils literal notranslate"><span class="pre">current_app</span></code>: A hint indicating which application contains the current view. See the <a class="reference internal" href="../http/urls.html#topics-http-reversing-url-namespaces"><span class="std std-ref">namespaced URL resolution strategy</span></a> for more information.</li> </ul> <div class="deprecated"> <p><span class="versionmodified">Deprecated since version 1.9: </span>The <code class="docutils literal notranslate"><span class="pre">current_app</span></code> parameter is deprecated and will be removed in Django 2.0. Callers should set <code class="docutils literal notranslate"><span class="pre">request.current_app</span></code> instead.</p> </div> </dd></dl> <dl class="class"> <dt id="django.contrib.auth.views.PasswordResetDoneView"> <em class="property">class </em><code class="descname">PasswordResetDoneView</code><a class="headerlink" href="#django.contrib.auth.views.PasswordResetDoneView" title="Permalink to this definition">¶</a></dt> <dd><div class="versionadded"> <span class="title">New in Django 1.11.</span> </div> <p><strong>URL name:</strong> <code class="docutils literal notranslate"><span class="pre">password_reset_done</span></code></p> <p>The page shown after a user has been emailed a link to reset their password. This view is called by default if the <a class="reference internal" href="#django.contrib.auth.views.PasswordResetView" title="django.contrib.auth.views.PasswordResetView"><code class="xref py py-class docutils literal notranslate"><span class="pre">PasswordResetView</span></code></a> doesn’t have an explicit <code class="docutils literal notranslate"><span class="pre">success_url</span></code> URL set.</p> <div class="admonition note"> <p class="first admonition-title">Note</p> <p class="last">If the email address provided does not exist in the system, the user is inactive, or has an unusable password, the user will still be redirected to this view but no email will be sent.</p> </div> <p><strong>Attributes:</strong></p> <ul class="simple"> <li><code class="docutils literal notranslate"><span class="pre">template_name</span></code>: The full name of a template to use. Defaults to <code class="file docutils literal notranslate"><span class="pre">registration/password_reset_done.html</span></code> if not supplied.</li> <li><code class="docutils literal notranslate"><span class="pre">extra_context</span></code>: A dictionary of context data that will be added to the default context data passed to the template.</li> </ul> </dd></dl> <dl class="function"> <dt id="django.contrib.auth.views.password_reset_confirm"> <code class="descname">password_reset_confirm</code>(<em>request</em>, <em>uidb64=None</em>, <em>token=None</em>, <em>template_name='registration/password_reset_confirm.html'</em>, <em>token_generator=default_token_generator</em>, <em>set_password_form=SetPasswordForm</em>, <em>post_reset_redirect=None</em>, <em>current_app=None</em>, <em>extra_context=None</em>)<a class="headerlink" href="#django.contrib.auth.views.password_reset_confirm" title="Permalink to this definition">¶</a></dt> <dd><div class="deprecated"> <p><span class="versionmodified">Deprecated since version 1.11: </span>The <code class="docutils literal notranslate"><span class="pre">password_reset_confirm</span></code> function-based view should be replaced by the class-based <a class="reference internal" href="#django.contrib.auth.views.PasswordResetConfirmView" title="django.contrib.auth.views.PasswordResetConfirmView"><code class="xref py py-class docutils literal notranslate"><span class="pre">PasswordResetConfirmView</span></code></a>.</p> </div> <p>The optional arguments of this view are similar to the class-based <code class="docutils literal notranslate"><span class="pre">PasswordResetConfirmView</span></code> attributes, except the <code class="docutils literal notranslate"><span class="pre">post_reset_redirect</span></code> and <code class="docutils literal notranslate"><span class="pre">set_password_form</span></code> arguments which map to the <code class="docutils literal notranslate"><span class="pre">success_url</span></code> and <code class="docutils literal notranslate"><span class="pre">form_class</span></code> attributes of the class-based view. In addition, it has:</p> <ul class="simple"> <li><code class="docutils literal notranslate"><span class="pre">current_app</span></code>: A hint indicating which application contains the current view. See the <a class="reference internal" href="../http/urls.html#topics-http-reversing-url-namespaces"><span class="std std-ref">namespaced URL resolution strategy</span></a> for more information.</li> </ul> <div class="deprecated"> <p><span class="versionmodified">Deprecated since version 1.9: </span>The <code class="docutils literal notranslate"><span class="pre">current_app</span></code> parameter is deprecated and will be removed in Django 2.0. Callers should set <code class="docutils literal notranslate"><span class="pre">request.current_app</span></code> instead.</p> </div> </dd></dl> <dl class="class"> <dt id="django.contrib.auth.views.PasswordResetConfirmView"> <em class="property">class </em><code class="descname">PasswordResetConfirmView</code><a class="headerlink" href="#django.contrib.auth.views.PasswordResetConfirmView" title="Permalink to this definition">¶</a></dt> <dd><div class="versionadded"> <span class="title">New in Django 1.11.</span> </div> <p><strong>URL name:</strong> <code class="docutils literal notranslate"><span class="pre">password_reset_confirm</span></code></p> <p>Presents a form for entering a new password.</p> <p><strong>Keyword arguments from the URL:</strong></p> <ul class="simple"> <li><code class="docutils literal notranslate"><span class="pre">uidb64</span></code>: The user’s id encoded in base 64.</li> <li><code class="docutils literal notranslate"><span class="pre">token</span></code>: Token to check that the password is valid.</li> </ul> <p><strong>Attributes:</strong></p> <ul class="simple"> <li><code class="docutils literal notranslate"><span class="pre">template_name</span></code>: The full name of a template to display the confirm password view. Default value is <code class="file docutils literal notranslate"><span class="pre">registration/password_reset_confirm.html</span></code>.</li> <li><code class="docutils literal notranslate"><span class="pre">token_generator</span></code>: Instance of the class to check the password. This will default to <code class="docutils literal notranslate"><span class="pre">default_token_generator</span></code>, it’s an instance of <code class="docutils literal notranslate"><span class="pre">django.contrib.auth.tokens.PasswordResetTokenGenerator</span></code>.</li> <li><code class="docutils literal notranslate"><span class="pre">post_reset_login</span></code>: A boolean indicating if the user should be automatically authenticated after a successful password reset. Defaults to <code class="docutils literal notranslate"><span class="pre">False</span></code>.</li> <li><code class="docutils literal notranslate"><span class="pre">post_reset_login_backend</span></code>: A dotted path to the authentication backend to use when authenticating a user if <code class="docutils literal notranslate"><span class="pre">post_reset_login</span></code> is <code class="docutils literal notranslate"><span class="pre">True</span></code>. Required only if you have multiple <a class="reference internal" href="../../ref/settings.html#std:setting-AUTHENTICATION_BACKENDS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">AUTHENTICATION_BACKENDS</span></code></a> configured. Defaults to <code class="docutils literal notranslate"><span class="pre">None</span></code>.</li> <li><code class="docutils literal notranslate"><span class="pre">form_class</span></code>: Form that will be used to set the password. Defaults to <a class="reference internal" href="#django.contrib.auth.forms.SetPasswordForm" title="django.contrib.auth.forms.SetPasswordForm"><code class="xref py py-class docutils literal notranslate"><span class="pre">SetPasswordForm</span></code></a>.</li> <li><code class="docutils literal notranslate"><span class="pre">success_url</span></code>: URL to redirect after the password reset done. Defaults to <code class="docutils literal notranslate"><span class="pre">'password_reset_complete'</span></code>.</li> <li><code class="docutils literal notranslate"><span class="pre">extra_context</span></code>: A dictionary of context data that will be added to the default context data passed to the template.</li> </ul> <p><strong>Template context:</strong></p> <ul class="simple"> <li><code class="docutils literal notranslate"><span class="pre">form</span></code>: The form (see <code class="docutils literal notranslate"><span class="pre">set_password_form</span></code> above) for setting the new user’s password.</li> <li><code class="docutils literal notranslate"><span class="pre">validlink</span></code>: Boolean, True if the link (combination of <code class="docutils literal notranslate"><span class="pre">uidb64</span></code> and <code class="docutils literal notranslate"><span class="pre">token</span></code>) is valid or unused yet.</li> </ul> </dd></dl> <dl class="function"> <dt id="django.contrib.auth.views.password_reset_complete"> <code class="descname">password_reset_complete</code>(<em>request</em>, <em>template_name='registration/password_reset_complete.html'</em>, <em>current_app=None</em>, <em>extra_context=None</em>)<a class="headerlink" href="#django.contrib.auth.views.password_reset_complete" title="Permalink to this definition">¶</a></dt> <dd><div class="deprecated"> <p><span class="versionmodified">Deprecated since version 1.11: </span>The <code class="docutils literal notranslate"><span class="pre">password_reset_complete</span></code> function-based view should be replaced by the class-based <a class="reference internal" href="#django.contrib.auth.views.PasswordResetCompleteView" title="django.contrib.auth.views.PasswordResetCompleteView"><code class="xref py py-class docutils literal notranslate"><span class="pre">PasswordResetCompleteView</span></code></a>.</p> </div> <p>The optional arguments of this view are similar to the class-based <code class="docutils literal notranslate"><span class="pre">PasswordResetCompleteView</span></code> attributes. In addition, it has:</p> <ul class="simple"> <li><code class="docutils literal notranslate"><span class="pre">current_app</span></code>: A hint indicating which application contains the current view. See the <a class="reference internal" href="../http/urls.html#topics-http-reversing-url-namespaces"><span class="std std-ref">namespaced URL resolution strategy</span></a> for more information.</li> </ul> <div class="deprecated"> <p><span class="versionmodified">Deprecated since version 1.9: </span>The <code class="docutils literal notranslate"><span class="pre">current_app</span></code> parameter is deprecated and will be removed in Django 2.0. Callers should set <code class="docutils literal notranslate"><span class="pre">request.current_app</span></code> instead.</p> </div> </dd></dl> <dl class="class"> <dt id="django.contrib.auth.views.PasswordResetCompleteView"> <em class="property">class </em><code class="descname">PasswordResetCompleteView</code><a class="headerlink" href="#django.contrib.auth.views.PasswordResetCompleteView" title="Permalink to this definition">¶</a></dt> <dd><div class="versionadded"> <span class="title">New in Django 1.11.</span> </div> <p><strong>URL name:</strong> <code class="docutils literal notranslate"><span class="pre">password_reset_complete</span></code></p> <p>Presents a view which informs the user that the password has been successfully changed.</p> <p><strong>Attributes:</strong></p> <ul class="simple"> <li><code class="docutils literal notranslate"><span class="pre">template_name</span></code>: The full name of a template to display the view. Defaults to <code class="file docutils literal notranslate"><span class="pre">registration/password_reset_complete.html</span></code>.</li> <li><code class="docutils literal notranslate"><span class="pre">extra_context</span></code>: A dictionary of context data that will be added to the default context data passed to the template.</li> </ul> </dd></dl> </div> </div> <div class="section" id="s-helper-functions"> <span id="helper-functions"></span><h3>Helper functions<a class="headerlink" href="#helper-functions" title="Permalink to this headline">¶</a></h3> <dl class="function"> <dt id="django.contrib.auth.views.redirect_to_login"> <code class="descname">redirect_to_login</code>(<em>next</em>, <em>login_url=None</em>, <em>redirect_field_name='next'</em>)<a class="headerlink" href="#django.contrib.auth.views.redirect_to_login" title="Permalink to this definition">¶</a></dt> <dd><p>Redirects to the login page, and then back to another URL after a successful login.</p> <p><strong>Required arguments:</strong></p> <ul class="simple"> <li><code class="docutils literal notranslate"><span class="pre">next</span></code>: The URL to redirect to after a successful login.</li> </ul> <p><strong>Optional arguments:</strong></p> <ul class="simple"> <li><code class="docutils literal notranslate"><span class="pre">login_url</span></code>: The URL of the login page to redirect to. Defaults to <a class="reference internal" href="../../ref/settings.html#std:setting-LOGIN_URL"><code class="xref std std-setting docutils literal notranslate"><span class="pre">settings.LOGIN_URL</span></code></a> if not supplied.</li> <li><code class="docutils literal notranslate"><span class="pre">redirect_field_name</span></code>: The name of a <code class="docutils literal notranslate"><span class="pre">GET</span></code> field containing the URL to redirect to after log out. Overrides <code class="docutils literal notranslate"><span class="pre">next</span></code> if the given <code class="docutils literal notranslate"><span class="pre">GET</span></code> parameter is passed.</li> </ul> </dd></dl> </div> <div class="section" id="s-module-django.contrib.auth.forms"> <span id="s-built-in-forms"></span><span id="s-built-in-auth-forms"></span><span id="module-django.contrib.auth.forms"></span><span id="built-in-forms"></span><span id="built-in-auth-forms"></span><h3>Built-in forms<a class="headerlink" href="#module-django.contrib.auth.forms" title="Permalink to this headline">¶</a></h3> <p>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 <a class="reference internal" href="#module-django.contrib.auth.forms" title="django.contrib.auth.forms"><code class="xref py py-mod docutils literal notranslate"><span class="pre">django.contrib.auth.forms</span></code></a>:</p> <div class="admonition note"> <p class="first admonition-title">Note</p> <p class="last">The built-in authentication forms make certain assumptions about the user model that they are working with. If you’re using a <a class="reference internal" href="customizing.html#auth-custom-user"><span class="std std-ref">custom user model</span></a>, it may be necessary to define your own forms for the authentication system. For more information, refer to the documentation about <a class="reference internal" href="customizing.html#custom-users-and-the-built-in-auth-forms"><span class="std std-ref">using the built-in authentication forms with custom user models</span></a>.</p> </div> <dl class="class"> <dt id="django.contrib.auth.forms.AdminPasswordChangeForm"> <em class="property">class </em><code class="descname">AdminPasswordChangeForm</code><a class="headerlink" href="#django.contrib.auth.forms.AdminPasswordChangeForm" title="Permalink to this definition">¶</a></dt> <dd><p>A form used in the admin interface to change a user’s password.</p> <p>Takes the <code class="docutils literal notranslate"><span class="pre">user</span></code> as the first positional argument.</p> </dd></dl> <dl class="class"> <dt id="django.contrib.auth.forms.AuthenticationForm"> <em class="property">class </em><code class="descname">AuthenticationForm</code><a class="headerlink" href="#django.contrib.auth.forms.AuthenticationForm" title="Permalink to this definition">¶</a></dt> <dd><p>A form for logging a user in.</p> <p>Takes <code class="docutils literal notranslate"><span class="pre">request</span></code> as its first positional argument, which is stored on the form instance for use by sub-classes.</p> <dl class="method"> <dt id="django.contrib.auth.forms.AuthenticationForm.confirm_login_allowed"> <code class="descname">confirm_login_allowed</code>(<em>user</em>)<a class="headerlink" href="#django.contrib.auth.forms.AuthenticationForm.confirm_login_allowed" title="Permalink to this definition">¶</a></dt> <dd><p>By default, <code class="docutils literal notranslate"><span class="pre">AuthenticationForm</span></code> rejects users whose <code class="docutils literal notranslate"><span class="pre">is_active</span></code> flag is set to <code class="docutils literal notranslate"><span class="pre">False</span></code>. You may override this behavior with a custom policy to determine which users can log in. Do this with a custom form that subclasses <code class="docutils literal notranslate"><span class="pre">AuthenticationForm</span></code> and overrides the <code class="docutils literal notranslate"><span class="pre">confirm_login_allowed()</span></code> method. This method should raise a <a class="reference internal" href="../../ref/exceptions.html#django.core.exceptions.ValidationError" title="django.core.exceptions.ValidationError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValidationError</span></code></a> if the given user may not log in.</p> <p>For example, to allow all users to log in regardless of “active” status:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.contrib.auth.forms</span> <span class="k">import</span> <span class="n">AuthenticationForm</span> <span class="k">class</span> <span class="nc">AuthenticationFormWithInactiveUsersOkay</span><span class="p">(</span><span class="n">AuthenticationForm</span><span class="p">):</span> <span class="k">def</span> <span class="nf">confirm_login_allowed</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">user</span><span class="p">):</span> <span class="k">pass</span> </pre></div> </div> <p>(In this case, you’ll also need to use an authentication backend that allows inactive users, such as as <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.backends.AllowAllUsersModelBackend" title="django.contrib.auth.backends.AllowAllUsersModelBackend"><code class="xref py py-class docutils literal notranslate"><span class="pre">AllowAllUsersModelBackend</span></code></a>.)</p> <p>Or to allow only some active users to log in:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">PickyAuthenticationForm</span><span class="p">(</span><span class="n">AuthenticationForm</span><span class="p">):</span> <span class="k">def</span> <span class="nf">confirm_login_allowed</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">user</span><span class="p">):</span> <span class="k">if</span> <span class="ow">not</span> <span class="n">user</span><span class="o">.</span><span class="n">is_active</span><span class="p">:</span> <span class="k">raise</span> <span class="n">forms</span><span class="o">.</span><span class="n">ValidationError</span><span class="p">(</span> <span class="n">_</span><span class="p">(</span><span class="s2">"This account is inactive."</span><span class="p">),</span> <span class="n">code</span><span class="o">=</span><span class="s1">'inactive'</span><span class="p">,</span> <span class="p">)</span> <span class="k">if</span> <span class="n">user</span><span class="o">.</span><span class="n">username</span><span class="o">.</span><span class="n">startswith</span><span class="p">(</span><span class="s1">'b'</span><span class="p">):</span> <span class="k">raise</span> <span class="n">forms</span><span class="o">.</span><span class="n">ValidationError</span><span class="p">(</span> <span class="n">_</span><span class="p">(</span><span class="s2">"Sorry, accounts starting with 'b' aren't welcome here."</span><span class="p">),</span> <span class="n">code</span><span class="o">=</span><span class="s1">'no_b_users'</span><span class="p">,</span> <span class="p">)</span> </pre></div> </div> </dd></dl> </dd></dl> <dl class="class"> <dt id="django.contrib.auth.forms.PasswordChangeForm"> <em class="property">class </em><code class="descname">PasswordChangeForm</code><a class="headerlink" href="#django.contrib.auth.forms.PasswordChangeForm" title="Permalink to this definition">¶</a></dt> <dd><p>A form for allowing a user to change their password.</p> </dd></dl> <dl class="class"> <dt id="django.contrib.auth.forms.PasswordResetForm"> <em class="property">class </em><code class="descname">PasswordResetForm</code><a class="headerlink" href="#django.contrib.auth.forms.PasswordResetForm" title="Permalink to this definition">¶</a></dt> <dd><p>A form for generating and emailing a one-time use link to reset a user’s password.</p> <dl class="method"> <dt id="django.contrib.auth.forms.PasswordResetForm.send_mail"> <code class="descname">send_mail</code>(<em>subject_template_name</em>, <em>email_template_name</em>, <em>context</em>, <em>from_email</em>, <em>to_email</em>, <em>html_email_template_name=None</em>)<a class="headerlink" href="#django.contrib.auth.forms.PasswordResetForm.send_mail" title="Permalink to this definition">¶</a></dt> <dd><p>Uses the arguments to send an <code class="docutils literal notranslate"><span class="pre">EmailMultiAlternatives</span></code>. Can be overridden to customize how the email is sent to the user.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple"> <li><strong>subject_template_name</strong> – the template for the subject.</li> <li><strong>email_template_name</strong> – the template for the email body.</li> <li><strong>context</strong> – context passed to the <code class="docutils literal notranslate"><span class="pre">subject_template</span></code>, <code class="docutils literal notranslate"><span class="pre">email_template</span></code>, and <code class="docutils literal notranslate"><span class="pre">html_email_template</span></code> (if it is not <code class="docutils literal notranslate"><span class="pre">None</span></code>).</li> <li><strong>from_email</strong> – the sender’s email.</li> <li><strong>to_email</strong> – the email of the requester.</li> <li><strong>html_email_template_name</strong> – the template for the HTML body; defaults to <code class="docutils literal notranslate"><span class="pre">None</span></code>, in which case a plain text email is sent.</li> </ul> </td> </tr> </tbody> </table> <p>By default, <code class="docutils literal notranslate"><span class="pre">save()</span></code> populates the <code class="docutils literal notranslate"><span class="pre">context</span></code> with the same variables that <a class="reference internal" href="#django.contrib.auth.views.PasswordResetView" title="django.contrib.auth.views.PasswordResetView"><code class="xref py py-class docutils literal notranslate"><span class="pre">PasswordResetView</span></code></a> passes to its email context.</p> </dd></dl> </dd></dl> <dl class="class"> <dt id="django.contrib.auth.forms.SetPasswordForm"> <em class="property">class </em><code class="descname">SetPasswordForm</code><a class="headerlink" href="#django.contrib.auth.forms.SetPasswordForm" title="Permalink to this definition">¶</a></dt> <dd><p>A form that lets a user change their password without entering the old password.</p> </dd></dl> <dl class="class"> <dt id="django.contrib.auth.forms.UserChangeForm"> <em class="property">class </em><code class="descname">UserChangeForm</code><a class="headerlink" href="#django.contrib.auth.forms.UserChangeForm" title="Permalink to this definition">¶</a></dt> <dd><p>A form used in the admin interface to change a user’s information and permissions.</p> </dd></dl> <dl class="class"> <dt id="django.contrib.auth.forms.UserCreationForm"> <em class="property">class </em><code class="descname">UserCreationForm</code><a class="headerlink" href="#django.contrib.auth.forms.UserCreationForm" title="Permalink to this definition">¶</a></dt> <dd><p>A <a class="reference internal" href="../forms/modelforms.html#django.forms.ModelForm" title="django.forms.ModelForm"><code class="xref py py-class docutils literal notranslate"><span class="pre">ModelForm</span></code></a> for creating a new user.</p> <p>It has three fields: <code class="docutils literal notranslate"><span class="pre">username</span></code> (from the user model), <code class="docutils literal notranslate"><span class="pre">password1</span></code>, and <code class="docutils literal notranslate"><span class="pre">password2</span></code>. It verifies that <code class="docutils literal notranslate"><span class="pre">password1</span></code> and <code class="docutils literal notranslate"><span class="pre">password2</span></code> match, validates the password using <a class="reference internal" href="passwords.html#django.contrib.auth.password_validation.validate_password" title="django.contrib.auth.password_validation.validate_password"><code class="xref py py-func docutils literal notranslate"><span class="pre">validate_password()</span></code></a>, and sets the user’s password using <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User.set_password" title="django.contrib.auth.models.User.set_password"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_password()</span></code></a>.</p> </dd></dl> </div> <div class="section" id="s-authentication-data-in-templates"> <span id="authentication-data-in-templates"></span><h3>Authentication data in templates<a class="headerlink" href="#authentication-data-in-templates" title="Permalink to this headline">¶</a></h3> <p>The currently logged-in user and their permissions are made available in the <a class="reference internal" href="../../ref/templates/api.html"><span class="doc">template context</span></a> when you use <a class="reference internal" href="../../ref/templates/api.html#django.template.RequestContext" title="django.template.RequestContext"><code class="xref py py-class docutils literal notranslate"><span class="pre">RequestContext</span></code></a>.</p> <div class="admonition-technicality admonition"> <p class="first admonition-title">Technicality</p> <p class="last">Technically, these variables are only made available in the template context if you use <a class="reference internal" href="../../ref/templates/api.html#django.template.RequestContext" title="django.template.RequestContext"><code class="xref py py-class docutils literal notranslate"><span class="pre">RequestContext</span></code></a> and the <code class="docutils literal notranslate"><span class="pre">'django.contrib.auth.context_processors.auth'</span></code> context processor is enabled. It is in the default generated settings file. For more, see the <a class="reference internal" href="../../ref/templates/api.html#subclassing-context-requestcontext"><span class="std std-ref">RequestContext docs</span></a>.</p> </div> <div class="section" id="s-users"> <span id="users"></span><h4>Users<a class="headerlink" href="#users" title="Permalink to this headline">¶</a></h4> <p>When rendering a template <a class="reference internal" href="../../ref/templates/api.html#django.template.RequestContext" title="django.template.RequestContext"><code class="xref py py-class docutils literal notranslate"><span class="pre">RequestContext</span></code></a>, the currently logged-in user, either a <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User" title="django.contrib.auth.models.User"><code class="xref py py-class docutils literal notranslate"><span class="pre">User</span></code></a> instance or an <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.AnonymousUser" title="django.contrib.auth.models.AnonymousUser"><code class="xref py py-class docutils literal notranslate"><span class="pre">AnonymousUser</span></code></a> instance, is stored in the template variable <code class="docutils literal notranslate"><span class="pre">{{</span> <span class="pre">user</span> <span class="pre">}}</span></code>:</p> <div class="highlight-html+django notranslate"><div class="highlight"><pre><span></span><span class="cp">{%</span> <span class="k">if</span> <span class="nv">user.is_authenticated</span> <span class="cp">%}</span> <span class="p"><</span><span class="nt">p</span><span class="p">></span>Welcome, <span class="cp">{{</span> <span class="nv">user.username</span> <span class="cp">}}</span>. Thanks for logging in.<span class="p"></</span><span class="nt">p</span><span class="p">></span> <span class="cp">{%</span> <span class="k">else</span> <span class="cp">%}</span> <span class="p"><</span><span class="nt">p</span><span class="p">></span>Welcome, new user. Please log in.<span class="p"></</span><span class="nt">p</span><span class="p">></span> <span class="cp">{%</span> <span class="k">endif</span> <span class="cp">%}</span> </pre></div> </div> <p>This template context variable is not available if a <code class="docutils literal notranslate"><span class="pre">RequestContext</span></code> is not being used.</p> </div> <div class="section" id="s-permissions"> <span id="permissions"></span><h4>Permissions<a class="headerlink" href="#permissions" title="Permalink to this headline">¶</a></h4> <p>The currently logged-in user’s permissions are stored in the template variable <code class="docutils literal notranslate"><span class="pre">{{</span> <span class="pre">perms</span> <span class="pre">}}</span></code>. This is an instance of <code class="docutils literal notranslate"><span class="pre">django.contrib.auth.context_processors.PermWrapper</span></code>, which is a template-friendly proxy of permissions.</p> <p>In the <code class="docutils literal notranslate"><span class="pre">{{</span> <span class="pre">perms</span> <span class="pre">}}</span></code> object, single-attribute lookup is a proxy to <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User.has_module_perms" title="django.contrib.auth.models.User.has_module_perms"><code class="xref py py-meth docutils literal notranslate"><span class="pre">User.has_module_perms</span></code></a>. This example would display <code class="docutils literal notranslate"><span class="pre">True</span></code> if the logged-in user had any permissions in the <code class="docutils literal notranslate"><span class="pre">foo</span></code> app:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">{{</span> <span class="n">perms</span><span class="o">.</span><span class="n">foo</span> <span class="p">}}</span> </pre></div> </div> <p>Two-level-attribute lookup is a proxy to <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User.has_perm" title="django.contrib.auth.models.User.has_perm"><code class="xref py py-meth docutils literal notranslate"><span class="pre">User.has_perm</span></code></a>. This example would display <code class="docutils literal notranslate"><span class="pre">True</span></code> if the logged-in user had the permission <code class="docutils literal notranslate"><span class="pre">foo.can_vote</span></code>:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">{{</span> <span class="n">perms</span><span class="o">.</span><span class="n">foo</span><span class="o">.</span><span class="n">can_vote</span> <span class="p">}}</span> </pre></div> </div> <p>Thus, you can check permissions in template <code class="docutils literal notranslate"><span class="pre">{%</span> <span class="pre">if</span> <span class="pre">%}</span></code> statements:</p> <div class="highlight-html+django notranslate"><div class="highlight"><pre><span></span><span class="cp">{%</span> <span class="k">if</span> <span class="nv">perms.foo</span> <span class="cp">%}</span> <span class="p"><</span><span class="nt">p</span><span class="p">></span>You have permission to do something in the foo app.<span class="p"></</span><span class="nt">p</span><span class="p">></span> <span class="cp">{%</span> <span class="k">if</span> <span class="nv">perms.foo.can_vote</span> <span class="cp">%}</span> <span class="p"><</span><span class="nt">p</span><span class="p">></span>You can vote!<span class="p"></</span><span class="nt">p</span><span class="p">></span> <span class="cp">{%</span> <span class="k">endif</span> <span class="cp">%}</span> <span class="cp">{%</span> <span class="k">if</span> <span class="nv">perms.foo.can_drive</span> <span class="cp">%}</span> <span class="p"><</span><span class="nt">p</span><span class="p">></span>You can drive!<span class="p"></</span><span class="nt">p</span><span class="p">></span> <span class="cp">{%</span> <span class="k">endif</span> <span class="cp">%}</span> <span class="cp">{%</span> <span class="k">else</span> <span class="cp">%}</span> <span class="p"><</span><span class="nt">p</span><span class="p">></span>You don't have permission to do anything in the foo app.<span class="p"></</span><span class="nt">p</span><span class="p">></span> <span class="cp">{%</span> <span class="k">endif</span> <span class="cp">%}</span> </pre></div> </div> <p>It is possible to also look permissions up by <code class="docutils literal notranslate"><span class="pre">{%</span> <span class="pre">if</span> <span class="pre">in</span> <span class="pre">%}</span></code> statements. For example:</p> <div class="highlight-html+django notranslate"><div class="highlight"><pre><span></span><span class="cp">{%</span> <span class="k">if</span> <span class="s1">'foo'</span> <span class="k">in</span> <span class="nv">perms</span> <span class="cp">%}</span> <span class="cp">{%</span> <span class="k">if</span> <span class="s1">'foo.can_vote'</span> <span class="k">in</span> <span class="nv">perms</span> <span class="cp">%}</span> <span class="p"><</span><span class="nt">p</span><span class="p">></span>In lookup works, too.<span class="p"></</span><span class="nt">p</span><span class="p">></span> <span class="cp">{%</span> <span class="k">endif</span> <span class="cp">%}</span> <span class="cp">{%</span> <span class="k">endif</span> <span class="cp">%}</span> </pre></div> </div> </div> </div> </div> <div class="section" id="s-managing-users-in-the-admin"> <span id="s-auth-admin"></span><span id="managing-users-in-the-admin"></span><span id="auth-admin"></span><h2>Managing users in the admin<a class="headerlink" href="#managing-users-in-the-admin" title="Permalink to this headline">¶</a></h2> <p>When you have both <code class="docutils literal notranslate"><span class="pre">django.contrib.admin</span></code> and <code class="docutils literal notranslate"><span class="pre">django.contrib.auth</span></code> 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.</p> <div class="section" id="s-id6"> <span id="id6"></span><h3>Creating users<a class="headerlink" href="#id6" title="Permalink to this headline">¶</a></h3> <p>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.</p> <p>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 <em>and</em> 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 <em>and</em> change permissions as a slight security measure.</p> <p>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!</p> </div> <div class="section" id="s-id7"> <span id="id7"></span><h3>Changing passwords<a class="headerlink" href="#id7" title="Permalink to this headline">¶</a></h3> <p>User passwords are not displayed in the admin (nor stored in the database), but the <a class="reference internal" href="passwords.html"><span class="doc">password storage details</span></a> are displayed. Included in the display of this information is a link to a password change form that allows admins to change user passwords.</p> </div> </div> </div> </div> </div> </div> <div class="yui-b" id="sidebar"> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="sphinxsidebarwrapper"> <h3><a href="../../contents.html">Table of Contents</a></h3> <ul> <li><a class="reference internal" href="#">Using the Django authentication system</a><ul> <li><a class="reference internal" href="#user-objects"><code class="docutils literal notranslate"><span class="pre">User</span></code> objects</a><ul> <li><a class="reference internal" href="#creating-users">Creating users</a></li> <li><a class="reference internal" href="#creating-superusers">Creating superusers</a></li> <li><a class="reference internal" href="#changing-passwords">Changing passwords</a></li> <li><a class="reference internal" href="#authenticating-users">Authenticating users</a></li> </ul> </li> <li><a class="reference internal" href="#permissions-and-authorization">Permissions and Authorization</a><ul> <li><a class="reference internal" href="#default-permissions">Default permissions</a></li> <li><a class="reference internal" href="#groups">Groups</a></li> <li><a class="reference internal" href="#programmatically-creating-permissions">Programmatically creating permissions</a></li> <li><a class="reference internal" href="#permission-caching">Permission caching</a></li> </ul> </li> <li><a class="reference internal" href="#authentication-in-web-requests">Authentication in Web requests</a><ul> <li><a class="reference internal" href="#how-to-log-a-user-in">How to log a user in</a><ul> <li><a class="reference internal" href="#selecting-the-authentication-backend">Selecting the authentication backend</a></li> </ul> </li> <li><a class="reference internal" href="#how-to-log-a-user-out">How to log a user out</a></li> <li><a class="reference internal" href="#limiting-access-to-logged-in-users">Limiting access to logged-in users</a><ul> <li><a class="reference internal" href="#the-raw-way">The raw way</a></li> <li><a class="reference internal" href="#the-login-required-decorator">The <code class="docutils literal notranslate"><span class="pre">login_required</span></code> decorator</a></li> <li><a class="reference internal" href="#the-loginrequired-mixin">The <code class="docutils literal notranslate"><span class="pre">LoginRequired</span></code> mixin</a></li> <li><a class="reference internal" href="#limiting-access-to-logged-in-users-that-pass-a-test">Limiting access to logged-in users that pass a test</a></li> <li><a class="reference internal" href="#the-permission-required-decorator">The <code class="docutils literal notranslate"><span class="pre">permission_required</span></code> decorator</a></li> <li><a class="reference internal" href="#the-permissionrequiredmixin-mixin">The <code class="docutils literal notranslate"><span class="pre">PermissionRequiredMixin</span></code> mixin</a></li> </ul> </li> <li><a class="reference internal" href="#redirecting-unauthorized-requests-in-class-based-views">Redirecting unauthorized requests in class-based views</a><ul> <li><a class="reference internal" href="#session-invalidation-on-password-change">Session invalidation on password change</a></li> </ul> </li> <li><a class="reference internal" href="#module-django.contrib.auth.views">Authentication Views</a><ul> <li><a class="reference internal" href="#using-the-views">Using the views</a></li> <li><a class="reference internal" href="#all-authentication-views">All authentication views</a></li> </ul> </li> <li><a class="reference internal" href="#helper-functions">Helper functions</a></li> <li><a class="reference internal" href="#module-django.contrib.auth.forms">Built-in forms</a></li> <li><a class="reference internal" href="#authentication-data-in-templates">Authentication data in templates</a><ul> <li><a class="reference internal" href="#users">Users</a></li> <li><a class="reference internal" href="#permissions">Permissions</a></li> </ul> </li> </ul> </li> <li><a class="reference internal" href="#managing-users-in-the-admin">Managing users in the admin</a><ul> <li><a class="reference internal" href="#id6">Creating users</a></li> <li><a class="reference internal" href="#id7">Changing passwords</a></li> </ul> </li> </ul> </li> </ul> <h4>Previous topic</h4> <p class="topless"><a href="index.html" title="previous chapter">User authentication in Django</a></p> <h4>Next topic</h4> <p class="topless"><a href="passwords.html" title="next chapter">Password management in Django</a></p> <div role="note" aria-label="source link"> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="../../_sources/topics/auth/default.txt" rel="nofollow">Show Source</a></li> </ul> </div> <div id="searchbox" style="display: none" role="search"> <h3>Quick search</h3> <div class="searchformwrapper"> <form class="search" action="../../search.html" method="get"> <input type="text" name="q" /> <input type="submit" value="Go" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <h3>Last update:</h3> <p class="topless">Feb 11, 2019</p> </div> </div> <div id="ft"> <div class="nav"> « <a href="index.html" title="User authentication in Django">previous</a> | <a href="../index.html" title="Using Django" accesskey="U">up</a> | <a href="passwords.html" title="Password management in Django">next</a> »</div> </div> </div> <div class="clearer"></div> </div> </body> </html>