<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang=""> <head> <meta http-equiv="X-UA-Compatible" content="IE=Edge" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Customizing authentication in Django — Django 1.11.20 documentation</title> <link rel="stylesheet" href="../../_static/default.css" type="text/css" /> <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" /> <script type="text/javascript" id="documentation_options" data-url_root="../../" src="../../_static/documentation_options.js"></script> <script type="text/javascript" src="../../_static/jquery.js"></script> <script type="text/javascript" src="../../_static/underscore.js"></script> <script type="text/javascript" src="../../_static/doctools.js"></script> <script type="text/javascript" src="../../_static/language_data.js"></script> <link rel="index" title="Index" href="../../genindex.html" /> <link rel="search" title="Search" href="../../search.html" /> <link rel="next" title="Django’s cache framework" href="../cache.html" /> <link rel="prev" title="Password management in Django" href="passwords.html" /> <script type="text/javascript" src="../../templatebuiltins.js"></script> <script type="text/javascript"> (function($) { if (!django_template_builtins) { // templatebuiltins.js missing, do nothing. return; } $(document).ready(function() { // Hyperlink Django template tags and filters var base = "../../ref/templates/builtins.html"; if (base == "#") { // Special case for builtins.html itself base = ""; } // Tags are keywords, class '.k' $("div.highlight\\-html\\+django span.k").each(function(i, elem) { var tagname = $(elem).text(); if ($.inArray(tagname, django_template_builtins.ttags) != -1) { var fragment = tagname.replace(/_/, '-'); $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>"); } }); // Filters are functions, class '.nf' $("div.highlight\\-html\\+django span.nf").each(function(i, elem) { var filtername = $(elem).text(); if ($.inArray(filtername, django_template_builtins.tfilters) != -1) { var fragment = filtername.replace(/_/, '-'); $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>"); } }); }); })(jQuery); </script> </head><body> <div class="document"> <div id="custom-doc" class="yui-t6"> <div id="hd"> <h1><a href="../../index.html">Django 1.11.20 documentation</a></h1> <div id="global-nav"> <a title="Home page" href="../../index.html">Home</a> | <a title="Table of contents" href="../../contents.html">Table of contents</a> | <a title="Global index" href="../../genindex.html">Index</a> | <a title="Module index" href="../../py-modindex.html">Modules</a> </div> <div class="nav"> « <a href="passwords.html" title="Password management in Django">previous</a> | <a href="../index.html" title="Using Django" accesskey="U">up</a> | <a href="../cache.html" title="Django’s cache framework">next</a> »</div> </div> <div id="bd"> <div id="yui-main"> <div class="yui-b"> <div class="yui-g" id="topics-auth-customizing"> <div class="section" id="s-customizing-authentication-in-django"> <span id="customizing-authentication-in-django"></span><h1>Customizing authentication in Django<a class="headerlink" href="#customizing-authentication-in-django" title="Permalink to this headline">¶</a></h1> <p>The authentication that comes with Django is good enough for most common cases, but you may have needs not met by the out-of-the-box defaults. To customize authentication to your projects needs involves understanding what points of the provided system are extensible or replaceable. This document provides details about how the auth system can be customized.</p> <p><a class="reference internal" href="#authentication-backends"><span class="std std-ref">Authentication backends</span></a> provide an extensible system for when a username and password stored with the user model need to be authenticated against a different service than Django’s default.</p> <p>You can give your models <a class="reference internal" href="#custom-permissions"><span class="std std-ref">custom permissions</span></a> that can be checked through Django’s authorization system.</p> <p>You can <a class="reference internal" href="#extending-user"><span class="std std-ref">extend</span></a> the default <code class="docutils literal notranslate"><span class="pre">User</span></code> model, or <a class="reference internal" href="#auth-custom-user"><span class="std std-ref">substitute</span></a> a completely customized model.</p> <div class="section" id="s-other-authentication-sources"> <span id="s-authentication-backends"></span><span id="other-authentication-sources"></span><span id="authentication-backends"></span><h2>Other authentication sources<a class="headerlink" href="#other-authentication-sources" title="Permalink to this headline">¶</a></h2> <p>There may be times you have the need to hook into another authentication source – that is, another source of usernames and passwords or authentication methods.</p> <p>For example, your company may already have an LDAP setup that stores a username and password for every employee. It’d be a hassle for both the network administrator and the users themselves if users had separate accounts in LDAP and the Django-based applications.</p> <p>So, to handle situations like this, the Django authentication system lets you plug in other authentication sources. You can override Django’s default database-based scheme, or you can use the default system in tandem with other systems.</p> <p>See the <a class="reference internal" href="../../ref/contrib/auth.html#authentication-backends-reference"><span class="std std-ref">authentication backend reference</span></a> for information on the authentication backends included with Django.</p> <div class="section" id="s-specifying-authentication-backends"> <span id="specifying-authentication-backends"></span><h3>Specifying authentication backends<a class="headerlink" href="#specifying-authentication-backends" title="Permalink to this headline">¶</a></h3> <p>Behind the scenes, Django maintains a list of “authentication backends” that it checks for authentication. When somebody calls <a class="reference internal" href="default.html#django.contrib.auth.authenticate" title="django.contrib.auth.authenticate"><code class="xref py py-func docutils literal notranslate"><span class="pre">django.contrib.auth.authenticate()</span></code></a> – as described in <a class="reference internal" href="default.html#how-to-log-a-user-in"><span class="std std-ref">How to log a user in</span></a> – Django tries authenticating across all of its authentication backends. If the first authentication method fails, Django tries the second one, and so on, until all backends have been attempted.</p> <p>The list of authentication backends to use is specified in the <a class="reference internal" href="../../ref/settings.html#std:setting-AUTHENTICATION_BACKENDS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">AUTHENTICATION_BACKENDS</span></code></a> setting. This should be a list of Python path names that point to Python classes that know how to authenticate. These classes can be anywhere on your Python path.</p> <p>By default, <a class="reference internal" href="../../ref/settings.html#std:setting-AUTHENTICATION_BACKENDS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">AUTHENTICATION_BACKENDS</span></code></a> is set to:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">[</span><span class="s1">'django.contrib.auth.backends.ModelBackend'</span><span class="p">]</span> </pre></div> </div> <p>That’s the basic authentication backend that checks the Django users database and queries the built-in permissions. It does not provide protection against brute force attacks via any rate limiting mechanism. You may either implement your own rate limiting mechanism in a custom auth backend, or use the mechanisms provided by most Web servers.</p> <p>The order of <a class="reference internal" href="../../ref/settings.html#std:setting-AUTHENTICATION_BACKENDS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">AUTHENTICATION_BACKENDS</span></code></a> matters, so if the same username and password is valid in multiple backends, Django will stop processing at the first positive match.</p> <p>If a backend raises a <a class="reference internal" href="../../ref/exceptions.html#django.core.exceptions.PermissionDenied" title="django.core.exceptions.PermissionDenied"><code class="xref py py-class docutils literal notranslate"><span class="pre">PermissionDenied</span></code></a> exception, authentication will immediately fail. Django won’t check the backends that follow.</p> <div class="admonition note"> <p class="first admonition-title">Note</p> <p class="last">Once a user has authenticated, Django stores which backend was used to authenticate the user in the user’s session, and re-uses the same backend for the duration of that session whenever access to the currently authenticated user is needed. This effectively means that authentication sources are cached on a per-session basis, so if you change <a class="reference internal" href="../../ref/settings.html#std:setting-AUTHENTICATION_BACKENDS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">AUTHENTICATION_BACKENDS</span></code></a>, you’ll need to clear out session data if you need to force users to re-authenticate using different methods. A simple way to do that is simply to execute <code class="docutils literal notranslate"><span class="pre">Session.objects.all().delete()</span></code>.</p> </div> </div> <div class="section" id="s-writing-an-authentication-backend"> <span id="writing-an-authentication-backend"></span><h3>Writing an authentication backend<a class="headerlink" href="#writing-an-authentication-backend" title="Permalink to this headline">¶</a></h3> <p>An authentication backend is a class that implements two required methods: <code class="docutils literal notranslate"><span class="pre">get_user(user_id)</span></code> and <code class="docutils literal notranslate"><span class="pre">authenticate(request,</span> <span class="pre">**credentials)</span></code>, as well as a set of optional permission related <a class="reference internal" href="#authorization-methods"><span class="std std-ref">authorization methods</span></a>.</p> <p>The <code class="docutils literal notranslate"><span class="pre">get_user</span></code> method takes a <code class="docutils literal notranslate"><span class="pre">user_id</span></code> – which could be a username, database ID or whatever, but has to be the primary key of your user object – and returns a user object.</p> <p>The <code class="docutils literal notranslate"><span class="pre">authenticate</span></code> method takes a <code class="docutils literal notranslate"><span class="pre">request</span></code> argument and credentials as keyword arguments. Most of the time, it’ll just look like this:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">MyBackend</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span> <span class="k">def</span> <span class="nf">authenticate</span><span class="p">(</span><span class="bp">self</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="kc">None</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span> <span class="c1"># Check the username/password and return a user.</span> <span class="o">...</span> </pre></div> </div> <p>But it could also authenticate a token, like so:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">MyBackend</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span> <span class="k">def</span> <span class="nf">authenticate</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">request</span><span class="p">,</span> <span class="n">token</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span> <span class="c1"># Check the token and return a user.</span> <span class="o">...</span> </pre></div> </div> <p>Either way, <code class="docutils literal notranslate"><span class="pre">authenticate()</span></code> should check the credentials it gets and return a user object that matches those credentials if the credentials are valid. If they’re not valid, it should return <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p> <p><code class="docutils literal notranslate"><span class="pre">request</span></code> is an <a class="reference internal" href="../../ref/request-response.html#django.http.HttpRequest" title="django.http.HttpRequest"><code class="xref py py-class docutils literal notranslate"><span class="pre">HttpRequest</span></code></a> and may be <code class="docutils literal notranslate"><span class="pre">None</span></code> if it wasn’t provided to <a class="reference internal" href="default.html#django.contrib.auth.authenticate" title="django.contrib.auth.authenticate"><code class="xref py py-func docutils literal notranslate"><span class="pre">authenticate()</span></code></a> (which passes it on to the backend).</p> <p>The Django admin is tightly coupled to the Django <a class="reference internal" href="default.html#user-objects"><span class="std std-ref">User object</span></a>. The best way to deal with this is to create a Django <code class="docutils literal notranslate"><span class="pre">User</span></code> object for each user that exists for your backend (e.g., in your LDAP directory, your external SQL database, etc.) You can either write a script to do this in advance, or your <code class="docutils literal notranslate"><span class="pre">authenticate</span></code> method can do it the first time a user logs in.</p> <p>Here’s an example backend that authenticates against a username and password variable defined in your <code class="docutils literal notranslate"><span class="pre">settings.py</span></code> file and creates a Django <code class="docutils literal notranslate"><span class="pre">User</span></code> object the first time a user authenticates:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.conf</span> <span class="k">import</span> <span class="n">settings</span> <span class="kn">from</span> <span class="nn">django.contrib.auth.hashers</span> <span class="k">import</span> <span class="n">check_password</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="k">class</span> <span class="nc">SettingsBackend</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span> <span class="sd">"""</span> <span class="sd"> Authenticate against the settings ADMIN_LOGIN and ADMIN_PASSWORD.</span> <span class="sd"> Use the login name and a hash of the password. For example:</span> <span class="sd"> ADMIN_LOGIN = 'admin'</span> <span class="sd"> ADMIN_PASSWORD = 'pbkdf2_sha256$30000$Vo0VlMnkR4Bk$qEvtdyZRWTcOsCnI/oQ7fVOu1XAURIZYoOZ3iq8Dr4M='</span> <span class="sd"> """</span> <span class="k">def</span> <span class="nf">authenticate</span><span class="p">(</span><span class="bp">self</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="kc">None</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span> <span class="n">login_valid</span> <span class="o">=</span> <span class="p">(</span><span class="n">settings</span><span class="o">.</span><span class="n">ADMIN_LOGIN</span> <span class="o">==</span> <span class="n">username</span><span class="p">)</span> <span class="n">pwd_valid</span> <span class="o">=</span> <span class="n">check_password</span><span class="p">(</span><span class="n">password</span><span class="p">,</span> <span class="n">settings</span><span class="o">.</span><span class="n">ADMIN_PASSWORD</span><span class="p">)</span> <span class="k">if</span> <span class="n">login_valid</span> <span class="ow">and</span> <span class="n">pwd_valid</span><span class="p">:</span> <span class="k">try</span><span class="p">:</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">get</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="k">except</span> <span class="n">User</span><span class="o">.</span><span class="n">DoesNotExist</span><span class="p">:</span> <span class="c1"># Create a new user. There's no need to set a password</span> <span class="c1"># because only the password from settings.py is checked.</span> <span class="n">user</span> <span class="o">=</span> <span class="n">User</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">user</span><span class="o">.</span><span class="n">is_staff</span> <span class="o">=</span> <span class="kc">True</span> <span class="n">user</span><span class="o">.</span><span class="n">is_superuser</span> <span class="o">=</span> <span class="kc">True</span> <span class="n">user</span><span class="o">.</span><span class="n">save</span><span class="p">()</span> <span class="k">return</span> <span class="n">user</span> <span class="k">return</span> <span class="kc">None</span> <span class="k">def</span> <span class="nf">get_user</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">user_id</span><span class="p">):</span> <span class="k">try</span><span class="p">:</span> <span class="k">return</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">pk</span><span class="o">=</span><span class="n">user_id</span><span class="p">)</span> <span class="k">except</span> <span class="n">User</span><span class="o">.</span><span class="n">DoesNotExist</span><span class="p">:</span> <span class="k">return</span> <span class="kc">None</span> </pre></div> </div> <div class="versionchanged"> <span class="title">Changed in Django 1.11:</span> <p>The <code class="docutils literal notranslate"><span class="pre">request</span></code> parameter was added to <code class="docutils literal notranslate"><span class="pre">authenticate()</span></code> and support for backends that don’t accept it will be removed in Django 2.1.</p> </div> </div> <div class="section" id="s-handling-authorization-in-custom-backends"> <span id="s-authorization-methods"></span><span id="handling-authorization-in-custom-backends"></span><span id="authorization-methods"></span><h3>Handling authorization in custom backends<a class="headerlink" href="#handling-authorization-in-custom-backends" title="Permalink to this headline">¶</a></h3> <p>Custom auth backends can provide their own permissions.</p> <p>The user model will delegate permission lookup functions (<a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User.get_group_permissions" title="django.contrib.auth.models.User.get_group_permissions"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_group_permissions()</span></code></a>, <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User.get_all_permissions" title="django.contrib.auth.models.User.get_all_permissions"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_all_permissions()</span></code></a>, <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User.has_perm" title="django.contrib.auth.models.User.has_perm"><code class="xref py py-meth docutils literal notranslate"><span class="pre">has_perm()</span></code></a>, and <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User.has_module_perms" title="django.contrib.auth.models.User.has_module_perms"><code class="xref py py-meth docutils literal notranslate"><span class="pre">has_module_perms()</span></code></a>) to any authentication backend that implements these functions.</p> <p>The permissions given to the user will be the superset of all permissions returned by all backends. That is, Django grants a permission to a user that any one backend grants.</p> <p>If a backend raises a <a class="reference internal" href="../../ref/exceptions.html#django.core.exceptions.PermissionDenied" title="django.core.exceptions.PermissionDenied"><code class="xref py py-class docutils literal notranslate"><span class="pre">PermissionDenied</span></code></a> exception in <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User.has_perm" title="django.contrib.auth.models.User.has_perm"><code class="xref py py-meth docutils literal notranslate"><span class="pre">has_perm()</span></code></a> or <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User.has_module_perms" title="django.contrib.auth.models.User.has_module_perms"><code class="xref py py-meth docutils literal notranslate"><span class="pre">has_module_perms()</span></code></a>, the authorization will immediately fail and Django won’t check the backends that follow.</p> <p>The simple backend above could implement permissions for the magic admin fairly simply:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">SettingsBackend</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span> <span class="o">...</span> <span class="k">def</span> <span class="nf">has_perm</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">user_obj</span><span class="p">,</span> <span class="n">perm</span><span class="p">,</span> <span class="n">obj</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span> <span class="k">return</span> <span class="n">user_obj</span><span class="o">.</span><span class="n">username</span> <span class="o">==</span> <span class="n">settings</span><span class="o">.</span><span class="n">ADMIN_LOGIN</span> </pre></div> </div> <p>This gives full permissions to the user granted access in the above example. Notice that in addition to the same arguments given to the associated <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User" title="django.contrib.auth.models.User"><code class="xref py py-class docutils literal notranslate"><span class="pre">django.contrib.auth.models.User</span></code></a> functions, the backend auth functions all take the user object, which may be an anonymous user, as an argument.</p> <p>A full authorization implementation can be found in the <code class="docutils literal notranslate"><span class="pre">ModelBackend</span></code> class in <a class="reference external" href="https://github.com/django/django/blob/master/django/contrib/auth/backends.py">django/contrib/auth/backends.py</a>, which is the default backend and queries the <code class="docutils literal notranslate"><span class="pre">auth_permission</span></code> table most of the time. If you wish to provide custom behavior for only part of the backend API, you can take advantage of Python inheritance and subclass <code class="docutils literal notranslate"><span class="pre">ModelBackend</span></code> instead of implementing the complete API in a custom backend.</p> <div class="section" id="s-authorization-for-anonymous-users"> <span id="s-anonymous-auth"></span><span id="authorization-for-anonymous-users"></span><span id="anonymous-auth"></span><h4>Authorization for anonymous users<a class="headerlink" href="#authorization-for-anonymous-users" title="Permalink to this headline">¶</a></h4> <p>An anonymous user is one that is not authenticated i.e. they have provided no valid authentication details. However, that does not necessarily mean they are not authorized to do anything. At the most basic level, most websites authorize anonymous users to browse most of the site, and many allow anonymous posting of comments etc.</p> <p>Django’s permission framework does not have a place to store permissions for anonymous users. However, the user object passed to an authentication backend may be an <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.AnonymousUser" title="django.contrib.auth.models.AnonymousUser"><code class="xref py py-class docutils literal notranslate"><span class="pre">django.contrib.auth.models.AnonymousUser</span></code></a> object, allowing the backend to specify custom authorization behavior for anonymous users. This is especially useful for the authors of re-usable apps, who can delegate all questions of authorization to the auth backend, rather than needing settings, for example, to control anonymous access.</p> </div> <div class="section" id="s-authorization-for-inactive-users"> <span id="s-inactive-auth"></span><span id="authorization-for-inactive-users"></span><span id="inactive-auth"></span><h4>Authorization for inactive users<a class="headerlink" href="#authorization-for-inactive-users" title="Permalink to this headline">¶</a></h4> <p>An inactive user is one that has its <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User.is_active" title="django.contrib.auth.models.User.is_active"><code class="xref py py-attr docutils literal notranslate"><span class="pre">is_active</span></code></a> field set to <code class="docutils literal notranslate"><span class="pre">False</span></code>. The <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.backends.ModelBackend" title="django.contrib.auth.backends.ModelBackend"><code class="xref py py-class docutils literal notranslate"><span class="pre">ModelBackend</span></code></a> and <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.backends.RemoteUserBackend" title="django.contrib.auth.backends.RemoteUserBackend"><code class="xref py py-class docutils literal notranslate"><span class="pre">RemoteUserBackend</span></code></a> authentication backends prohibits these users from authenticating. If a custom user model doesn’t have an <a class="reference internal" href="#django.contrib.auth.models.CustomUser.is_active" title="django.contrib.auth.models.CustomUser.is_active"><code class="xref py py-attr docutils literal notranslate"><span class="pre">is_active</span></code></a> field, all users will be allowed to authenticate.</p> <p>You can use <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.backends.AllowAllUsersModelBackend" title="django.contrib.auth.backends.AllowAllUsersModelBackend"><code class="xref py py-class docutils literal notranslate"><span class="pre">AllowAllUsersModelBackend</span></code></a> or <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.backends.AllowAllUsersRemoteUserBackend" title="django.contrib.auth.backends.AllowAllUsersRemoteUserBackend"><code class="xref py py-class docutils literal notranslate"><span class="pre">AllowAllUsersRemoteUserBackend</span></code></a> if you want to allow inactive users to authenticate.</p> <p>The support for anonymous users in the permission system allows for a scenario where anonymous users have permissions to do something while inactive authenticated users do not.</p> <p>Do not forget to test for the <code class="docutils literal notranslate"><span class="pre">is_active</span></code> attribute of the user in your own backend permission methods.</p> <div class="versionchanged"> <span class="title">Changed in Django 1.10:</span> <p>In older versions, the <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.backends.ModelBackend" title="django.contrib.auth.backends.ModelBackend"><code class="xref py py-class docutils literal notranslate"><span class="pre">ModelBackend</span></code></a> allowed inactive users to authenticate.</p> </div> </div> <div class="section" id="s-handling-object-permissions"> <span id="handling-object-permissions"></span><h4>Handling object permissions<a class="headerlink" href="#handling-object-permissions" title="Permalink to this headline">¶</a></h4> <p>Django’s permission framework has a foundation for object permissions, though there is no implementation for it in the core. That means that checking for object permissions will always return <code class="docutils literal notranslate"><span class="pre">False</span></code> or an empty list (depending on the check performed). An authentication backend will receive the keyword parameters <code class="docutils literal notranslate"><span class="pre">obj</span></code> and <code class="docutils literal notranslate"><span class="pre">user_obj</span></code> for each object related authorization method and can return the object level permission as appropriate.</p> </div> </div> </div> <div class="section" id="s-custom-permissions"> <span id="s-id1"></span><span id="custom-permissions"></span><span id="id1"></span><h2>Custom permissions<a class="headerlink" href="#custom-permissions" title="Permalink to this headline">¶</a></h2> <p>To create custom permissions for a given model object, use the <code class="docutils literal notranslate"><span class="pre">permissions</span></code> <a class="reference internal" href="../db/models.html#meta-options"><span class="std std-ref">model Meta attribute</span></a>.</p> <p>This example Task model creates three custom permissions, i.e., actions users can or cannot do with Task instances, specific to your application:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Task</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span> <span class="o">...</span> <span class="k">class</span> <span class="nc">Meta</span><span class="p">:</span> <span class="n">permissions</span> <span class="o">=</span> <span class="p">(</span> <span class="p">(</span><span class="s2">"view_task"</span><span class="p">,</span> <span class="s2">"Can see available tasks"</span><span class="p">),</span> <span class="p">(</span><span class="s2">"change_task_status"</span><span class="p">,</span> <span class="s2">"Can change the status of tasks"</span><span class="p">),</span> <span class="p">(</span><span class="s2">"close_task"</span><span class="p">,</span> <span class="s2">"Can remove a task by setting its status as closed"</span><span class="p">),</span> <span class="p">)</span> </pre></div> </div> <p>The only thing this does is create those extra permissions when you run <a class="reference internal" href="../../ref/django-admin.html#django-admin-migrate"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">manage.py</span> <span class="pre">migrate</span></code></a> (the function that creates permissions is connected to the <a class="reference internal" href="../../ref/signals.html#django.db.models.signals.post_migrate" title="django.db.models.signals.post_migrate"><code class="xref py py-data docutils literal notranslate"><span class="pre">post_migrate</span></code></a> signal). Your code is in charge of checking the value of these permissions when a user is trying to access the functionality provided by the application (viewing tasks, changing the status of tasks, closing tasks.) Continuing the above example, the following checks if a user may view tasks:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">user</span><span class="o">.</span><span class="n">has_perm</span><span class="p">(</span><span class="s1">'app.view_task'</span><span class="p">)</span> </pre></div> </div> </div> <div class="section" id="s-extending-the-existing-user-model"> <span id="s-extending-user"></span><span id="extending-the-existing-user-model"></span><span id="extending-user"></span><h2>Extending the existing <code class="docutils literal notranslate"><span class="pre">User</span></code> model<a class="headerlink" href="#extending-the-existing-user-model" title="Permalink to this headline">¶</a></h2> <p>There are two ways to extend the default <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User" title="django.contrib.auth.models.User"><code class="xref py py-class docutils literal notranslate"><span class="pre">User</span></code></a> model without substituting your own model. If the changes you need are purely behavioral, and don’t require any change to what is stored in the database, you can create a <a class="reference internal" href="../db/models.html#proxy-models"><span class="std std-ref">proxy model</span></a> based on <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User" title="django.contrib.auth.models.User"><code class="xref py py-class docutils literal notranslate"><span class="pre">User</span></code></a>. This allows for any of the features offered by proxy models including default ordering, custom managers, or custom model methods.</p> <p>If you wish to store information related to <code class="docutils literal notranslate"><span class="pre">User</span></code>, you can use a <a class="reference internal" href="../../ref/models/fields.html#django.db.models.OneToOneField" title="django.db.models.OneToOneField"><code class="xref py py-class docutils literal notranslate"><span class="pre">OneToOneField</span></code></a> to a model containing the fields for additional information. This one-to-one model is often called a profile model, as it might store non-auth related information about a site user. For example you might create an Employee model:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.contrib.auth.models</span> <span class="k">import</span> <span class="n">User</span> <span class="k">class</span> <span class="nc">Employee</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span> <span class="n">user</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">OneToOneField</span><span class="p">(</span><span class="n">User</span><span class="p">,</span> <span class="n">on_delete</span><span class="o">=</span><span class="n">models</span><span class="o">.</span><span class="n">CASCADE</span><span class="p">)</span> <span class="n">department</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">100</span><span class="p">)</span> </pre></div> </div> <p>Assuming an existing Employee Fred Smith who has both a User and Employee model, you can access the related information using Django’s standard related model conventions:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></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">'fsmith'</span><span class="p">)</span> <span class="gp">>>> </span><span class="n">freds_department</span> <span class="o">=</span> <span class="n">u</span><span class="o">.</span><span class="n">employee</span><span class="o">.</span><span class="n">department</span> </pre></div> </div> <p>To add a profile model’s fields to the user page in the admin, define an <a class="reference internal" href="../../ref/contrib/admin/index.html#django.contrib.admin.InlineModelAdmin" title="django.contrib.admin.InlineModelAdmin"><code class="xref py py-class docutils literal notranslate"><span class="pre">InlineModelAdmin</span></code></a> (for this example, we’ll use a <a class="reference internal" href="../../ref/contrib/admin/index.html#django.contrib.admin.StackedInline" title="django.contrib.admin.StackedInline"><code class="xref py py-class docutils literal notranslate"><span class="pre">StackedInline</span></code></a>) in your app’s <code class="docutils literal notranslate"><span class="pre">admin.py</span></code> and add it to a <code class="docutils literal notranslate"><span class="pre">UserAdmin</span></code> class which is registered with the <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User" title="django.contrib.auth.models.User"><code class="xref py py-class docutils literal notranslate"><span class="pre">User</span></code></a> class:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.contrib</span> <span class="k">import</span> <span class="n">admin</span> <span class="kn">from</span> <span class="nn">django.contrib.auth.admin</span> <span class="k">import</span> <span class="n">UserAdmin</span> <span class="k">as</span> <span class="n">BaseUserAdmin</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="kn">from</span> <span class="nn">my_user_profile_app.models</span> <span class="k">import</span> <span class="n">Employee</span> <span class="c1"># Define an inline admin descriptor for Employee model</span> <span class="c1"># which acts a bit like a singleton</span> <span class="k">class</span> <span class="nc">EmployeeInline</span><span class="p">(</span><span class="n">admin</span><span class="o">.</span><span class="n">StackedInline</span><span class="p">):</span> <span class="n">model</span> <span class="o">=</span> <span class="n">Employee</span> <span class="n">can_delete</span> <span class="o">=</span> <span class="kc">False</span> <span class="n">verbose_name_plural</span> <span class="o">=</span> <span class="s1">'employee'</span> <span class="c1"># Define a new User admin</span> <span class="k">class</span> <span class="nc">UserAdmin</span><span class="p">(</span><span class="n">BaseUserAdmin</span><span class="p">):</span> <span class="n">inlines</span> <span class="o">=</span> <span class="p">(</span><span class="n">EmployeeInline</span><span class="p">,</span> <span class="p">)</span> <span class="c1"># Re-register UserAdmin</span> <span class="n">admin</span><span class="o">.</span><span class="n">site</span><span class="o">.</span><span class="n">unregister</span><span class="p">(</span><span class="n">User</span><span class="p">)</span> <span class="n">admin</span><span class="o">.</span><span class="n">site</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="n">User</span><span class="p">,</span> <span class="n">UserAdmin</span><span class="p">)</span> </pre></div> </div> <p>These profile models are not special in any way - they are just Django models that happen to have a one-to-one link with a user model. As such, they aren’t auto created when a user is created, but a <a class="reference internal" href="../../ref/signals.html#django.db.models.signals.post_save" title="django.db.models.signals.post_save"><code class="xref py py-attr docutils literal notranslate"><span class="pre">django.db.models.signals.post_save</span></code></a> could be used to create or update related models as appropriate.</p> <p>Using related models results in additional queries or joins to retrieve the related data. Depending on your needs, a custom user model that includes the related fields may be your better option, however, existing relations to the default user model within your project’s apps may justify the extra database load.</p> </div> <div class="section" id="s-substituting-a-custom-user-model"> <span id="s-auth-custom-user"></span><span id="substituting-a-custom-user-model"></span><span id="auth-custom-user"></span><h2>Substituting a custom <code class="docutils literal notranslate"><span class="pre">User</span></code> model<a class="headerlink" href="#substituting-a-custom-user-model" title="Permalink to this headline">¶</a></h2> <p>Some kinds of projects may have authentication requirements for which Django’s built-in <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User" title="django.contrib.auth.models.User"><code class="xref py py-class docutils literal notranslate"><span class="pre">User</span></code></a> model is not always appropriate. For instance, on some sites it makes more sense to use an email address as your identification token instead of a username.</p> <p>Django allows you to override the default user model by providing a value for the <a class="reference internal" href="../../ref/settings.html#std:setting-AUTH_USER_MODEL"><code class="xref std std-setting docutils literal notranslate"><span class="pre">AUTH_USER_MODEL</span></code></a> setting that references a custom model:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">AUTH_USER_MODEL</span> <span class="o">=</span> <span class="s1">'myapp.MyUser'</span> </pre></div> </div> <p>This dotted pair describes the name of the Django app (which must be in your <a class="reference internal" href="../../ref/settings.html#std:setting-INSTALLED_APPS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">INSTALLED_APPS</span></code></a>), and the name of the Django model that you wish to use as your user model.</p> <div class="section" id="s-using-a-custom-user-model-when-starting-a-project"> <span id="using-a-custom-user-model-when-starting-a-project"></span><h3>Using a custom user model when starting a project<a class="headerlink" href="#using-a-custom-user-model-when-starting-a-project" title="Permalink to this headline">¶</a></h3> <p>If you’re starting a new project, it’s highly recommended to set up a custom user model, even if the default <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User" title="django.contrib.auth.models.User"><code class="xref py py-class docutils literal notranslate"><span class="pre">User</span></code></a> model is sufficient for you. This model behaves identically to the default user model, but you’ll be able to customize it in the future if the need arises:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.contrib.auth.models</span> <span class="k">import</span> <span class="n">AbstractUser</span> <span class="k">class</span> <span class="nc">User</span><span class="p">(</span><span class="n">AbstractUser</span><span class="p">):</span> <span class="k">pass</span> </pre></div> </div> <p>Don’t forget to point <a class="reference internal" href="../../ref/settings.html#std:setting-AUTH_USER_MODEL"><code class="xref std std-setting docutils literal notranslate"><span class="pre">AUTH_USER_MODEL</span></code></a> to it. Do this before creating any migrations or running <code class="docutils literal notranslate"><span class="pre">manage.py</span> <span class="pre">migrate</span></code> for the first time.</p> <p>Also, register the model in the app’s <code class="docutils literal notranslate"><span class="pre">admin.py</span></code>:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.contrib</span> <span class="k">import</span> <span class="n">admin</span> <span class="kn">from</span> <span class="nn">django.contrib.auth.admin</span> <span class="k">import</span> <span class="n">UserAdmin</span> <span class="kn">from</span> <span class="nn">.models</span> <span class="k">import</span> <span class="n">User</span> <span class="n">admin</span><span class="o">.</span><span class="n">site</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="n">User</span><span class="p">,</span> <span class="n">UserAdmin</span><span class="p">)</span> </pre></div> </div> </div> <div class="section" id="s-changing-to-a-custom-user-model-mid-project"> <span id="changing-to-a-custom-user-model-mid-project"></span><h3>Changing to a custom user model mid-project<a class="headerlink" href="#changing-to-a-custom-user-model-mid-project" title="Permalink to this headline">¶</a></h3> <p>Changing <a class="reference internal" href="../../ref/settings.html#std:setting-AUTH_USER_MODEL"><code class="xref std std-setting docutils literal notranslate"><span class="pre">AUTH_USER_MODEL</span></code></a> after you’ve created database tables is significantly more difficult since it affects foreign keys and many-to-many relationships, for example.</p> <p>This change can’t be done automatically and requires manually fixing your schema, moving your data from the old user table, and possibly manually reapplying some migrations. See <a class="reference external" href="https://code.djangoproject.com/ticket/25313">#25313</a> for an outline of the steps.</p> <p>Due to limitations of Django’s dynamic dependency feature for swappable models, the model referenced by <a class="reference internal" href="../../ref/settings.html#std:setting-AUTH_USER_MODEL"><code class="xref std std-setting docutils literal notranslate"><span class="pre">AUTH_USER_MODEL</span></code></a> must be created in the first migration of its app (usually called <code class="docutils literal notranslate"><span class="pre">0001_initial</span></code>); otherwise, you’ll have dependency issues.</p> <p>In addition, you may run into a <code class="docutils literal notranslate"><span class="pre">CircularDependencyError</span></code> when running your migrations as Django won’t be able to automatically break the dependency loop due to the dynamic dependency. If you see this error, you should break the loop by moving the models depended on by your user model into a second migration. (You can try making two normal models that have a <code class="docutils literal notranslate"><span class="pre">ForeignKey</span></code> to each other and seeing how <code class="docutils literal notranslate"><span class="pre">makemigrations</span></code> resolves that circular dependency if you want to see how it’s usually done.)</p> </div> <div class="section" id="s-reusable-apps-and-auth-user-model"> <span id="reusable-apps-and-auth-user-model"></span><h3>Reusable apps and <code class="docutils literal notranslate"><span class="pre">AUTH_USER_MODEL</span></code><a class="headerlink" href="#reusable-apps-and-auth-user-model" title="Permalink to this headline">¶</a></h3> <p>Reusable apps shouldn’t implement a custom user model. A project may use many apps, and two reusable apps that implemented a custom user model couldn’t be used together. If you need to store per user information in your app, use a <a class="reference internal" href="../../ref/models/fields.html#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><code class="xref py py-class docutils literal notranslate"><span class="pre">ForeignKey</span></code></a> or <a class="reference internal" href="../../ref/models/fields.html#django.db.models.OneToOneField" title="django.db.models.OneToOneField"><code class="xref py py-class docutils literal notranslate"><span class="pre">OneToOneField</span></code></a> to <code class="docutils literal notranslate"><span class="pre">settings.AUTH_USER_MODEL</span></code> as described below.</p> </div> <div class="section" id="s-referencing-the-user-model"> <span id="referencing-the-user-model"></span><h3>Referencing the <code class="docutils literal notranslate"><span class="pre">User</span></code> model<a class="headerlink" href="#referencing-the-user-model" title="Permalink to this headline">¶</a></h3> <p>If you reference <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User" title="django.contrib.auth.models.User"><code class="xref py py-class docutils literal notranslate"><span class="pre">User</span></code></a> directly (for example, by referring to it in a foreign key), your code will not work in projects where the <a class="reference internal" href="../../ref/settings.html#std:setting-AUTH_USER_MODEL"><code class="xref std std-setting docutils literal notranslate"><span class="pre">AUTH_USER_MODEL</span></code></a> setting has been changed to a different user model.</p> <dl class="function"> <dt id="django.contrib.auth.get_user_model"> <code class="descname">get_user_model</code>()<a class="reference internal" href="../../_modules/django/contrib/auth.html#get_user_model"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.contrib.auth.get_user_model" title="Permalink to this definition">¶</a></dt> <dd><p>Instead of referring to <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User" title="django.contrib.auth.models.User"><code class="xref py py-class docutils literal notranslate"><span class="pre">User</span></code></a> directly, you should reference the user model using <code class="docutils literal notranslate"><span class="pre">django.contrib.auth.get_user_model()</span></code>. This method will return the currently active user model – the custom user model if one is specified, or <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User" title="django.contrib.auth.models.User"><code class="xref py py-class docutils literal notranslate"><span class="pre">User</span></code></a> otherwise.</p> <p>When you define a foreign key or many-to-many relations to the user model, you should specify the custom model using the <a class="reference internal" href="../../ref/settings.html#std:setting-AUTH_USER_MODEL"><code class="xref std std-setting docutils literal notranslate"><span class="pre">AUTH_USER_MODEL</span></code></a> setting. For example:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.conf</span> <span class="k">import</span> <span class="n">settings</span> <span class="kn">from</span> <span class="nn">django.db</span> <span class="k">import</span> <span class="n">models</span> <span class="k">class</span> <span class="nc">Article</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span> <span class="n">author</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span> <span class="n">settings</span><span class="o">.</span><span class="n">AUTH_USER_MODEL</span><span class="p">,</span> <span class="n">on_delete</span><span class="o">=</span><span class="n">models</span><span class="o">.</span><span class="n">CASCADE</span><span class="p">,</span> <span class="p">)</span> </pre></div> </div> <p>When connecting to signals sent by the user model, you should specify the custom model using the <a class="reference internal" href="../../ref/settings.html#std:setting-AUTH_USER_MODEL"><code class="xref std std-setting docutils literal notranslate"><span class="pre">AUTH_USER_MODEL</span></code></a> setting. For example:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.conf</span> <span class="k">import</span> <span class="n">settings</span> <span class="kn">from</span> <span class="nn">django.db.models.signals</span> <span class="k">import</span> <span class="n">post_save</span> <span class="k">def</span> <span class="nf">post_save_receiver</span><span class="p">(</span><span class="n">sender</span><span class="p">,</span> <span class="n">instance</span><span class="p">,</span> <span class="n">created</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span> <span class="k">pass</span> <span class="n">post_save</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">post_save_receiver</span><span class="p">,</span> <span class="n">sender</span><span class="o">=</span><span class="n">settings</span><span class="o">.</span><span class="n">AUTH_USER_MODEL</span><span class="p">)</span> </pre></div> </div> <p>Generally speaking, it’s easiest to refer to the user model with the <a class="reference internal" href="../../ref/settings.html#std:setting-AUTH_USER_MODEL"><code class="xref std std-setting docutils literal notranslate"><span class="pre">AUTH_USER_MODEL</span></code></a> setting in code that’s executed at import time, however, it’s also possible to call <code class="docutils literal notranslate"><span class="pre">get_user_model()</span></code> while Django is importing models, so you could use <code class="docutils literal notranslate"><span class="pre">models.ForeignKey(get_user_model(),</span> <span class="pre">...)</span></code>.</p> <p>If your app is tested with multiple user models, using <code class="docutils literal notranslate"><span class="pre">@override_settings(AUTH_USER_MODEL=...)</span></code> for example, and you cache the result of <code class="docutils literal notranslate"><span class="pre">get_user_model()</span></code> in a module-level variable, you may need to listen to the <a class="reference internal" href="../../ref/signals.html#django.test.signals.setting_changed" title="django.test.signals.setting_changed"><code class="xref py py-data docutils literal notranslate"><span class="pre">setting_changed</span></code></a> signal to clear the cache. For example:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.apps</span> <span class="k">import</span> <span class="n">apps</span> <span class="kn">from</span> <span class="nn">django.contrib.auth</span> <span class="k">import</span> <span class="n">get_user_model</span> <span class="kn">from</span> <span class="nn">django.core.signals</span> <span class="k">import</span> <span class="n">setting_changed</span> <span class="kn">from</span> <span class="nn">django.dispatch</span> <span class="k">import</span> <span class="n">receiver</span> <span class="nd">@receiver</span><span class="p">(</span><span class="n">setting_changed</span><span class="p">)</span> <span class="k">def</span> <span class="nf">user_model_swapped</span><span class="p">(</span><span class="o">**</span><span class="n">kwargs</span><span class="p">):</span> <span class="k">if</span> <span class="n">kwargs</span><span class="p">[</span><span class="s1">'setting'</span><span class="p">]</span> <span class="o">==</span> <span class="s1">'AUTH_USER_MODEL'</span><span class="p">:</span> <span class="n">apps</span><span class="o">.</span><span class="n">clear_cache</span><span class="p">()</span> <span class="kn">from</span> <span class="nn">myapp</span> <span class="k">import</span> <span class="n">some_module</span> <span class="n">some_module</span><span class="o">.</span><span class="n">UserModel</span> <span class="o">=</span> <span class="n">get_user_model</span><span class="p">()</span> </pre></div> </div> <div class="versionchanged"> <span class="title">Changed in Django 1.11:</span> <p>The ability to call <code class="docutils literal notranslate"><span class="pre">get_user_model()</span></code> at import time was added.</p> </div> </dd></dl> </div> <div class="section" id="s-specifying-a-custom-user-model"> <span id="s-specifying-custom-user-model"></span><span id="specifying-a-custom-user-model"></span><span id="specifying-custom-user-model"></span><h3>Specifying a custom user model<a class="headerlink" href="#specifying-a-custom-user-model" title="Permalink to this headline">¶</a></h3> <div class="admonition-model-design-considerations admonition"> <p class="first admonition-title">Model design considerations</p> <p>Think carefully before handling information not directly related to authentication in your custom user model.</p> <p class="last">It may be better to store app-specific user information in a model that has a relation with the user model. That allows each app to specify its own user data requirements without risking conflicts with other apps. On the other hand, queries to retrieve this related information will involve a database join, which may have an effect on performance.</p> </div> <p>Django expects your custom user model to meet some minimum requirements.</p> <ol class="arabic simple"> <li>If you use the default authentication backend, then your model must have a single unique field that can be used for identification purposes. This can be a username, an email address, or any other unique attribute. A non-unique username field is allowed if you use a custom authentication backend that can support it.</li> <li>Your model must provide a way to address the user in a “short” and “long” form. The most common interpretation of this would be to use the user’s given name as the “short” identifier, and the user’s full name as the “long” identifier. However, there are no constraints on what these two methods return - if you want, they can return exactly the same value.</li> </ol> <p>The easiest way to construct a compliant custom user model is to inherit from <a class="reference internal" href="#django.contrib.auth.models.AbstractBaseUser" title="django.contrib.auth.models.AbstractBaseUser"><code class="xref py py-class docutils literal notranslate"><span class="pre">AbstractBaseUser</span></code></a>. <a class="reference internal" href="#django.contrib.auth.models.AbstractBaseUser" title="django.contrib.auth.models.AbstractBaseUser"><code class="xref py py-class docutils literal notranslate"><span class="pre">AbstractBaseUser</span></code></a> provides the core implementation of a user model, including hashed passwords and tokenized password resets. You must then provide some key implementation details:</p> <dl class="class"> <dt id="django.contrib.auth.models.CustomUser"> <em class="property">class </em><code class="descclassname">models.</code><code class="descname">CustomUser</code><a class="headerlink" href="#django.contrib.auth.models.CustomUser" title="Permalink to this definition">¶</a></dt> <dd><dl class="attribute"> <dt id="django.contrib.auth.models.CustomUser.USERNAME_FIELD"> <code class="descname">USERNAME_FIELD</code><a class="headerlink" href="#django.contrib.auth.models.CustomUser.USERNAME_FIELD" title="Permalink to this definition">¶</a></dt> <dd><p>A string describing the name of the field on the user model that is used as the unique identifier. This will usually be a username of some kind, but it can also be an email address, or any other unique identifier. The field <em>must</em> be unique (i.e., have <code class="docutils literal notranslate"><span class="pre">unique=True</span></code> set in its definition), unless you use a custom authentication backend that can support non-unique usernames.</p> <p>In the following example, the field <code class="docutils literal notranslate"><span class="pre">identifier</span></code> is used as the identifying field:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">MyUser</span><span class="p">(</span><span class="n">AbstractBaseUser</span><span class="p">):</span> <span class="n">identifier</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">40</span><span class="p">,</span> <span class="n">unique</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span> <span class="o">...</span> <span class="n">USERNAME_FIELD</span> <span class="o">=</span> <span class="s1">'identifier'</span> </pre></div> </div> <p><a class="reference internal" href="#django.contrib.auth.models.CustomUser.USERNAME_FIELD" title="django.contrib.auth.models.CustomUser.USERNAME_FIELD"><code class="xref py py-attr docutils literal notranslate"><span class="pre">USERNAME_FIELD</span></code></a> now supports <a class="reference internal" href="../../ref/models/fields.html#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><code class="xref py py-class docutils literal notranslate"><span class="pre">ForeignKey</span></code></a>s. Since there is no way to pass model instances during the <a class="reference internal" href="../../ref/django-admin.html#django-admin-createsuperuser"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">createsuperuser</span></code></a> prompt, expect the user to enter the value of <a class="reference internal" href="../../ref/models/fields.html#django.db.models.ForeignKey.to_field" title="django.db.models.ForeignKey.to_field"><code class="xref py py-attr docutils literal notranslate"><span class="pre">to_field</span></code></a> value (the <a class="reference internal" href="../../ref/models/fields.html#django.db.models.Field.primary_key" title="django.db.models.Field.primary_key"><code class="xref py py-attr docutils literal notranslate"><span class="pre">primary_key</span></code></a> by default) of an existing instance.</p> </dd></dl> <dl class="attribute"> <dt id="django.contrib.auth.models.CustomUser.EMAIL_FIELD"> <code class="descname">EMAIL_FIELD</code><a class="headerlink" href="#django.contrib.auth.models.CustomUser.EMAIL_FIELD" title="Permalink to this definition">¶</a></dt> <dd><div class="versionadded"> <span class="title">New in Django 1.11.</span> </div> <p>A string describing the name of the email field on the <code class="docutils literal notranslate"><span class="pre">User</span></code> model. This value is returned by <a class="reference internal" href="#django.contrib.auth.models.AbstractBaseUser.get_email_field_name" title="django.contrib.auth.models.AbstractBaseUser.get_email_field_name"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_email_field_name()</span></code></a>.</p> </dd></dl> <dl class="attribute"> <dt id="django.contrib.auth.models.CustomUser.REQUIRED_FIELDS"> <code class="descname">REQUIRED_FIELDS</code><a class="headerlink" href="#django.contrib.auth.models.CustomUser.REQUIRED_FIELDS" title="Permalink to this definition">¶</a></dt> <dd><p>A list of the field names that will be prompted for when creating a user via the <a class="reference internal" href="../../ref/django-admin.html#django-admin-createsuperuser"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">createsuperuser</span></code></a> management command. The user will be prompted to supply a value for each of these fields. It must include any field for which <a class="reference internal" href="../../ref/models/fields.html#django.db.models.Field.blank" title="django.db.models.Field.blank"><code class="xref py py-attr docutils literal notranslate"><span class="pre">blank</span></code></a> is <code class="docutils literal notranslate"><span class="pre">False</span></code> or undefined and may include additional fields you want prompted for when a user is created interactively. <code class="docutils literal notranslate"><span class="pre">REQUIRED_FIELDS</span></code> has no effect in other parts of Django, like creating a user in the admin.</p> <p>For example, here is the partial definition for a user model that defines two required fields - a date of birth and height:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">MyUser</span><span class="p">(</span><span class="n">AbstractBaseUser</span><span class="p">):</span> <span class="o">...</span> <span class="n">date_of_birth</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">DateField</span><span class="p">()</span> <span class="n">height</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">FloatField</span><span class="p">()</span> <span class="o">...</span> <span class="n">REQUIRED_FIELDS</span> <span class="o">=</span> <span class="p">[</span><span class="s1">'date_of_birth'</span><span class="p">,</span> <span class="s1">'height'</span><span class="p">]</span> </pre></div> </div> <div class="admonition note"> <p class="first admonition-title">Note</p> <p class="last"><code class="docutils literal notranslate"><span class="pre">REQUIRED_FIELDS</span></code> must contain all required fields on your user model, but should <em>not</em> contain the <code class="docutils literal notranslate"><span class="pre">USERNAME_FIELD</span></code> or <code class="docutils literal notranslate"><span class="pre">password</span></code> as these fields will always be prompted for.</p> </div> <p><a class="reference internal" href="#django.contrib.auth.models.CustomUser.REQUIRED_FIELDS" title="django.contrib.auth.models.CustomUser.REQUIRED_FIELDS"><code class="xref py py-attr docutils literal notranslate"><span class="pre">REQUIRED_FIELDS</span></code></a> now supports <a class="reference internal" href="../../ref/models/fields.html#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><code class="xref py py-class docutils literal notranslate"><span class="pre">ForeignKey</span></code></a>s. Since there is no way to pass model instances during the <a class="reference internal" href="../../ref/django-admin.html#django-admin-createsuperuser"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">createsuperuser</span></code></a> prompt, expect the user to enter the value of <a class="reference internal" href="../../ref/models/fields.html#django.db.models.ForeignKey.to_field" title="django.db.models.ForeignKey.to_field"><code class="xref py py-attr docutils literal notranslate"><span class="pre">to_field</span></code></a> value (the <a class="reference internal" href="../../ref/models/fields.html#django.db.models.Field.primary_key" title="django.db.models.Field.primary_key"><code class="xref py py-attr docutils literal notranslate"><span class="pre">primary_key</span></code></a> by default) of an existing instance.</p> </dd></dl> <dl class="attribute"> <dt id="django.contrib.auth.models.CustomUser.is_active"> <code class="descname">is_active</code><a class="headerlink" href="#django.contrib.auth.models.CustomUser.is_active" title="Permalink to this definition">¶</a></dt> <dd><p>A boolean attribute that indicates whether the user is considered “active”. This attribute is provided as an attribute on <code class="docutils literal notranslate"><span class="pre">AbstractBaseUser</span></code> defaulting to <code class="docutils literal notranslate"><span class="pre">True</span></code>. How you choose to implement it will depend on the details of your chosen auth backends. See the documentation of the <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User.is_active" title="django.contrib.auth.models.User.is_active"><code class="xref py py-attr docutils literal notranslate"><span class="pre">is_active</span> <span class="pre">attribute</span> <span class="pre">on</span> <span class="pre">the</span> <span class="pre">built-in</span> <span class="pre">user</span> <span class="pre">model</span></code></a> for details.</p> </dd></dl> <dl class="method"> <dt id="django.contrib.auth.models.CustomUser.get_full_name"> <code class="descname">get_full_name</code>()<a class="headerlink" href="#django.contrib.auth.models.CustomUser.get_full_name" title="Permalink to this definition">¶</a></dt> <dd><p>A longer formal identifier for the user. A common interpretation would be the full name of the user, but it can be any string that identifies the user.</p> </dd></dl> <dl class="method"> <dt id="django.contrib.auth.models.CustomUser.get_short_name"> <code class="descname">get_short_name</code>()<a class="headerlink" href="#django.contrib.auth.models.CustomUser.get_short_name" title="Permalink to this definition">¶</a></dt> <dd><p>A short, informal identifier for the user. A common interpretation would be the first name of the user, but it can be any string that identifies the user in an informal way. It may also return the same value as <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User.get_full_name" title="django.contrib.auth.models.User.get_full_name"><code class="xref py py-meth docutils literal notranslate"><span class="pre">django.contrib.auth.models.User.get_full_name()</span></code></a>.</p> </dd></dl> <div class="admonition-importing-abstractbaseuser admonition"> <p class="first admonition-title">Importing <code class="docutils literal notranslate"><span class="pre">AbstractBaseUser</span></code></p> <p class="last"><code class="docutils literal notranslate"><span class="pre">AbstractBaseUser</span></code> and <code class="docutils literal notranslate"><span class="pre">BaseUserManager</span></code> are importable from <code class="docutils literal notranslate"><span class="pre">django.contrib.auth.base_user</span></code> so that they can be imported without including <code class="docutils literal notranslate"><span class="pre">django.contrib.auth</span></code> in <a class="reference internal" href="../../ref/settings.html#std:setting-INSTALLED_APPS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">INSTALLED_APPS</span></code></a>.</p> </div> </dd></dl> <p>The following attributes and methods are available on any subclass of <a class="reference internal" href="#django.contrib.auth.models.AbstractBaseUser" title="django.contrib.auth.models.AbstractBaseUser"><code class="xref py py-class docutils literal notranslate"><span class="pre">AbstractBaseUser</span></code></a>:</p> <dl class="class"> <dt id="django.contrib.auth.models.AbstractBaseUser"> <em class="property">class </em><code class="descclassname">models.</code><code class="descname">AbstractBaseUser</code><a class="headerlink" href="#django.contrib.auth.models.AbstractBaseUser" title="Permalink to this definition">¶</a></dt> <dd><dl class="method"> <dt id="django.contrib.auth.models.AbstractBaseUser.get_username"> <code class="descname">get_username</code>()<a class="headerlink" href="#django.contrib.auth.models.AbstractBaseUser.get_username" title="Permalink to this definition">¶</a></dt> <dd><p>Returns the value of the field nominated by <code class="docutils literal notranslate"><span class="pre">USERNAME_FIELD</span></code>.</p> </dd></dl> <dl class="method"> <dt id="django.contrib.auth.models.AbstractBaseUser.clean"> <code class="descname">clean</code>()<a class="headerlink" href="#django.contrib.auth.models.AbstractBaseUser.clean" title="Permalink to this definition">¶</a></dt> <dd><div class="versionadded"> <span class="title">New in Django 1.10.</span> </div> <p>Normalizes the username by calling <a class="reference internal" href="#django.contrib.auth.models.AbstractBaseUser.normalize_username" title="django.contrib.auth.models.AbstractBaseUser.normalize_username"><code class="xref py py-meth docutils literal notranslate"><span class="pre">normalize_username()</span></code></a>. If you override this method, be sure to call <code class="docutils literal notranslate"><span class="pre">super()</span></code> to retain the normalization.</p> </dd></dl> <dl class="classmethod"> <dt id="django.contrib.auth.models.AbstractBaseUser.get_email_field_name"> <em class="property">classmethod </em><code class="descname">get_email_field_name</code>()<a class="headerlink" href="#django.contrib.auth.models.AbstractBaseUser.get_email_field_name" title="Permalink to this definition">¶</a></dt> <dd><div class="versionadded"> <span class="title">New in Django 1.11.</span> </div> <p>Returns the name of the email field specified by the <a class="reference internal" href="#django.contrib.auth.models.CustomUser.EMAIL_FIELD" title="django.contrib.auth.models.CustomUser.EMAIL_FIELD"><code class="xref py py-attr docutils literal notranslate"><span class="pre">EMAIL_FIELD</span></code></a> attribute. Defaults to <code class="docutils literal notranslate"><span class="pre">'email'</span></code> if <code class="docutils literal notranslate"><span class="pre">EMAIL_FIELD</span></code> isn’t specified.</p> </dd></dl> <dl class="classmethod"> <dt id="django.contrib.auth.models.AbstractBaseUser.normalize_username"> <em class="property">classmethod </em><code class="descname">normalize_username</code>(<em>username</em>)<a class="headerlink" href="#django.contrib.auth.models.AbstractBaseUser.normalize_username" title="Permalink to this definition">¶</a></dt> <dd><div class="versionadded"> <span class="title">New in Django 1.10.</span> </div> <p>Applies NFKC Unicode normalization to usernames so that visually identical characters with different Unicode code points are considered identical.</p> </dd></dl> <dl class="attribute"> <dt id="django.contrib.auth.models.AbstractBaseUser.is_authenticated"> <code class="descname">is_authenticated</code><a class="headerlink" href="#django.contrib.auth.models.AbstractBaseUser.is_authenticated" title="Permalink to this definition">¶</a></dt> <dd><p>Read-only attribute which is always <code class="docutils literal notranslate"><span class="pre">True</span></code> (as opposed to <code class="docutils literal notranslate"><span class="pre">AnonymousUser.is_authenticated</span></code> which is always <code class="docutils literal notranslate"><span class="pre">False</span></code>). This is a way to tell if the user has been authenticated. This does not imply any permissions and doesn’t check if the user is active or has a valid session. Even though normally you will check this attribute on <code class="docutils literal notranslate"><span class="pre">request.user</span></code> to find out whether it has been populated by the <a class="reference internal" href="../../ref/middleware.html#django.contrib.auth.middleware.AuthenticationMiddleware" title="django.contrib.auth.middleware.AuthenticationMiddleware"><code class="xref py py-class docutils literal notranslate"><span class="pre">AuthenticationMiddleware</span></code></a> (representing the currently logged-in user), you should know this attribute is <code class="docutils literal notranslate"><span class="pre">True</span></code> for any <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User" title="django.contrib.auth.models.User"><code class="xref py py-class docutils literal notranslate"><span class="pre">User</span></code></a> instance.</p> <div class="versionchanged"> <span class="title">Changed in Django 1.10:</span> <p>In older versions, this was a method. Backwards-compatibility support for using it as a method will be removed in Django 2.0.</p> </div> </dd></dl> <dl class="attribute"> <dt id="django.contrib.auth.models.AbstractBaseUser.is_anonymous"> <code class="descname">is_anonymous</code><a class="headerlink" href="#django.contrib.auth.models.AbstractBaseUser.is_anonymous" title="Permalink to this definition">¶</a></dt> <dd><p>Read-only attribute which is always <code class="docutils literal notranslate"><span class="pre">False</span></code>. This is a way of differentiating <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User" title="django.contrib.auth.models.User"><code class="xref py py-class docutils literal notranslate"><span class="pre">User</span></code></a> and <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.AnonymousUser" title="django.contrib.auth.models.AnonymousUser"><code class="xref py py-class docutils literal notranslate"><span class="pre">AnonymousUser</span></code></a> objects. Generally, you should prefer using <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User.is_authenticated" title="django.contrib.auth.models.User.is_authenticated"><code class="xref py py-attr docutils literal notranslate"><span class="pre">is_authenticated</span></code></a> to this attribute.</p> <div class="versionchanged"> <span class="title">Changed in Django 1.10:</span> <p>In older versions, this was a method. Backwards-compatibility support for using it as a method will be removed in Django 2.0.</p> </div> </dd></dl> <dl class="method"> <dt id="django.contrib.auth.models.AbstractBaseUser.set_password"> <code class="descname">set_password</code>(<em>raw_password</em>)<a class="headerlink" href="#django.contrib.auth.models.AbstractBaseUser.set_password" title="Permalink to this definition">¶</a></dt> <dd><p>Sets the user’s password to the given raw string, taking care of the password hashing. Doesn’t save the <a class="reference internal" href="#django.contrib.auth.models.AbstractBaseUser" title="django.contrib.auth.models.AbstractBaseUser"><code class="xref py py-class docutils literal notranslate"><span class="pre">AbstractBaseUser</span></code></a> object.</p> <p>When the raw_password is <code class="docutils literal notranslate"><span class="pre">None</span></code>, the password will be set to an unusable password, as if <a class="reference internal" href="#django.contrib.auth.models.AbstractBaseUser.set_unusable_password" title="django.contrib.auth.models.AbstractBaseUser.set_unusable_password"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_unusable_password()</span></code></a> were used.</p> </dd></dl> <dl class="method"> <dt id="django.contrib.auth.models.AbstractBaseUser.check_password"> <code class="descname">check_password</code>(<em>raw_password</em>)<a class="headerlink" href="#django.contrib.auth.models.AbstractBaseUser.check_password" title="Permalink to this definition">¶</a></dt> <dd><p>Returns <code class="docutils literal notranslate"><span class="pre">True</span></code> if the given raw string is the correct password for the user. (This takes care of the password hashing in making the comparison.)</p> </dd></dl> <dl class="method"> <dt id="django.contrib.auth.models.AbstractBaseUser.set_unusable_password"> <code class="descname">set_unusable_password</code>()<a class="headerlink" href="#django.contrib.auth.models.AbstractBaseUser.set_unusable_password" title="Permalink to this definition">¶</a></dt> <dd><p>Marks the user as having no password set. This isn’t the same as having a blank string for a password. <a class="reference internal" href="#django.contrib.auth.models.AbstractBaseUser.check_password" title="django.contrib.auth.models.AbstractBaseUser.check_password"><code class="xref py py-meth docutils literal notranslate"><span class="pre">check_password()</span></code></a> for this user will never return <code class="docutils literal notranslate"><span class="pre">True</span></code>. Doesn’t save the <a class="reference internal" href="#django.contrib.auth.models.AbstractBaseUser" title="django.contrib.auth.models.AbstractBaseUser"><code class="xref py py-class docutils literal notranslate"><span class="pre">AbstractBaseUser</span></code></a> object.</p> <p>You may need this if authentication for your application takes place against an existing external source such as an LDAP directory.</p> </dd></dl> <dl class="method"> <dt id="django.contrib.auth.models.AbstractBaseUser.has_usable_password"> <code class="descname">has_usable_password</code>()<a class="headerlink" href="#django.contrib.auth.models.AbstractBaseUser.has_usable_password" title="Permalink to this definition">¶</a></dt> <dd><p>Returns <code class="docutils literal notranslate"><span class="pre">False</span></code> if <a class="reference internal" href="#django.contrib.auth.models.AbstractBaseUser.set_unusable_password" title="django.contrib.auth.models.AbstractBaseUser.set_unusable_password"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_unusable_password()</span></code></a> has been called for this user.</p> </dd></dl> <dl class="method"> <dt id="django.contrib.auth.models.AbstractBaseUser.get_session_auth_hash"> <code class="descname">get_session_auth_hash</code>()<a class="headerlink" href="#django.contrib.auth.models.AbstractBaseUser.get_session_auth_hash" title="Permalink to this definition">¶</a></dt> <dd><p>Returns an HMAC of the password field. Used for <a class="reference internal" href="default.html#session-invalidation-on-password-change"><span class="std std-ref">Session invalidation on password change</span></a>.</p> </dd></dl> </dd></dl> <p><a class="reference internal" href="#django.contrib.auth.models.AbstractUser" title="django.contrib.auth.models.AbstractUser"><code class="xref py py-class docutils literal notranslate"><span class="pre">AbstractUser</span></code></a> subclasses <a class="reference internal" href="#django.contrib.auth.models.AbstractBaseUser" title="django.contrib.auth.models.AbstractBaseUser"><code class="xref py py-class docutils literal notranslate"><span class="pre">AbstractBaseUser</span></code></a>:</p> <dl class="class"> <dt id="django.contrib.auth.models.AbstractUser"> <em class="property">class </em><code class="descclassname">models.</code><code class="descname">AbstractUser</code><a class="headerlink" href="#django.contrib.auth.models.AbstractUser" title="Permalink to this definition">¶</a></dt> <dd><dl class="method"> <dt id="django.contrib.auth.models.AbstractUser.clean"> <code class="descname">clean</code>()<a class="headerlink" href="#django.contrib.auth.models.AbstractUser.clean" title="Permalink to this definition">¶</a></dt> <dd><div class="versionadded"> <span class="title">New in Django 1.11.</span> </div> <p>Normalizes the email by calling <a class="reference internal" href="#django.contrib.auth.models.BaseUserManager.normalize_email" title="django.contrib.auth.models.BaseUserManager.normalize_email"><code class="xref py py-meth docutils literal notranslate"><span class="pre">BaseUserManager.normalize_email()</span></code></a>. If you override this method, be sure to call <code class="docutils literal notranslate"><span class="pre">super()</span></code> to retain the normalization.</p> </dd></dl> </dd></dl> <p>You should also define a custom manager for your user model. If your user model defines <code class="docutils literal notranslate"><span class="pre">username</span></code>, <code class="docutils literal notranslate"><span class="pre">email</span></code>, <code class="docutils literal notranslate"><span class="pre">is_staff</span></code>, <code class="docutils literal notranslate"><span class="pre">is_active</span></code>, <code class="docutils literal notranslate"><span class="pre">is_superuser</span></code>, <code class="docutils literal notranslate"><span class="pre">last_login</span></code>, and <code class="docutils literal notranslate"><span class="pre">date_joined</span></code> fields the same as Django’s default user, you can just install Django’s <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.UserManager" title="django.contrib.auth.models.UserManager"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserManager</span></code></a>; however, if your user model defines different fields, you’ll need to define a custom manager that extends <a class="reference internal" href="#django.contrib.auth.models.BaseUserManager" title="django.contrib.auth.models.BaseUserManager"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseUserManager</span></code></a> providing two additional methods:</p> <dl class="class"> <dt id="django.contrib.auth.models.CustomUserManager"> <em class="property">class </em><code class="descclassname">models.</code><code class="descname">CustomUserManager</code><a class="headerlink" href="#django.contrib.auth.models.CustomUserManager" title="Permalink to this definition">¶</a></dt> <dd><dl class="method"> <dt id="django.contrib.auth.models.CustomUserManager.create_user"> <code class="descname">create_user</code>(<em>*username_field*</em>, <em>password=None</em>, <em>**other_fields</em>)<a class="headerlink" href="#django.contrib.auth.models.CustomUserManager.create_user" title="Permalink to this definition">¶</a></dt> <dd><p>The prototype of <code class="docutils literal notranslate"><span class="pre">create_user()</span></code> should accept the username field, plus all required fields as arguments. For example, if your user model uses <code class="docutils literal notranslate"><span class="pre">email</span></code> as the username field, and has <code class="docutils literal notranslate"><span class="pre">date_of_birth</span></code> as a required field, then <code class="docutils literal notranslate"><span class="pre">create_user</span></code> should be defined as:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">create_user</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">email</span><span class="p">,</span> <span class="n">date_of_birth</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span> <span class="c1"># create user here</span> <span class="o">...</span> </pre></div> </div> </dd></dl> <dl class="method"> <dt id="django.contrib.auth.models.CustomUserManager.create_superuser"> <code class="descname">create_superuser</code>(<em>*username_field*</em>, <em>password</em>, <em>**other_fields</em>)<a class="headerlink" href="#django.contrib.auth.models.CustomUserManager.create_superuser" title="Permalink to this definition">¶</a></dt> <dd><p>The prototype of <code class="docutils literal notranslate"><span class="pre">create_superuser()</span></code> should accept the username field, plus all required fields as arguments. For example, if your user model uses <code class="docutils literal notranslate"><span class="pre">email</span></code> as the username field, and has <code class="docutils literal notranslate"><span class="pre">date_of_birth</span></code> as a required field, then <code class="docutils literal notranslate"><span class="pre">create_superuser</span></code> should be defined as:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">create_superuser</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">email</span><span class="p">,</span> <span class="n">date_of_birth</span><span class="p">,</span> <span class="n">password</span><span class="p">):</span> <span class="c1"># create superuser here</span> <span class="o">...</span> </pre></div> </div> <p>Unlike <code class="docutils literal notranslate"><span class="pre">create_user()</span></code>, <code class="docutils literal notranslate"><span class="pre">create_superuser()</span></code> <em>must</em> require the caller to provide a password.</p> </dd></dl> </dd></dl> <p><a class="reference internal" href="#django.contrib.auth.models.BaseUserManager" title="django.contrib.auth.models.BaseUserManager"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseUserManager</span></code></a> provides the following utility methods:</p> <dl class="class"> <dt id="django.contrib.auth.models.BaseUserManager"> <em class="property">class </em><code class="descclassname">models.</code><code class="descname">BaseUserManager</code><a class="headerlink" href="#django.contrib.auth.models.BaseUserManager" title="Permalink to this definition">¶</a></dt> <dd><dl class="classmethod"> <dt id="django.contrib.auth.models.BaseUserManager.normalize_email"> <em class="property">classmethod </em><code class="descname">normalize_email</code>(<em>email</em>)<a class="headerlink" href="#django.contrib.auth.models.BaseUserManager.normalize_email" title="Permalink to this definition">¶</a></dt> <dd><p>Normalizes email addresses by lowercasing the domain portion of the email address.</p> </dd></dl> <dl class="method"> <dt id="django.contrib.auth.models.BaseUserManager.get_by_natural_key"> <code class="descname">get_by_natural_key</code>(<em>username</em>)<a class="headerlink" href="#django.contrib.auth.models.BaseUserManager.get_by_natural_key" title="Permalink to this definition">¶</a></dt> <dd><p>Retrieves a user instance using the contents of the field nominated by <code class="docutils literal notranslate"><span class="pre">USERNAME_FIELD</span></code>.</p> </dd></dl> <dl class="method"> <dt id="django.contrib.auth.models.BaseUserManager.make_random_password"> <code class="descname">make_random_password</code>(<em>length=10</em>, <em>allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789'</em>)<a class="headerlink" href="#django.contrib.auth.models.BaseUserManager.make_random_password" title="Permalink to this definition">¶</a></dt> <dd><p>Returns a random password with the given length and given string of allowed characters. Note that the default value of <code class="docutils literal notranslate"><span class="pre">allowed_chars</span></code> doesn’t contain letters that can cause user confusion, including:</p> <ul class="simple"> <li><code class="docutils literal notranslate"><span class="pre">i</span></code>, <code class="docutils literal notranslate"><span class="pre">l</span></code>, <code class="docutils literal notranslate"><span class="pre">I</span></code>, and <code class="docutils literal notranslate"><span class="pre">1</span></code> (lowercase letter i, lowercase letter L, uppercase letter i, and the number one)</li> <li><code class="docutils literal notranslate"><span class="pre">o</span></code>, <code class="docutils literal notranslate"><span class="pre">O</span></code>, and <code class="docutils literal notranslate"><span class="pre">0</span></code> (lowercase letter o, uppercase letter o, and zero)</li> </ul> </dd></dl> </dd></dl> </div> <div class="section" id="s-extending-django-s-default-user"> <span id="extending-django-s-default-user"></span><h3>Extending Django’s default <code class="docutils literal notranslate"><span class="pre">User</span></code><a class="headerlink" href="#extending-django-s-default-user" title="Permalink to this headline">¶</a></h3> <p>If you’re entirely happy with Django’s <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User" title="django.contrib.auth.models.User"><code class="xref py py-class docutils literal notranslate"><span class="pre">User</span></code></a> model and you just want to add some additional profile information, you could simply subclass <a class="reference internal" href="#django.contrib.auth.models.AbstractUser" title="django.contrib.auth.models.AbstractUser"><code class="xref py py-class docutils literal notranslate"><span class="pre">django.contrib.auth.models.AbstractUser</span></code></a> and add your custom profile fields, although we’d recommend a separate model as described in the “Model design considerations” note of <a class="reference internal" href="#specifying-custom-user-model"><span class="std std-ref">Specifying a custom user model</span></a>. <code class="docutils literal notranslate"><span class="pre">AbstractUser</span></code> provides the full implementation of the default <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User" title="django.contrib.auth.models.User"><code class="xref py py-class docutils literal notranslate"><span class="pre">User</span></code></a> as an <a class="reference internal" href="../db/models.html#abstract-base-classes"><span class="std std-ref">abstract model</span></a>.</p> </div> <div class="section" id="s-custom-users-and-the-built-in-auth-forms"> <span id="s-id2"></span><span id="custom-users-and-the-built-in-auth-forms"></span><span id="id2"></span><h3>Custom users and the built-in auth forms<a class="headerlink" href="#custom-users-and-the-built-in-auth-forms" title="Permalink to this headline">¶</a></h3> <p>Django’s built-in <a class="reference internal" href="default.html#built-in-auth-forms"><span class="std std-ref">forms</span></a> and <a class="reference internal" href="default.html#built-in-auth-views"><span class="std std-ref">views</span></a> make certain assumptions about the user model that they are working with.</p> <p>The following forms are compatible with any subclass of <a class="reference internal" href="#django.contrib.auth.models.AbstractBaseUser" title="django.contrib.auth.models.AbstractBaseUser"><code class="xref py py-class docutils literal notranslate"><span class="pre">AbstractBaseUser</span></code></a>:</p> <ul class="simple"> <li><a class="reference internal" href="default.html#django.contrib.auth.forms.AuthenticationForm" title="django.contrib.auth.forms.AuthenticationForm"><code class="xref py py-class docutils literal notranslate"><span class="pre">AuthenticationForm</span></code></a>: Uses the username field specified by <a class="reference internal" href="#django.contrib.auth.models.CustomUser.USERNAME_FIELD" title="django.contrib.auth.models.CustomUser.USERNAME_FIELD"><code class="xref py py-attr docutils literal notranslate"><span class="pre">USERNAME_FIELD</span></code></a>.</li> <li><a class="reference internal" href="default.html#django.contrib.auth.forms.SetPasswordForm" title="django.contrib.auth.forms.SetPasswordForm"><code class="xref py py-class docutils literal notranslate"><span class="pre">SetPasswordForm</span></code></a></li> <li><a class="reference internal" href="default.html#django.contrib.auth.forms.PasswordChangeForm" title="django.contrib.auth.forms.PasswordChangeForm"><code class="xref py py-class docutils literal notranslate"><span class="pre">PasswordChangeForm</span></code></a></li> <li><a class="reference internal" href="default.html#django.contrib.auth.forms.AdminPasswordChangeForm" title="django.contrib.auth.forms.AdminPasswordChangeForm"><code class="xref py py-class docutils literal notranslate"><span class="pre">AdminPasswordChangeForm</span></code></a></li> </ul> <p>The following forms make assumptions about the user model and can be used as-is if those assumptions are met:</p> <ul class="simple"> <li><a class="reference internal" href="default.html#django.contrib.auth.forms.PasswordResetForm" title="django.contrib.auth.forms.PasswordResetForm"><code class="xref py py-class docutils literal notranslate"><span class="pre">PasswordResetForm</span></code></a>: Assumes that the user model has a field that stores the user’s email address with the name returned by <a class="reference internal" href="#django.contrib.auth.models.AbstractBaseUser.get_email_field_name" title="django.contrib.auth.models.AbstractBaseUser.get_email_field_name"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_email_field_name()</span></code></a> (<code class="docutils literal notranslate"><span class="pre">email</span></code> by default) that can be used to identify the user and a boolean field named <code class="docutils literal notranslate"><span class="pre">is_active</span></code> to prevent password resets for inactive users.</li> </ul> <p>Finally, the following forms are tied to <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User" title="django.contrib.auth.models.User"><code class="xref py py-class docutils literal notranslate"><span class="pre">User</span></code></a> and need to be rewritten or extended to work with a custom user model:</p> <ul class="simple"> <li><a class="reference internal" href="default.html#django.contrib.auth.forms.UserCreationForm" title="django.contrib.auth.forms.UserCreationForm"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserCreationForm</span></code></a></li> <li><a class="reference internal" href="default.html#django.contrib.auth.forms.UserChangeForm" title="django.contrib.auth.forms.UserChangeForm"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserChangeForm</span></code></a></li> </ul> <p>If your custom user model is a simple subclass of <code class="docutils literal notranslate"><span class="pre">AbstractUser</span></code>, then you can extend these forms in this manner:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.contrib.auth.forms</span> <span class="k">import</span> <span class="n">UserCreationForm</span> <span class="kn">from</span> <span class="nn">myapp.models</span> <span class="k">import</span> <span class="n">CustomUser</span> <span class="k">class</span> <span class="nc">CustomUserCreationForm</span><span class="p">(</span><span class="n">UserCreationForm</span><span class="p">):</span> <span class="k">class</span> <span class="nc">Meta</span><span class="p">(</span><span class="n">UserCreationForm</span><span class="o">.</span><span class="n">Meta</span><span class="p">):</span> <span class="n">model</span> <span class="o">=</span> <span class="n">CustomUser</span> <span class="n">fields</span> <span class="o">=</span> <span class="n">UserCreationForm</span><span class="o">.</span><span class="n">Meta</span><span class="o">.</span><span class="n">fields</span> <span class="o">+</span> <span class="p">(</span><span class="s1">'custom_field'</span><span class="p">,)</span> </pre></div> </div> </div> <div class="section" id="s-custom-users-and-django-contrib-admin"> <span id="custom-users-and-django-contrib-admin"></span><h3>Custom users and <a class="reference internal" href="../../ref/contrib/admin/index.html#module-django.contrib.admin" title="django.contrib.admin: Django's admin site."><code class="xref py py-mod docutils literal notranslate"><span class="pre">django.contrib.admin</span></code></a><a class="headerlink" href="#custom-users-and-django-contrib-admin" title="Permalink to this headline">¶</a></h3> <p>If you want your custom user model to also work with the admin, your user model must define some additional attributes and methods. These methods allow the admin to control access of the user to admin content:</p> <dl class="class"> <dt> <em class="property">class </em><code class="descclassname">models.</code><code class="descname">CustomUser</code></dt> <dd></dd></dl> <dl class="attribute"> <dt id="django.contrib.auth.is_staff"> <code class="descname">is_staff</code><a class="headerlink" href="#django.contrib.auth.is_staff" title="Permalink to this definition">¶</a></dt> <dd><p>Returns <code class="docutils literal notranslate"><span class="pre">True</span></code> if the user is allowed to have access to the admin site.</p> </dd></dl> <dl class="attribute"> <dt id="django.contrib.auth.is_active"> <code class="descname">is_active</code><a class="headerlink" href="#django.contrib.auth.is_active" title="Permalink to this definition">¶</a></dt> <dd><p>Returns <code class="docutils literal notranslate"><span class="pre">True</span></code> if the user account is currently active.</p> </dd></dl> <dl class="method"> <dt> <code class="descname">has_perm(perm, obj=None):</code></dt> <dd><p>Returns <code class="docutils literal notranslate"><span class="pre">True</span></code> if the user has the named permission. If <code class="docutils literal notranslate"><span class="pre">obj</span></code> is provided, the permission needs to be checked against a specific object instance.</p> </dd></dl> <dl class="method"> <dt> <code class="descname">has_module_perms(app_label):</code></dt> <dd><p>Returns <code class="docutils literal notranslate"><span class="pre">True</span></code> if the user has permission to access models in the given app.</p> </dd></dl> <p>You will also need to register your custom user model with the admin. If your custom user model extends <code class="docutils literal notranslate"><span class="pre">django.contrib.auth.models.AbstractUser</span></code>, you can use Django’s existing <code class="docutils literal notranslate"><span class="pre">django.contrib.auth.admin.UserAdmin</span></code> class. However, if your user model extends <a class="reference internal" href="#django.contrib.auth.models.AbstractBaseUser" title="django.contrib.auth.models.AbstractBaseUser"><code class="xref py py-class docutils literal notranslate"><span class="pre">AbstractBaseUser</span></code></a>, you’ll need to define a custom <code class="docutils literal notranslate"><span class="pre">ModelAdmin</span></code> class. It may be possible to subclass the default <code class="docutils literal notranslate"><span class="pre">django.contrib.auth.admin.UserAdmin</span></code>; however, you’ll need to override any of the definitions that refer to fields on <code class="docutils literal notranslate"><span class="pre">django.contrib.auth.models.AbstractUser</span></code> that aren’t on your custom user class.</p> </div> <div class="section" id="s-custom-users-and-permissions"> <span id="custom-users-and-permissions"></span><h3>Custom users and permissions<a class="headerlink" href="#custom-users-and-permissions" title="Permalink to this headline">¶</a></h3> <p>To make it easy to include Django’s permission framework into your own user class, Django provides <a class="reference internal" href="#django.contrib.auth.models.PermissionsMixin" title="django.contrib.auth.models.PermissionsMixin"><code class="xref py py-class docutils literal notranslate"><span class="pre">PermissionsMixin</span></code></a>. This is an abstract model you can include in the class hierarchy for your user model, giving you all the methods and database fields necessary to support Django’s permission model.</p> <p><a class="reference internal" href="#django.contrib.auth.models.PermissionsMixin" title="django.contrib.auth.models.PermissionsMixin"><code class="xref py py-class docutils literal notranslate"><span class="pre">PermissionsMixin</span></code></a> provides the following methods and attributes:</p> <dl class="class"> <dt id="django.contrib.auth.models.PermissionsMixin"> <em class="property">class </em><code class="descclassname">models.</code><code class="descname">PermissionsMixin</code><a class="headerlink" href="#django.contrib.auth.models.PermissionsMixin" title="Permalink to this definition">¶</a></dt> <dd><dl class="attribute"> <dt id="django.contrib.auth.models.PermissionsMixin.is_superuser"> <code class="descname">is_superuser</code><a class="headerlink" href="#django.contrib.auth.models.PermissionsMixin.is_superuser" title="Permalink to this definition">¶</a></dt> <dd><p>Boolean. Designates that this user has all permissions without explicitly assigning them.</p> </dd></dl> <dl class="method"> <dt id="django.contrib.auth.models.PermissionsMixin.get_group_permissions"> <code class="descname">get_group_permissions</code>(<em>obj=None</em>)<a class="headerlink" href="#django.contrib.auth.models.PermissionsMixin.get_group_permissions" title="Permalink to this definition">¶</a></dt> <dd><p>Returns a set of permission strings that the user has, through their groups.</p> <p>If <code class="docutils literal notranslate"><span class="pre">obj</span></code> is passed in, only returns the group permissions for this specific object.</p> </dd></dl> <dl class="method"> <dt id="django.contrib.auth.models.PermissionsMixin.get_all_permissions"> <code class="descname">get_all_permissions</code>(<em>obj=None</em>)<a class="headerlink" href="#django.contrib.auth.models.PermissionsMixin.get_all_permissions" title="Permalink to this definition">¶</a></dt> <dd><p>Returns a set of permission strings that the user has, both through group and user permissions.</p> <p>If <code class="docutils literal notranslate"><span class="pre">obj</span></code> is passed in, only returns the permissions for this specific object.</p> </dd></dl> <dl class="method"> <dt id="django.contrib.auth.models.PermissionsMixin.has_perm"> <code class="descname">has_perm</code>(<em>perm</em>, <em>obj=None</em>)<a class="headerlink" href="#django.contrib.auth.models.PermissionsMixin.has_perm" title="Permalink to this definition">¶</a></dt> <dd><p>Returns <code class="docutils literal notranslate"><span class="pre">True</span></code> if the user has the specified permission, where <code class="docutils literal notranslate"><span class="pre">perm</span></code> is in the format <code class="docutils literal notranslate"><span class="pre">"<app</span> <span class="pre">label>.<permission</span> <span class="pre">codename>"</span></code> (see <a class="reference internal" href="default.html#topic-authorization"><span class="std std-ref">permissions</span></a>). If the user is inactive, this method will always return <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p> <p>If <code class="docutils literal notranslate"><span class="pre">obj</span></code> is passed in, this method won’t check for a permission for the model, but for this specific object.</p> </dd></dl> <dl class="method"> <dt id="django.contrib.auth.models.PermissionsMixin.has_perms"> <code class="descname">has_perms</code>(<em>perm_list</em>, <em>obj=None</em>)<a class="headerlink" href="#django.contrib.auth.models.PermissionsMixin.has_perms" title="Permalink to this definition">¶</a></dt> <dd><p>Returns <code class="docutils literal notranslate"><span class="pre">True</span></code> if the user has each of the specified permissions, where each perm is in the format <code class="docutils literal notranslate"><span class="pre">"<app</span> <span class="pre">label>.<permission</span> <span class="pre">codename>"</span></code>. If the user is inactive, this method will always return <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p> <p>If <code class="docutils literal notranslate"><span class="pre">obj</span></code> is passed in, this method won’t check for permissions for the model, but for the specific object.</p> </dd></dl> <dl class="method"> <dt id="django.contrib.auth.models.PermissionsMixin.has_module_perms"> <code class="descname">has_module_perms</code>(<em>package_name</em>)<a class="headerlink" href="#django.contrib.auth.models.PermissionsMixin.has_module_perms" title="Permalink to this definition">¶</a></dt> <dd><p>Returns <code class="docutils literal notranslate"><span class="pre">True</span></code> if the user has any permissions in the given package (the Django app label). If the user is inactive, this method will always return <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p> </dd></dl> </dd></dl> <div class="admonition-permissionsmixin-and-modelbackend admonition"> <p class="first admonition-title"><code class="docutils literal notranslate"><span class="pre">PermissionsMixin</span></code> and <code class="docutils literal notranslate"><span class="pre">ModelBackend</span></code></p> <p class="last">If you don’t include the <a class="reference internal" href="#django.contrib.auth.models.PermissionsMixin" title="django.contrib.auth.models.PermissionsMixin"><code class="xref py py-class docutils literal notranslate"><span class="pre">PermissionsMixin</span></code></a>, you must ensure you don’t invoke the permissions methods on <code class="docutils literal notranslate"><span class="pre">ModelBackend</span></code>. <code class="docutils literal notranslate"><span class="pre">ModelBackend</span></code> assumes that certain fields are available on your user model. If your user model doesn’t provide those fields, you’ll receive database errors when you check permissions.</p> </div> </div> <div class="section" id="s-custom-users-and-proxy-models"> <span id="custom-users-and-proxy-models"></span><h3>Custom users and proxy models<a class="headerlink" href="#custom-users-and-proxy-models" title="Permalink to this headline">¶</a></h3> <p>One limitation of custom user models is that installing a custom user model will break any proxy model extending <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User" title="django.contrib.auth.models.User"><code class="xref py py-class docutils literal notranslate"><span class="pre">User</span></code></a>. Proxy models must be based on a concrete base class; by defining a custom user model, you remove the ability of Django to reliably identify the base class.</p> <p>If your project uses proxy models, you must either modify the proxy to extend the user model that’s in use in your project, or merge your proxy’s behavior into your <a class="reference internal" href="../../ref/contrib/auth.html#django.contrib.auth.models.User" title="django.contrib.auth.models.User"><code class="xref py py-class docutils literal notranslate"><span class="pre">User</span></code></a> subclass.</p> </div> <div class="section" id="s-a-full-example"> <span id="a-full-example"></span><h3>A full example<a class="headerlink" href="#a-full-example" title="Permalink to this headline">¶</a></h3> <p>Here is an example of an admin-compliant custom user app. This user model uses an email address as the username, and has a required date of birth; it provides no permission checking, beyond a simple <code class="docutils literal notranslate"><span class="pre">admin</span></code> flag on the user account. This model would be compatible with all the built-in auth forms and views, except for the user creation forms. This example illustrates how most of the components work together, but is not intended to be copied directly into projects for production use.</p> <p>This code would all live in a <code class="docutils literal notranslate"><span class="pre">models.py</span></code> file for a custom authentication app:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.db</span> <span class="k">import</span> <span class="n">models</span> <span class="kn">from</span> <span class="nn">django.contrib.auth.models</span> <span class="k">import</span> <span class="p">(</span> <span class="n">BaseUserManager</span><span class="p">,</span> <span class="n">AbstractBaseUser</span> <span class="p">)</span> <span class="k">class</span> <span class="nc">MyUserManager</span><span class="p">(</span><span class="n">BaseUserManager</span><span class="p">):</span> <span class="k">def</span> <span class="nf">create_user</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">email</span><span class="p">,</span> <span class="n">date_of_birth</span><span class="p">,</span> <span class="n">password</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span> <span class="sd">"""</span> <span class="sd"> Creates and saves a User with the given email, date of</span> <span class="sd"> birth and password.</span> <span class="sd"> """</span> <span class="k">if</span> <span class="ow">not</span> <span class="n">email</span><span class="p">:</span> <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="s1">'Users must have an email address'</span><span class="p">)</span> <span class="n">user</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="p">(</span> <span class="n">email</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">normalize_email</span><span class="p">(</span><span class="n">email</span><span class="p">),</span> <span class="n">date_of_birth</span><span class="o">=</span><span class="n">date_of_birth</span><span class="p">,</span> <span class="p">)</span> <span class="n">user</span><span class="o">.</span><span class="n">set_password</span><span class="p">(</span><span class="n">password</span><span class="p">)</span> <span class="n">user</span><span class="o">.</span><span class="n">save</span><span class="p">(</span><span class="n">using</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">_db</span><span class="p">)</span> <span class="k">return</span> <span class="n">user</span> <span class="k">def</span> <span class="nf">create_superuser</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">email</span><span class="p">,</span> <span class="n">date_of_birth</span><span class="p">,</span> <span class="n">password</span><span class="p">):</span> <span class="sd">"""</span> <span class="sd"> Creates and saves a superuser with the given email, date of</span> <span class="sd"> birth and password.</span> <span class="sd"> """</span> <span class="n">user</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">create_user</span><span class="p">(</span> <span class="n">email</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="n">date_of_birth</span><span class="o">=</span><span class="n">date_of_birth</span><span class="p">,</span> <span class="p">)</span> <span class="n">user</span><span class="o">.</span><span class="n">is_admin</span> <span class="o">=</span> <span class="kc">True</span> <span class="n">user</span><span class="o">.</span><span class="n">save</span><span class="p">(</span><span class="n">using</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">_db</span><span class="p">)</span> <span class="k">return</span> <span class="n">user</span> <span class="k">class</span> <span class="nc">MyUser</span><span class="p">(</span><span class="n">AbstractBaseUser</span><span class="p">):</span> <span class="n">email</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">EmailField</span><span class="p">(</span> <span class="n">verbose_name</span><span class="o">=</span><span class="s1">'email address'</span><span class="p">,</span> <span class="n">max_length</span><span class="o">=</span><span class="mi">255</span><span class="p">,</span> <span class="n">unique</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span> <span class="p">)</span> <span class="n">date_of_birth</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">DateField</span><span class="p">()</span> <span class="n">is_active</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">BooleanField</span><span class="p">(</span><span class="n">default</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span> <span class="n">is_admin</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">BooleanField</span><span class="p">(</span><span class="n">default</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span> <span class="n">objects</span> <span class="o">=</span> <span class="n">MyUserManager</span><span class="p">()</span> <span class="n">USERNAME_FIELD</span> <span class="o">=</span> <span class="s1">'email'</span> <span class="n">REQUIRED_FIELDS</span> <span class="o">=</span> <span class="p">[</span><span class="s1">'date_of_birth'</span><span class="p">]</span> <span class="k">def</span> <span class="nf">get_full_name</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="c1"># The user is identified by their email address</span> <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">email</span> <span class="k">def</span> <span class="nf">get_short_name</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="c1"># The user is identified by their email address</span> <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">email</span> <span class="k">def</span> <span class="nf">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="c1"># __unicode__ on Python 2</span> <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">email</span> <span class="k">def</span> <span class="nf">has_perm</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">perm</span><span class="p">,</span> <span class="n">obj</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span> <span class="s2">"Does the user have a specific permission?"</span> <span class="c1"># Simplest possible answer: Yes, always</span> <span class="k">return</span> <span class="kc">True</span> <span class="k">def</span> <span class="nf">has_module_perms</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">app_label</span><span class="p">):</span> <span class="s2">"Does the user have permissions to view the app `app_label`?"</span> <span class="c1"># Simplest possible answer: Yes, always</span> <span class="k">return</span> <span class="kc">True</span> <span class="nd">@property</span> <span class="k">def</span> <span class="nf">is_staff</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="s2">"Is the user a member of staff?"</span> <span class="c1"># Simplest possible answer: All admins are staff</span> <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">is_admin</span> </pre></div> </div> <p>Then, to register this custom user model with Django’s admin, the following code would be required in the app’s <code class="docutils literal notranslate"><span class="pre">admin.py</span></code> file:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django</span> <span class="k">import</span> <span class="n">forms</span> <span class="kn">from</span> <span class="nn">django.contrib</span> <span class="k">import</span> <span class="n">admin</span> <span class="kn">from</span> <span class="nn">django.contrib.auth.models</span> <span class="k">import</span> <span class="n">Group</span> <span class="kn">from</span> <span class="nn">django.contrib.auth.admin</span> <span class="k">import</span> <span class="n">UserAdmin</span> <span class="k">as</span> <span class="n">BaseUserAdmin</span> <span class="kn">from</span> <span class="nn">django.contrib.auth.forms</span> <span class="k">import</span> <span class="n">ReadOnlyPasswordHashField</span> <span class="kn">from</span> <span class="nn">customauth.models</span> <span class="k">import</span> <span class="n">MyUser</span> <span class="k">class</span> <span class="nc">UserCreationForm</span><span class="p">(</span><span class="n">forms</span><span class="o">.</span><span class="n">ModelForm</span><span class="p">):</span> <span class="sd">"""A form for creating new users. Includes all the required</span> <span class="sd"> fields, plus a repeated password."""</span> <span class="n">password1</span> <span class="o">=</span> <span class="n">forms</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">label</span><span class="o">=</span><span class="s1">'Password'</span><span class="p">,</span> <span class="n">widget</span><span class="o">=</span><span class="n">forms</span><span class="o">.</span><span class="n">PasswordInput</span><span class="p">)</span> <span class="n">password2</span> <span class="o">=</span> <span class="n">forms</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">label</span><span class="o">=</span><span class="s1">'Password confirmation'</span><span class="p">,</span> <span class="n">widget</span><span class="o">=</span><span class="n">forms</span><span class="o">.</span><span class="n">PasswordInput</span><span class="p">)</span> <span class="k">class</span> <span class="nc">Meta</span><span class="p">:</span> <span class="n">model</span> <span class="o">=</span> <span class="n">MyUser</span> <span class="n">fields</span> <span class="o">=</span> <span class="p">(</span><span class="s1">'email'</span><span class="p">,</span> <span class="s1">'date_of_birth'</span><span class="p">)</span> <span class="k">def</span> <span class="nf">clean_password2</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="c1"># Check that the two password entries match</span> <span class="n">password1</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">cleaned_data</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s2">"password1"</span><span class="p">)</span> <span class="n">password2</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">cleaned_data</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s2">"password2"</span><span class="p">)</span> <span class="k">if</span> <span class="n">password1</span> <span class="ow">and</span> <span class="n">password2</span> <span class="ow">and</span> <span class="n">password1</span> <span class="o">!=</span> <span class="n">password2</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="s2">"Passwords don't match"</span><span class="p">)</span> <span class="k">return</span> <span class="n">password2</span> <span class="k">def</span> <span class="nf">save</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">commit</span><span class="o">=</span><span class="kc">True</span><span class="p">):</span> <span class="c1"># Save the provided password in hashed format</span> <span class="n">user</span> <span class="o">=</span> <span class="nb">super</span><span class="p">(</span><span class="n">UserCreationForm</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">save</span><span class="p">(</span><span class="n">commit</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span> <span class="n">user</span><span class="o">.</span><span class="n">set_password</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">cleaned_data</span><span class="p">[</span><span class="s2">"password1"</span><span class="p">])</span> <span class="k">if</span> <span class="n">commit</span><span class="p">:</span> <span class="n">user</span><span class="o">.</span><span class="n">save</span><span class="p">()</span> <span class="k">return</span> <span class="n">user</span> <span class="k">class</span> <span class="nc">UserChangeForm</span><span class="p">(</span><span class="n">forms</span><span class="o">.</span><span class="n">ModelForm</span><span class="p">):</span> <span class="sd">"""A form for updating users. Includes all the fields on</span> <span class="sd"> the user, but replaces the password field with admin's</span> <span class="sd"> password hash display field.</span> <span class="sd"> """</span> <span class="n">password</span> <span class="o">=</span> <span class="n">ReadOnlyPasswordHashField</span><span class="p">()</span> <span class="k">class</span> <span class="nc">Meta</span><span class="p">:</span> <span class="n">model</span> <span class="o">=</span> <span class="n">MyUser</span> <span class="n">fields</span> <span class="o">=</span> <span class="p">(</span><span class="s1">'email'</span><span class="p">,</span> <span class="s1">'password'</span><span class="p">,</span> <span class="s1">'date_of_birth'</span><span class="p">,</span> <span class="s1">'is_active'</span><span class="p">,</span> <span class="s1">'is_admin'</span><span class="p">)</span> <span class="k">def</span> <span class="nf">clean_password</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="c1"># Regardless of what the user provides, return the initial value.</span> <span class="c1"># This is done here, rather than on the field, because the</span> <span class="c1"># field does not have access to the initial value</span> <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">initial</span><span class="p">[</span><span class="s2">"password"</span><span class="p">]</span> <span class="k">class</span> <span class="nc">UserAdmin</span><span class="p">(</span><span class="n">BaseUserAdmin</span><span class="p">):</span> <span class="c1"># The forms to add and change user instances</span> <span class="n">form</span> <span class="o">=</span> <span class="n">UserChangeForm</span> <span class="n">add_form</span> <span class="o">=</span> <span class="n">UserCreationForm</span> <span class="c1"># The fields to be used in displaying the User model.</span> <span class="c1"># These override the definitions on the base UserAdmin</span> <span class="c1"># that reference specific fields on auth.User.</span> <span class="n">list_display</span> <span class="o">=</span> <span class="p">(</span><span class="s1">'email'</span><span class="p">,</span> <span class="s1">'date_of_birth'</span><span class="p">,</span> <span class="s1">'is_admin'</span><span class="p">)</span> <span class="n">list_filter</span> <span class="o">=</span> <span class="p">(</span><span class="s1">'is_admin'</span><span class="p">,)</span> <span class="n">fieldsets</span> <span class="o">=</span> <span class="p">(</span> <span class="p">(</span><span class="kc">None</span><span class="p">,</span> <span class="p">{</span><span class="s1">'fields'</span><span class="p">:</span> <span class="p">(</span><span class="s1">'email'</span><span class="p">,</span> <span class="s1">'password'</span><span class="p">)}),</span> <span class="p">(</span><span class="s1">'Personal info'</span><span class="p">,</span> <span class="p">{</span><span class="s1">'fields'</span><span class="p">:</span> <span class="p">(</span><span class="s1">'date_of_birth'</span><span class="p">,)}),</span> <span class="p">(</span><span class="s1">'Permissions'</span><span class="p">,</span> <span class="p">{</span><span class="s1">'fields'</span><span class="p">:</span> <span class="p">(</span><span class="s1">'is_admin'</span><span class="p">,)}),</span> <span class="p">)</span> <span class="c1"># add_fieldsets is not a standard ModelAdmin attribute. UserAdmin</span> <span class="c1"># overrides get_fieldsets to use this attribute when creating a user.</span> <span class="n">add_fieldsets</span> <span class="o">=</span> <span class="p">(</span> <span class="p">(</span><span class="kc">None</span><span class="p">,</span> <span class="p">{</span> <span class="s1">'classes'</span><span class="p">:</span> <span class="p">(</span><span class="s1">'wide'</span><span class="p">,),</span> <span class="s1">'fields'</span><span class="p">:</span> <span class="p">(</span><span class="s1">'email'</span><span class="p">,</span> <span class="s1">'date_of_birth'</span><span class="p">,</span> <span class="s1">'password1'</span><span class="p">,</span> <span class="s1">'password2'</span><span class="p">)}</span> <span class="p">),</span> <span class="p">)</span> <span class="n">search_fields</span> <span class="o">=</span> <span class="p">(</span><span class="s1">'email'</span><span class="p">,)</span> <span class="n">ordering</span> <span class="o">=</span> <span class="p">(</span><span class="s1">'email'</span><span class="p">,)</span> <span class="n">filter_horizontal</span> <span class="o">=</span> <span class="p">()</span> <span class="c1"># Now register the new UserAdmin...</span> <span class="n">admin</span><span class="o">.</span><span class="n">site</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="n">MyUser</span><span class="p">,</span> <span class="n">UserAdmin</span><span class="p">)</span> <span class="c1"># ... and, since we're not using Django's built-in permissions,</span> <span class="c1"># unregister the Group model from admin.</span> <span class="n">admin</span><span class="o">.</span><span class="n">site</span><span class="o">.</span><span class="n">unregister</span><span class="p">(</span><span class="n">Group</span><span class="p">)</span> </pre></div> </div> <p>Finally, specify the custom model as the default user model for your project using the <a class="reference internal" href="../../ref/settings.html#std:setting-AUTH_USER_MODEL"><code class="xref std std-setting docutils literal notranslate"><span class="pre">AUTH_USER_MODEL</span></code></a> setting in your <code class="docutils literal notranslate"><span class="pre">settings.py</span></code>:</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">AUTH_USER_MODEL</span> <span class="o">=</span> <span class="s1">'customauth.MyUser'</span> </pre></div> </div> </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="#">Customizing authentication in Django</a><ul> <li><a class="reference internal" href="#other-authentication-sources">Other authentication sources</a><ul> <li><a class="reference internal" href="#specifying-authentication-backends">Specifying authentication backends</a></li> <li><a class="reference internal" href="#writing-an-authentication-backend">Writing an authentication backend</a></li> <li><a class="reference internal" href="#handling-authorization-in-custom-backends">Handling authorization in custom backends</a><ul> <li><a class="reference internal" href="#authorization-for-anonymous-users">Authorization for anonymous users</a></li> <li><a class="reference internal" href="#authorization-for-inactive-users">Authorization for inactive users</a></li> <li><a class="reference internal" href="#handling-object-permissions">Handling object permissions</a></li> </ul> </li> </ul> </li> <li><a class="reference internal" href="#custom-permissions">Custom permissions</a></li> <li><a class="reference internal" href="#extending-the-existing-user-model">Extending the existing <code class="docutils literal notranslate"><span class="pre">User</span></code> model</a></li> <li><a class="reference internal" href="#substituting-a-custom-user-model">Substituting a custom <code class="docutils literal notranslate"><span class="pre">User</span></code> model</a><ul> <li><a class="reference internal" href="#using-a-custom-user-model-when-starting-a-project">Using a custom user model when starting a project</a></li> <li><a class="reference internal" href="#changing-to-a-custom-user-model-mid-project">Changing to a custom user model mid-project</a></li> <li><a class="reference internal" href="#reusable-apps-and-auth-user-model">Reusable apps and <code class="docutils literal notranslate"><span class="pre">AUTH_USER_MODEL</span></code></a></li> <li><a class="reference internal" href="#referencing-the-user-model">Referencing the <code class="docutils literal notranslate"><span class="pre">User</span></code> model</a></li> <li><a class="reference internal" href="#specifying-a-custom-user-model">Specifying a custom user model</a></li> <li><a class="reference internal" href="#extending-django-s-default-user">Extending Django’s default <code class="docutils literal notranslate"><span class="pre">User</span></code></a></li> <li><a class="reference internal" href="#custom-users-and-the-built-in-auth-forms">Custom users and the built-in auth forms</a></li> <li><a class="reference internal" href="#custom-users-and-django-contrib-admin">Custom users and <code class="docutils literal notranslate"><span class="pre">django.contrib.admin</span></code></a></li> <li><a class="reference internal" href="#custom-users-and-permissions">Custom users and permissions</a></li> <li><a class="reference internal" href="#custom-users-and-proxy-models">Custom users and proxy models</a></li> <li><a class="reference internal" href="#a-full-example">A full example</a></li> </ul> </li> </ul> </li> </ul> <h4>Previous topic</h4> <p class="topless"><a href="passwords.html" title="previous chapter">Password management in Django</a></p> <h4>Next topic</h4> <p class="topless"><a href="../cache.html" title="next chapter">Django’s cache framework</a></p> <div role="note" aria-label="source link"> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="../../_sources/topics/auth/customizing.txt" rel="nofollow">Show Source</a></li> </ul> </div> <div id="searchbox" style="display: none" role="search"> <h3>Quick search</h3> <div class="searchformwrapper"> <form class="search" action="../../search.html" method="get"> <input type="text" name="q" /> <input type="submit" value="Go" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <h3>Last update:</h3> <p class="topless">Feb 11, 2019</p> </div> </div> <div id="ft"> <div class="nav"> « <a href="passwords.html" title="Password management in Django">previous</a> | <a href="../index.html" title="Using Django" accesskey="U">up</a> | <a href="../cache.html" title="Django’s cache framework">next</a> »</div> </div> </div> <div class="clearer"></div> </div> </body> </html>