<!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="Content-Type" content="text/html; charset=utf-8" /> <title>Using the Django authentication system — Django 1.8.19 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"> var DOCUMENTATION_OPTIONS = { URL_ROOT: '../../', VERSION: '1.8.19', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true }; </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> <link rel="index" title="Index" href="../../genindex.html" /> <link rel="search" title="Search" href="../../search.html" /> <link rel="top" title="Django 1.8.19 documentation" href="../../contents.html" /> <link rel="up" title="User authentication in Django" href="index.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 role="document"> <div class="document"> <div id="custom-doc" class="yui-t6"> <div id="hd"> <h1><a href="../../index.html">Django 1.8.19 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>User 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"><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"><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"><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"><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"><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"><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"><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"><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"><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"><span class="pre">create_user()</span></code></a> helper function:</p> <div class="highlight-default"><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"><span class="pre">createsuperuser</span></code></a> command:</p> <div class="highlight-default"><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#django-admin-option---username"><code class="xref std std-djadminopt docutils literal"><span class="pre">--username</span></code></a> or the <a class="reference internal" href="../../ref/django-admin.html#django-admin-option---email"><code class="xref std std-djadminopt docutils literal"><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"><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"><span class="pre">set_password()</span></code></a>:</p> <div class="highlight-pycon"><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> <div class="versionadded"> <span class="title">New in Django 1.7.</span> </div> <p>Changing a user’s password will log out all their sessions if the <a class="reference internal" href="../../ref/middleware.html#django.contrib.auth.middleware.SessionAuthenticationMiddleware" title="django.contrib.auth.middleware.SessionAuthenticationMiddleware"><code class="xref py py-class docutils literal"><span class="pre">SessionAuthenticationMiddleware</span></code></a> is enabled. 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>**credentials</em>)<a class="headerlink" href="#django.contrib.auth.authenticate" title="Permalink to this definition">¶</a></dt> <dd><p>To authenticate a given username and password, use <a class="reference internal" href="#django.contrib.auth.authenticate" title="django.contrib.auth.authenticate"><code class="xref py py-func docutils literal"><span class="pre">authenticate()</span></code></a>. It takes credentials in the form of keyword arguments, for the default configuration this is <code class="docutils literal"><span class="pre">username</span></code> and <code class="docutils literal"><span class="pre">password</span></code>, and it 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"><span class="pre">User</span></code></a> object if the password is valid for the given username. If the password is invalid, <a class="reference internal" href="#django.contrib.auth.authenticate" title="django.contrib.auth.authenticate"><code class="xref py py-func docutils literal"><span class="pre">authenticate()</span></code></a> returns <code class="docutils literal"><span class="pre">None</span></code>. Example:</p> <div class="highlight-default"><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"># the password verified for the user</span> <span class="k">if</span> <span class="n">user</span><span class="o">.</span><span class="n">is_active</span><span class="p">:</span> <span class="nb">print</span><span class="p">(</span><span class="s2">"User is valid, active and authenticated"</span><span class="p">)</span> <span class="k">else</span><span class="p">:</span> <span class="nb">print</span><span class="p">(</span><span class="s2">"The password is valid, but the account has been disabled!"</span><span class="p">)</span> <span class="k">else</span><span class="p">:</span> <span class="c1"># the authentication system was unable to verify the username and password</span> <span class="nb">print</span><span class="p">(</span><span class="s2">"The username and password were incorrect."</span><span class="p">)</span> </pre></div> </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"><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"><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"><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"><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"><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"><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"><span class="pre">User</span></code></a> objects have two many-to-many fields: <code class="docutils literal"><span class="pre">groups</span></code> and <code class="docutils literal"><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"><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"><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="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="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"><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"><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"><span class="pre">manage.py</span> <span class="pre">migrate</span></code></a>; the first time you run <code class="docutils literal"><span class="pre">migrate</span></code> after adding <code class="docutils literal"><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"><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"><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"><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"><span class="pre">app_label</span></code></a> <code class="docutils literal"><span class="pre">foo</span></code> and a model named <code class="docutils literal"><span class="pre">Bar</span></code>, to test for basic permissions you should use:</p> <ul class="simple"> <li>add: <code class="docutils literal"><span class="pre">user.has_perm('foo.add_bar')</span></code></li> <li>change: <code class="docutils literal"><span class="pre">user.has_perm('foo.change_bar')</span></code></li> <li>delete: <code class="docutils literal"><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"><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"><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"><span class="pre">Site</span> <span class="pre">editors</span></code> has the permission <code class="docutils literal"><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"><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"><span class="pre">Meta</span></code> class, you can also create permissions directly. For example, you can create the <code class="docutils literal"><span class="pre">can_publish</span></code> permission for a <code class="docutils literal"><span class="pre">BlogPost</span></code> model in <code class="docutils literal"><span class="pre">myapp</span></code>:</p> <div class="highlight-default"><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> </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"><span class="pre">User</span></code></a> via its <code class="docutils literal"><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"><span class="pre">Group</span></code></a> via its <code class="docutils literal"><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"><span class="pre">ModelBackend</span></code></a> caches permissions on the <code class="docutils literal"><span class="pre">User</span></code> 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 are not 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 <code class="docutils literal"><span class="pre">User</span></code> from the database. For example:</p> <div class="highlight-default"><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.shortcuts</span> <span class="k">import</span> <span class="n">get_object_or_404</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_bar'</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_bar'</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_bar'</span><span class="p">)</span> <span class="c1"># False</span> <span class="c1"># Request new instance of User</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_bar'</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"><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"><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"><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"><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-meth docutils literal"><span class="pre">is_authenticated()</span></code></a>, like so:</p> <div class="highlight-default"><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"><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>)<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"><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"><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"><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"><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"><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"><span class="pre">login()</span></code></a>:</p> <div class="highlight-default"><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">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="k">if</span> <span class="n">user</span><span class="o">.</span><span class="n">is_active</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="k">else</span><span class="p">:</span> <span class="c1"># Return a 'disabled account' error message</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> </dd></dl> <div class="admonition-calling-authenticate-first admonition"> <p class="first admonition-title">Calling <code class="docutils literal"><span class="pre">authenticate()</span></code> first</p> <p class="last">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"><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"><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"><span class="pre">authenticate()</span></code></a> sets an attribute on 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"><span class="pre">User</span></code></a> noting which authentication backend successfully authenticated that user (see the <a class="reference internal" href="customizing.html#authentication-backends"><span class="std std-ref">backends documentation</span></a> for details), and this information is needed later during the login process. An error will be raised if you try to login a user object retrieved from the database directly.</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="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"><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"><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"><span class="pre">HttpRequest</span></code></a> object and has no return value. Example:</p> <div class="highlight-default"><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"><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"><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"><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-meth docutils literal"><span class="pre">request.user.is_authenticated()</span></code></a> and either redirect to a login page:</p> <div class="highlight-default"><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"><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 login_required 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="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"><span class="pre">login_required()</span></code></a> decorator:</p> <div class="highlight-default"><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"><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"><span class="pre">settings.LOGIN_URL</span></code></a>, passing the current absolute path in the query string. Example: <code class="docutils literal"><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"><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"><span class="pre">login_required()</span></code></a> takes an optional <code class="docutils literal"><span class="pre">redirect_field_name</span></code> parameter:</p> <div class="highlight-default"><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"><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"><span class="pre">redirect_field_name</span></code> as its key rather than <code class="docutils literal"><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"><span class="pre">login_required()</span></code></a> also takes an optional <code class="docutils literal"><span class="pre">login_url</span></code> parameter. Example:</p> <div class="highlight-default"><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"><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"><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"><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="s1">r'^accounts/login/$'</span><span class="p">,</span> <span class="n">auth_views</span><span class="o">.</span><span class="n">login</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"><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 login_required decorator does NOT check the is_active flag on a user.</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"><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"><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="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"><span class="pre">user_passes_test</span></code> decorator which performs a redirect when the callable returns <code class="docutils literal"><span class="pre">False</span></code>:</p> <div class="highlight-default"><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"><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"><span class="pre">User</span></code></a> object and returns <code class="docutils literal"><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"><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"><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"><span class="pre">user_passes_test()</span></code></a> takes two optional arguments:</p> <dl class="docutils"> <dt><code class="docutils literal"><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"><span class="pre">settings.LOGIN_URL</span></code></a> if you don’t specify one.</dd> <dt><code class="docutils literal"><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"><span class="pre">login_required()</span></code></a>. Setting it to <code class="docutils literal"><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"><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> </div> <div class="section" id="s-the-permission-required-decorator"> <span id="the-permission-required-decorator"></span><h4>The permission_required 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="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"><span class="pre">permission_required()</span></code></a> decorator.:</p> <div class="highlight-default"><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>As for 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"><span class="pre">has_perm()</span></code></a> method, permission names take the form <code class="docutils literal"><span class="pre">"<app</span> <span class="pre">label>.<permission</span> <span class="pre">codename>"</span></code> (i.e. <code class="docutils literal"><span class="pre">polls.can_vote</span></code> for a permission on a model in the <code class="docutils literal"><span class="pre">polls</span></code> application).</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"><span class="pre">permission_required()</span></code></a> also takes an optional <code class="docutils literal"><span class="pre">login_url</span></code> parameter. Example:</p> <div class="highlight-default"><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"><span class="pre">login_required()</span></code></a> decorator, <code class="docutils literal"><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"><span class="pre">settings.LOGIN_URL</span></code></a>.</p> <p>If the <code class="docutils literal"><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"><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"><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"><span class="pre">login_required()</span></code></a> decorator:</p> <div class="highlight-default"><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> <div class="versionchanged"> <span class="title">Changed in Django 1.7:</span> <p>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"><span class="pre">permission_required()</span></code></a> decorator can take a list of permissions, in which case the user must have all of the permissions in order to access the view.</p> </div> </dd></dl> </div> <div class="section" id="s-applying-permissions-to-generic-views"> <span id="s-id3"></span><span id="applying-permissions-to-generic-views"></span><span id="id3"></span><h4>Applying permissions to generic views<a class="headerlink" href="#applying-permissions-to-generic-views" title="Permalink to this headline">¶</a></h4> <p>To apply a permission to a <a class="reference internal" href="../../ref/class-based-views/index.html"><span class="doc">class-based generic view</span></a>, decorate the <a class="reference internal" href="../../ref/class-based-views/base.html#django.views.generic.base.View.dispatch" title="django.views.generic.base.View.dispatch"><code class="xref py py-meth docutils literal"><span class="pre">View.dispatch</span></code></a> method on the class. See <a class="reference internal" href="../class-based-views/intro.html#id2"><span class="std std-ref">Decorating the class</span></a> for details. Another approach is to <a class="reference internal" href="../class-based-views/intro.html#mixins-that-wrap-as-view"><span class="std std-ref">write a mixin that wraps as_view()</span></a>.</p> </div> <div class="section" id="s-session-invalidation-on-password-change"> <span id="s-id4"></span><span id="session-invalidation-on-password-change"></span><span id="id4"></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="versionadded"> <span class="title">New in Django 1.7.</span> </div> <div class="admonition warning"> <p class="first admonition-title">Warning</p> <p>This protection only applies if <a class="reference internal" href="../../ref/middleware.html#django.contrib.auth.middleware.SessionAuthenticationMiddleware" title="django.contrib.auth.middleware.SessionAuthenticationMiddleware"><code class="xref py py-class docutils literal"><span class="pre">SessionAuthenticationMiddleware</span></code></a> is enabled in <a class="reference internal" href="../../ref/settings.html#std:setting-MIDDLEWARE_CLASSES"><code class="xref std std-setting docutils literal"><span class="pre">MIDDLEWARE_CLASSES</span></code></a>. It’s included if <code class="docutils literal"><span class="pre">settings.py</span></code> was generated by <a class="reference internal" href="../../ref/django-admin.html#django-admin-startproject"><code class="xref std std-djadmin docutils literal"><span class="pre">startproject</span></code></a> on Django ≥ 1.7.</p> <p class="last">Session verification will become mandatory in Django 1.10 regardless of whether or not <code class="docutils literal"><span class="pre">SessionAuthenticationMiddleware</span></code> is enabled. If you have a pre-1.7 project or one generated using a template that doesn’t include <code class="docutils literal"><span class="pre">SessionAuthenticationMiddleware</span></code>, consider enabling it before then after reading the upgrade considerations below.</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"><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"><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"><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"><span class="pre">AbstractBaseUser</span></code></a> case, this is an HMAC of the password field. If the <a class="reference internal" href="../../ref/middleware.html#django.contrib.auth.middleware.SessionAuthenticationMiddleware" title="django.contrib.auth.middleware.SessionAuthenticationMiddleware"><code class="xref py py-class docutils literal"><span class="pre">SessionAuthenticationMiddleware</span></code></a> is enabled, Django verifies that the hash sent along with each request matches the one that’s computed server-side. 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.password_change" title="django.contrib.auth.views.password_change"><code class="xref py py-func docutils literal"><span class="pre">django.contrib.auth.views.password_change()</span></code></a> and the <code class="docutils literal"><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"><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 this function:</p> <dl class="function"> <dt id="django.contrib.auth.decorators.update_session_auth_hash"> <code class="descname">update_session_auth_hash</code>(<em>request</em>, <em>user</em>)<a class="headerlink" href="#django.contrib.auth.decorators.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. Example usage:</p> <div class="highlight-default"><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> </dd></dl> <p>If you are upgrading an existing site and wish to enable this middleware without requiring all your users to re-login afterward, you should first upgrade to Django 1.7 and run it for a while so that as sessions are naturally recreated as users login, they include the session hash as described above. Once you start running your site with <a class="reference internal" href="../../ref/middleware.html#django.contrib.auth.middleware.SessionAuthenticationMiddleware" title="django.contrib.auth.middleware.SessionAuthenticationMiddleware"><code class="xref py py-class docutils literal"><span class="pre">SessionAuthenticationMiddleware</span></code></a>, any users who have not logged in and had their session updated with the verification hash will have their existing session invalidated and be required to login.</p> <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"><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"><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-id5"></span><span id="using-the-views"></span><span id="id5"></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"><span class="pre">django.contrib.auth.urls</span></code> in your own URLconf, for example:</p> <div class="highlight-default"><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"><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"><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">password_change</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"><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"><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">password_change</span><span class="p">,</span> <span class="p">{</span><span class="s1">'template_name'</span><span class="p">:</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 return a <a class="reference internal" href="../../ref/template-response.html#django.template.response.TemplateResponse" title="django.template.response.TemplateResponse"><code class="xref py py-class docutils literal"><span class="pre">TemplateResponse</span></code></a> instance, which allows you to easily customize the response data before rendering. A way to do this is to wrap a view in your own view:</p> <div class="highlight-default"><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">def</span> <span class="nf">change_password</span><span class="p">(</span><span class="n">request</span><span class="p">):</span> <span class="n">template_response</span> <span class="o">=</span> <span class="n">views</span><span class="o">.</span><span class="n">password_change</span><span class="p">(</span><span class="n">request</span><span class="p">)</span> <span class="c1"># Do something with `template_response`</span> <span class="k">return</span> <span class="n">template_response</span> </pre></div> </div> <p>For more details, see the <a class="reference internal" href="../../ref/template-response.html"><span class="doc">TemplateResponse documentation</span></a>.</p> </div> <div class="section" id="s-all-authentication-views"> <span id="s-id6"></span><span id="all-authentication-views"></span><span id="id6"></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"><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>)<a class="headerlink" href="#django.contrib.auth.views.login" title="Permalink to this definition">¶</a></dt> <dd><p><strong>URL name:</strong> <code class="docutils literal"><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>Optional arguments:</strong></p> <ul class="simple"> <li><code class="docutils literal"><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"><span class="pre">registration/login.html</span></code>.</li> <li><code class="docutils literal"><span class="pre">redirect_field_name</span></code>: The name of a <code class="docutils literal"><span class="pre">GET</span></code> field containing the URL to redirect to after login. Defaults to <code class="docutils literal"><span class="pre">next</span></code>.</li> <li><code class="docutils literal"><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"><span class="pre">AuthenticationForm</span></code></a>.</li> <li><code class="docutils literal"><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"><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>Here’s what <code class="docutils literal"><span class="pre">django.contrib.auth.views.login</span></code> does:</p> <ul class="simple"> <li>If called via <code class="docutils literal"><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"><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"><span class="pre">next</span></code>. If <code class="docutils literal"><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"><span class="pre">settings.LOGIN_REDIRECT_URL</span></code></a> (which defaults to <code class="docutils literal"><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"><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"><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"><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"><span class="pre">AuthenticationForm</span></code></a>.</li> <li><code class="docutils literal"><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"><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"><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"><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"><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"><span class="pre">HttpRequest</span></code></a>.</li> <li><code class="docutils literal"><span class="pre">site_name</span></code>: An alias for <code class="docutils literal"><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"><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"><span class="pre">registration/login.html</span></code>, you can pass the <code class="docutils literal"><span class="pre">template_name</span></code> parameter via the extra arguments to the view in your URLconf. For example, this URLconf line would use <code class="file docutils literal"><span class="pre">myapp/login.html</span></code> instead:</p> <div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">url</span><span class="p">(</span><span class="s1">r'^accounts/login/$'</span><span class="p">,</span> <span class="n">auth_views</span><span class="o">.</span><span class="n">login</span><span class="p">,</span> <span class="p">{</span><span class="s1">'template_name'</span><span class="p">:</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"><span class="pre">GET</span></code> field which contains the URL to redirect to after login by passing <code class="docutils literal"><span class="pre">redirect_field_name</span></code> to the view. By default, the field is called <code class="docutils literal"><span class="pre">next</span></code>.</p> <p>Here’s a sample <code class="file docutils literal"><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"><span class="pre">base.html</span></code> template that defines a <code class="docutils literal"><span class="pre">content</span></code> block:</p> <div class="highlight-html+django"><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">'django.contrib.auth.views.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 pass a custom authentication form to the login view via the <code class="docutils literal"><span class="pre">authentication_form</span></code> parameter. This form must accept a <code class="docutils literal"><span class="pre">request</span></code> keyword argument in its <code class="docutils literal"><span class="pre">__init__</span></code> method, and provide a <code class="docutils literal"><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><p>Logs a user out.</p> <p><strong>URL name:</strong> <code class="docutils literal"><span class="pre">logout</span></code></p> <p><strong>Optional arguments:</strong></p> <ul class="simple"> <li><code class="docutils literal"><span class="pre">next_page</span></code>: The URL to redirect to after logout.</li> <li><code class="docutils literal"><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"><span class="pre">registration/logged_out.html</span></code> if no argument is supplied.</li> <li><code class="docutils literal"><span class="pre">redirect_field_name</span></code>: The name of a <code class="docutils literal"><span class="pre">GET</span></code> field containing the URL to redirect to after log out. Defaults to <code class="docutils literal"><span class="pre">next</span></code>. Overrides the <code class="docutils literal"><span class="pre">next_page</span></code> URL if the given <code class="docutils literal"><span class="pre">GET</span></code> parameter is passed.</li> <li><code class="docutils literal"><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"><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"><span class="pre">title</span></code>: The string “Logged out”, localized.</li> <li><code class="docutils literal"><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"><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"><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"><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"><span class="pre">HttpRequest</span></code></a>.</li> <li><code class="docutils literal"><span class="pre">site_name</span></code>: An alias for <code class="docutils literal"><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"><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"><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"><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.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"><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"><span class="pre">settings.LOGIN_URL</span></code></a> if not supplied.</li> <li><code class="docutils literal"><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"><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_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><p>Allows a user to change their password.</p> <p><strong>URL name:</strong> <code class="docutils literal"><span class="pre">password_change</span></code></p> <p><strong>Optional arguments:</strong></p> <ul class="simple"> <li><code class="docutils literal"><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"><span class="pre">registration/password_change_form.html</span></code> if not supplied.</li> <li><code class="docutils literal"><span class="pre">post_change_redirect</span></code>: The URL to redirect to after a successful password change.</li> <li><code class="docutils literal"><span class="pre">password_change_form</span></code>: A custom “change password” form which must accept a <code class="docutils literal"><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"><span class="pre">PasswordChangeForm</span></code></a>.</li> <li><code class="docutils literal"><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"><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"><span class="pre">form</span></code>: The password change form (see <code class="docutils literal"><span class="pre">password_change_form</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><p>The page shown after a user has changed their password.</p> <p><strong>URL name:</strong> <code class="docutils literal"><span class="pre">password_change_done</span></code></p> <p><strong>Optional arguments:</strong></p> <ul class="simple"> <li><code class="docutils literal"><span class="pre">template_name</span></code>: The full name of a template to use. Defaults to <code class="file docutils literal"><span class="pre">registration/password_change_done.html</span></code> if not supplied.</li> <li><code class="docutils literal"><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"><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>is_admin_site=False</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>)<a class="headerlink" href="#django.contrib.auth.views.password_reset" title="Permalink to this definition">¶</a></dt> <dd><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"><span class="pre">PasswordResetForm</span></code></a> and use the <code class="docutils literal"><span class="pre">password_reset_form</span></code> argument.</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"><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>URL name:</strong> <code class="docutils literal"><span class="pre">password_reset</span></code></p> <p><strong>Optional arguments:</strong></p> <ul class="simple"> <li><code class="docutils literal"><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"><span class="pre">registration/password_reset_form.html</span></code> if not supplied.</li> <li><code class="docutils literal"><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"><span class="pre">registration/password_reset_email.html</span></code> if not supplied.</li> <li><code class="docutils literal"><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"><span class="pre">registration/password_reset_subject.txt</span></code> if not supplied.</li> <li><code class="docutils literal"><span class="pre">password_reset_form</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"><span class="pre">PasswordResetForm</span></code></a>.</li> <li><code class="docutils literal"><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"><span class="pre">default_token_generator</span></code>, it’s an instance of <code class="docutils literal"><span class="pre">django.contrib.auth.tokens.PasswordResetTokenGenerator</span></code>.</li> <li><code class="docutils literal"><span class="pre">post_reset_redirect</span></code>: The URL to redirect to after a successful password reset request.</li> <li><code class="docutils literal"><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"><span class="pre">DEFAULT_FROM_EMAIL</span></code></a>.</li> <li><code class="docutils literal"><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"><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"><span class="pre">html_email_template_name</span></code>: The full name of a template to use for generating a <code class="docutils literal"><span class="pre">text/html</span></code> multipart email with the password reset link. By default, HTML email is not sent.</li> </ul> <div class="versionadded"> <span class="title">New in Django 1.7:</span> <p><code class="docutils literal"><span class="pre">html_email_template_name</span></code> was added.</p> </div> <div class="deprecated"> <p><span class="versionmodified">Deprecated since version 1.8: </span>The <code class="docutils literal"><span class="pre">is_admin_site</span></code> argument is deprecated and will be removed in Django 1.10.</p> </div> <p><strong>Template context:</strong></p> <ul class="simple"> <li><code class="docutils literal"><span class="pre">form</span></code>: The form (see <code class="docutils literal"><span class="pre">password_reset_form</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"><span class="pre">email</span></code>: An alias for <code class="docutils literal"><span class="pre">user.email</span></code></li> <li><code class="docutils literal"><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"><span class="pre">User</span></code></a>, according to the <code class="docutils literal"><span class="pre">email</span></code> form field. Only active users are able to reset their passwords (<code class="docutils literal"><span class="pre">User.is_active</span> <span class="pre">is</span> <span class="pre">True</span></code>).</li> <li><code class="docutils literal"><span class="pre">site_name</span></code>: An alias for <code class="docutils literal"><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"><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"><span class="pre">domain</span></code>: An alias for <code class="docutils literal"><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"><span class="pre">request.get_host()</span></code>.</li> <li><code class="docutils literal"><span class="pre">protocol</span></code>: http or https</li> <li><code class="docutils literal"><span class="pre">uid</span></code>: The user’s primary key encoded in base 64.</li> <li><code class="docutils literal"><span class="pre">token</span></code>: Token to check that the reset link is valid.</li> </ul> <p>Sample <code class="docutils literal"><span class="pre">registration/password_reset_email.html</span></code> (email body template):</p> <div class="highlight-html+django"><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><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.password_reset" title="django.contrib.auth.views.password_reset"><code class="xref py py-func docutils literal"><span class="pre">password_reset()</span></code></a> view doesn’t have an explicit <code class="docutils literal"><span class="pre">post_reset_redirect</span></code> URL set.</p> <p><strong>URL name:</strong> <code class="docutils literal"><span class="pre">password_reset_done</span></code></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>Optional arguments:</strong></p> <ul class="simple"> <li><code class="docutils literal"><span class="pre">template_name</span></code>: The full name of a template to use. Defaults to <code class="file docutils literal"><span class="pre">registration/password_reset_done.html</span></code> if not supplied.</li> <li><code class="docutils literal"><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"><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><p>Presents a form for entering a new password.</p> <p><strong>URL name:</strong> <code class="docutils literal"><span class="pre">password_reset_confirm</span></code></p> <p><strong>Optional arguments:</strong></p> <ul class="simple"> <li><code class="docutils literal"><span class="pre">uidb64</span></code>: The user’s id encoded in base 64. Defaults to <code class="docutils literal"><span class="pre">None</span></code>.</li> <li><code class="docutils literal"><span class="pre">token</span></code>: Token to check that the password is valid. Defaults to <code class="docutils literal"><span class="pre">None</span></code>.</li> <li><code class="docutils literal"><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"><span class="pre">registration/password_reset_confirm.html</span></code>.</li> <li><code class="docutils literal"><span class="pre">token_generator</span></code>: Instance of the class to check the password. This will default to <code class="docutils literal"><span class="pre">default_token_generator</span></code>, it’s an instance of <code class="docutils literal"><span class="pre">django.contrib.auth.tokens.PasswordResetTokenGenerator</span></code>.</li> <li><code class="docutils literal"><span class="pre">set_password_form</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"><span class="pre">SetPasswordForm</span></code></a></li> <li><code class="docutils literal"><span class="pre">post_reset_redirect</span></code>: URL to redirect after the password reset done. Defaults to <code class="docutils literal"><span class="pre">None</span></code>.</li> <li><code class="docutils literal"><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"><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"><span class="pre">form</span></code>: The form (see <code class="docutils literal"><span class="pre">set_password_form</span></code> above) for setting the new user’s password.</li> <li><code class="docutils literal"><span class="pre">validlink</span></code>: Boolean, True if the link (combination of <code class="docutils literal"><span class="pre">uidb64</span></code> and <code class="docutils literal"><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><p>Presents a view which informs the user that the password has been successfully changed.</p> <p><strong>URL name:</strong> <code class="docutils literal"><span class="pre">password_reset_complete</span></code></p> <p><strong>Optional arguments:</strong></p> <ul class="simple"> <li><code class="docutils literal"><span class="pre">template_name</span></code>: The full name of a template to display the view. Defaults to <code class="file docutils literal"><span class="pre">registration/password_reset_complete.html</span></code>.</li> <li><code class="docutils literal"><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"><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"><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"><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"><span class="pre">settings.LOGIN_URL</span></code></a> if not supplied.</li> <li><code class="docutils literal"><span class="pre">redirect_field_name</span></code>: The name of a <code class="docutils literal"><span class="pre">GET</span></code> field containing the URL to redirect to after log out. Overrides <code class="docutils literal"><span class="pre">next</span></code> if the given <code class="docutils literal"><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"><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"><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"><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><div class="versionadded"> <span class="title">New in Django 1.7.</span> </div> <p>By default, <code class="docutils literal"><span class="pre">AuthenticationForm</span></code> rejects users whose <code class="docutils literal"><span class="pre">is_active</span></code> flag is set to <code class="docutils literal"><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"><span class="pre">AuthenticationForm</span></code> and overrides the <code class="docutils literal"><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"><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"><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>Or to allow only some active users to log in:</p> <div class="highlight-default"><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><div class="versionadded"> <span class="title">New in Django 1.8.</span> </div> <p>Uses the arguments to send an <code class="docutils literal"><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"><span class="pre">subject_template</span></code>, <code class="docutils literal"><span class="pre">email_template</span></code>, and <code class="docutils literal"><span class="pre">html_email_template</span></code> (if it is not <code class="docutils literal"><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"><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"><span class="pre">save()</span></code> populates the <code class="docutils literal"><span class="pre">context</span></code> with the same variables that <a class="reference internal" href="#django.contrib.auth.views.password_reset" title="django.contrib.auth.views.password_reset"><code class="xref py py-func docutils literal"><span class="pre">password_reset()</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 form for creating a new user.</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"><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"><span class="pre">RequestContext</span></code></a> and the <code class="docutils literal"><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"><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"><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"><span class="pre">AnonymousUser</span></code></a> instance, is stored in the template variable <code class="docutils literal"><span class="pre">{{</span> <span class="pre">user</span> <span class="pre">}}</span></code>:</p> <div class="highlight-html+django"><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"><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"><span class="pre">{{</span> <span class="pre">perms</span> <span class="pre">}}</span></code>. This is an instance of <code class="docutils literal"><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"><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"><span class="pre">User.has_module_perms</span></code></a>. This example would display <code class="docutils literal"><span class="pre">True</span></code> if the logged-in user had any permissions in the <code class="docutils literal"><span class="pre">foo</span></code> app:</p> <div class="highlight-default"><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"><span class="pre">User.has_perm</span></code></a>. This example would display <code class="docutils literal"><span class="pre">True</span></code> if the logged-in user had the permission <code class="docutils literal"><span class="pre">foo.can_vote</span></code>:</p> <div class="highlight-default"><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"><span class="pre">{%</span> <span class="pre">if</span> <span class="pre">%}</span></code> statements:</p> <div class="highlight-html+django"><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"><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"><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"><span class="pre">django.contrib.admin</span></code> and <code class="docutils literal"><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-id7"> <span id="id7"></span><h3>Creating Users<a class="headerlink" href="#id7" 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-id8"> <span id="id8"></span><h3>Changing Passwords<a class="headerlink" href="#id8" 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">User 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></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 login_required decorator</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 permission_required decorator</a></li> <li><a class="reference internal" href="#applying-permissions-to-generic-views">Applying permissions to generic views</a></li> <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="#id7">Creating Users</a></li> <li><a class="reference internal" href="#id8">Changing Passwords</a></li> </ul> </li> </ul> </li> </ul> <h3>Browse</h3> <ul> <li>Prev: <a href="index.html">User authentication in Django</a></li> <li>Next: <a href="passwords.html">Password management in Django</a></li> </ul> <h3>You are here:</h3> <ul> <li> <a href="../../index.html">Django 1.8.19 documentation</a> <ul><li><a href="../index.html">Using Django</a> <ul><li><a href="index.html">User authentication in Django</a> <ul><li>Using the Django authentication system</li></ul> </li></ul></li></ul> </li> </ul> <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> <form class="search" action="../../search.html" method="get"> <div><input type="text" name="q" /></div> <div><input type="submit" value="Go" /></div> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <h3>Last update:</h3> <p class="topless">Mar 10, 2018</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>