1. ====================================
    
  2. Customizing authentication in Django
    
  3. ====================================
    
  4. 
    
  5. The authentication that comes with Django is good enough for most common cases,
    
  6. but you may have needs not met by the out-of-the-box defaults. Customizing
    
  7. authentication in your projects requires understanding what points of the
    
  8. provided system are extensible or replaceable. This document provides details
    
  9. about how the auth system can be customized.
    
  10. 
    
  11. :ref:`Authentication backends <authentication-backends>` provide an extensible
    
  12. system for when a username and password stored with the user model need to be
    
  13. authenticated against a different service than Django's default.
    
  14. 
    
  15. You can give your models :ref:`custom permissions <custom-permissions>` that
    
  16. can be checked through Django's authorization system.
    
  17. 
    
  18. You can :ref:`extend <extending-user>` the default ``User`` model, or
    
  19. :ref:`substitute <auth-custom-user>` a completely customized model.
    
  20. 
    
  21. .. _authentication-backends:
    
  22. 
    
  23. Other authentication sources
    
  24. ============================
    
  25. 
    
  26. There may be times you have the need to hook into another authentication source
    
  27. -- that is, another source of usernames and passwords or authentication
    
  28. methods.
    
  29. 
    
  30. For example, your company may already have an LDAP setup that stores a username
    
  31. and password for every employee. It'd be a hassle for both the network
    
  32. administrator and the users themselves if users had separate accounts in LDAP
    
  33. and the Django-based applications.
    
  34. 
    
  35. So, to handle situations like this, the Django authentication system lets you
    
  36. plug in other authentication sources. You can override Django's default
    
  37. database-based scheme, or you can use the default system in tandem with other
    
  38. systems.
    
  39. 
    
  40. See the :ref:`authentication backend reference
    
  41. <authentication-backends-reference>` for information on the authentication
    
  42. backends included with Django.
    
  43. 
    
  44. Specifying authentication backends
    
  45. ----------------------------------
    
  46. 
    
  47. Behind the scenes, Django maintains a list of "authentication backends" that it
    
  48. checks for authentication. When somebody calls
    
  49. :func:`django.contrib.auth.authenticate()` -- as described in :ref:`How to log
    
  50. a user in <how-to-log-a-user-in>` -- Django tries authenticating across
    
  51. all of its authentication backends. If the first authentication method fails,
    
  52. Django tries the second one, and so on, until all backends have been attempted.
    
  53. 
    
  54. The list of authentication backends to use is specified in the
    
  55. :setting:`AUTHENTICATION_BACKENDS` setting. This should be a list of Python
    
  56. path names that point to Python classes that know how to authenticate. These
    
  57. classes can be anywhere on your Python path.
    
  58. 
    
  59. By default, :setting:`AUTHENTICATION_BACKENDS` is set to::
    
  60. 
    
  61.     ['django.contrib.auth.backends.ModelBackend']
    
  62. 
    
  63. That's the basic authentication backend that checks the Django users database
    
  64. and queries the built-in permissions. It does not provide protection against
    
  65. brute force attacks via any rate limiting mechanism. You may either implement
    
  66. your own rate limiting mechanism in a custom auth backend, or use the
    
  67. mechanisms provided by most web servers.
    
  68. 
    
  69. The order of :setting:`AUTHENTICATION_BACKENDS` matters, so if the same
    
  70. username and password is valid in multiple backends, Django will stop
    
  71. processing at the first positive match.
    
  72. 
    
  73. If a backend raises a :class:`~django.core.exceptions.PermissionDenied`
    
  74. exception, authentication will immediately fail. Django won't check the
    
  75. backends that follow.
    
  76. 
    
  77. .. note::
    
  78. 
    
  79.     Once a user has authenticated, Django stores which backend was used to
    
  80.     authenticate the user in the user's session, and reuses the same backend
    
  81.     for the duration of that session whenever access to the currently
    
  82.     authenticated user is needed. This effectively means that authentication
    
  83.     sources are cached on a per-session basis, so if you change
    
  84.     :setting:`AUTHENTICATION_BACKENDS`, you'll need to clear out session data if
    
  85.     you need to force users to re-authenticate using different methods. A
    
  86.     simple way to do that is to execute ``Session.objects.all().delete()``.
    
  87. 
    
  88. Writing an authentication backend
    
  89. ---------------------------------
    
  90. 
    
  91. An authentication backend is a class that implements two required methods:
    
  92. ``get_user(user_id)`` and ``authenticate(request, **credentials)``, as well as
    
  93. a set of optional permission related :ref:`authorization methods
    
  94. <authorization_methods>`.
    
  95. 
    
  96. The ``get_user`` method takes a ``user_id`` -- which could be a username,
    
  97. database ID or whatever, but has to be the primary key of your user object --
    
  98. and returns a user object or ``None``.
    
  99. 
    
  100. The ``authenticate`` method takes a ``request`` argument and credentials as
    
  101. keyword arguments. Most of the time, it'll look like this::
    
  102. 
    
  103.     from django.contrib.auth.backends import BaseBackend
    
  104. 
    
  105.     class MyBackend(BaseBackend):
    
  106.         def authenticate(self, request, username=None, password=None):
    
  107.             # Check the username/password and return a user.
    
  108.             ...
    
  109. 
    
  110. But it could also authenticate a token, like so::
    
  111. 
    
  112.     from django.contrib.auth.backends import BaseBackend
    
  113. 
    
  114.     class MyBackend(BaseBackend):
    
  115.         def authenticate(self, request, token=None):
    
  116.             # Check the token and return a user.
    
  117.             ...
    
  118. 
    
  119. Either way, ``authenticate()`` should check the credentials it gets and return
    
  120. a user object that matches those credentials if the credentials are valid. If
    
  121. they're not valid, it should return ``None``.
    
  122. 
    
  123. ``request`` is an :class:`~django.http.HttpRequest` and may be ``None`` if it
    
  124. wasn't provided to :func:`~django.contrib.auth.authenticate` (which passes it
    
  125. on to the backend).
    
  126. 
    
  127. The Django admin is tightly coupled to the Django :ref:`User object
    
  128. <user-objects>`. The best way to deal with this is to create a Django ``User``
    
  129. object for each user that exists for your backend (e.g., in your LDAP
    
  130. directory, your external SQL database, etc.) You can either write a script to
    
  131. do this in advance, or your ``authenticate`` method can do it the first time a
    
  132. user logs in.
    
  133. 
    
  134. Here's an example backend that authenticates against a username and password
    
  135. variable defined in your ``settings.py`` file and creates a Django ``User``
    
  136. object the first time a user authenticates::
    
  137. 
    
  138.     from django.conf import settings
    
  139.     from django.contrib.auth.backends import BaseBackend
    
  140.     from django.contrib.auth.hashers import check_password
    
  141.     from django.contrib.auth.models import User
    
  142. 
    
  143.     class SettingsBackend(BaseBackend):
    
  144.         """
    
  145.         Authenticate against the settings ADMIN_LOGIN and ADMIN_PASSWORD.
    
  146. 
    
  147.         Use the login name and a hash of the password. For example:
    
  148. 
    
  149.         ADMIN_LOGIN = 'admin'
    
  150.         ADMIN_PASSWORD = 'pbkdf2_sha256$30000$Vo0VlMnkR4Bk$qEvtdyZRWTcOsCnI/oQ7fVOu1XAURIZYoOZ3iq8Dr4M='
    
  151.         """
    
  152. 
    
  153.         def authenticate(self, request, username=None, password=None):
    
  154.             login_valid = (settings.ADMIN_LOGIN == username)
    
  155.             pwd_valid = check_password(password, settings.ADMIN_PASSWORD)
    
  156.             if login_valid and pwd_valid:
    
  157.                 try:
    
  158.                     user = User.objects.get(username=username)
    
  159.                 except User.DoesNotExist:
    
  160.                     # Create a new user. There's no need to set a password
    
  161.                     # because only the password from settings.py is checked.
    
  162.                     user = User(username=username)
    
  163.                     user.is_staff = True
    
  164.                     user.is_superuser = True
    
  165.                     user.save()
    
  166.                 return user
    
  167.             return None
    
  168. 
    
  169.         def get_user(self, user_id):
    
  170.             try:
    
  171.                 return User.objects.get(pk=user_id)
    
  172.             except User.DoesNotExist:
    
  173.                 return None
    
  174. 
    
  175. .. _authorization_methods:
    
  176. 
    
  177. Handling authorization in custom backends
    
  178. -----------------------------------------
    
  179. 
    
  180. Custom auth backends can provide their own permissions.
    
  181. 
    
  182. The user model and its manager will delegate permission lookup functions
    
  183. (:meth:`~django.contrib.auth.models.User.get_user_permissions()`,
    
  184. :meth:`~django.contrib.auth.models.User.get_group_permissions()`,
    
  185. :meth:`~django.contrib.auth.models.User.get_all_permissions()`,
    
  186. :meth:`~django.contrib.auth.models.User.has_perm()`,
    
  187. :meth:`~django.contrib.auth.models.User.has_module_perms()`, and
    
  188. :meth:`~django.contrib.auth.models.UserManager.with_perm()`) to any
    
  189. authentication backend that implements these functions.
    
  190. 
    
  191. The permissions given to the user will be the superset of all permissions
    
  192. returned by all backends. That is, Django grants a permission to a user that
    
  193. any one backend grants.
    
  194. 
    
  195. If a backend raises a :class:`~django.core.exceptions.PermissionDenied`
    
  196. exception in :meth:`~django.contrib.auth.models.User.has_perm()` or
    
  197. :meth:`~django.contrib.auth.models.User.has_module_perms()`, the authorization
    
  198. will immediately fail and Django won't check the backends that follow.
    
  199. 
    
  200. A backend could implement permissions for the magic admin like this::
    
  201. 
    
  202.     from django.contrib.auth.backends import BaseBackend
    
  203. 
    
  204.     class MagicAdminBackend(BaseBackend):
    
  205.         def has_perm(self, user_obj, perm, obj=None):
    
  206.             return user_obj.username == settings.ADMIN_LOGIN
    
  207. 
    
  208. This gives full permissions to the user granted access in the above example.
    
  209. Notice that in addition to the same arguments given to the associated
    
  210. :class:`django.contrib.auth.models.User` functions, the backend auth functions
    
  211. all take the user object, which may be an anonymous user, as an argument.
    
  212. 
    
  213. A full authorization implementation can be found in the ``ModelBackend`` class
    
  214. in :source:`django/contrib/auth/backends.py`, which is the default backend and
    
  215. queries the ``auth_permission`` table most of the time.
    
  216. 
    
  217. .. _anonymous_auth:
    
  218. 
    
  219. Authorization for anonymous users
    
  220. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
  221. 
    
  222. An anonymous user is one that is not authenticated i.e. they have provided no
    
  223. valid authentication details. However, that does not necessarily mean they are
    
  224. not authorized to do anything. At the most basic level, most websites
    
  225. authorize anonymous users to browse most of the site, and many allow anonymous
    
  226. posting of comments etc.
    
  227. 
    
  228. Django's permission framework does not have a place to store permissions for
    
  229. anonymous users. However, the user object passed to an authentication backend
    
  230. may be an :class:`django.contrib.auth.models.AnonymousUser` object, allowing
    
  231. the backend to specify custom authorization behavior for anonymous users. This
    
  232. is especially useful for the authors of reusable apps, who can delegate all
    
  233. questions of authorization to the auth backend, rather than needing settings,
    
  234. for example, to control anonymous access.
    
  235. 
    
  236. .. _inactive_auth:
    
  237. 
    
  238. Authorization for inactive users
    
  239. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
  240. 
    
  241. An inactive user is one that has its
    
  242. :attr:`~django.contrib.auth.models.User.is_active` field set to ``False``. The
    
  243. :class:`~django.contrib.auth.backends.ModelBackend` and
    
  244. :class:`~django.contrib.auth.backends.RemoteUserBackend` authentication
    
  245. backends prohibits these users from authenticating. If a custom user model
    
  246. doesn't have an :attr:`~django.contrib.auth.models.CustomUser.is_active` field,
    
  247. all users will be allowed to authenticate.
    
  248. 
    
  249. You can use :class:`~django.contrib.auth.backends.AllowAllUsersModelBackend`
    
  250. or :class:`~django.contrib.auth.backends.AllowAllUsersRemoteUserBackend` if you
    
  251. want to allow inactive users to authenticate.
    
  252. 
    
  253. The support for anonymous users in the permission system allows for a scenario
    
  254. where anonymous users have permissions to do something while inactive
    
  255. authenticated users do not.
    
  256. 
    
  257. Do not forget to test for the ``is_active`` attribute of the user in your own
    
  258. backend permission methods.
    
  259. 
    
  260. Handling object permissions
    
  261. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
  262. 
    
  263. Django's permission framework has a foundation for object permissions, though
    
  264. there is no implementation for it in the core. That means that checking for
    
  265. object permissions will always return ``False`` or an empty list (depending on
    
  266. the check performed). An authentication backend will receive the keyword
    
  267. parameters ``obj`` and ``user_obj`` for each object related authorization
    
  268. method and can return the object level permission as appropriate.
    
  269. 
    
  270. .. _custom-permissions:
    
  271. 
    
  272. Custom permissions
    
  273. ==================
    
  274. 
    
  275. To create custom permissions for a given model object, use the ``permissions``
    
  276. :ref:`model Meta attribute <meta-options>`.
    
  277. 
    
  278. This example ``Task`` model creates two custom permissions, i.e., actions users
    
  279. can or cannot do with ``Task`` instances, specific to your application::
    
  280. 
    
  281.     class Task(models.Model):
    
  282.         ...
    
  283.         class Meta:
    
  284.             permissions = [
    
  285.                 ("change_task_status", "Can change the status of tasks"),
    
  286.                 ("close_task", "Can remove a task by setting its status as closed"),
    
  287.             ]
    
  288. 
    
  289. The only thing this does is create those extra permissions when you run
    
  290. :djadmin:`manage.py migrate <migrate>` (the function that creates permissions
    
  291. is connected to the :data:`~django.db.models.signals.post_migrate` signal).
    
  292. Your code is in charge of checking the value of these permissions when a user
    
  293. is trying to access the functionality provided by the application (changing the
    
  294. status of tasks or closing tasks.) Continuing the above example, the following
    
  295. checks if a user may close tasks::
    
  296. 
    
  297.     user.has_perm('app.close_task')
    
  298. 
    
  299. .. _extending-user:
    
  300. 
    
  301. Extending the existing ``User`` model
    
  302. =====================================
    
  303. 
    
  304. There are two ways to extend the default
    
  305. :class:`~django.contrib.auth.models.User` model without substituting your own
    
  306. model. If the changes you need are purely behavioral, and don't require any
    
  307. change to what is stored in the database, you can create a :ref:`proxy model
    
  308. <proxy-models>` based on :class:`~django.contrib.auth.models.User`. This
    
  309. allows for any of the features offered by proxy models including default
    
  310. ordering, custom managers, or custom model methods.
    
  311. 
    
  312. If you wish to store information related to ``User``, you can use a
    
  313. :class:`~django.db.models.OneToOneField` to a model containing the fields for
    
  314. additional information. This one-to-one model is often called a profile model,
    
  315. as it might store non-auth related information about a site user. For example
    
  316. you might create an Employee model::
    
  317. 
    
  318.     from django.contrib.auth.models import User
    
  319. 
    
  320.     class Employee(models.Model):
    
  321.         user = models.OneToOneField(User, on_delete=models.CASCADE)
    
  322.         department = models.CharField(max_length=100)
    
  323. 
    
  324. Assuming an existing Employee Fred Smith who has both a User and Employee
    
  325. model, you can access the related information using Django's standard related
    
  326. model conventions::
    
  327. 
    
  328.     >>> u = User.objects.get(username='fsmith')
    
  329.     >>> freds_department = u.employee.department
    
  330. 
    
  331. To add a profile model's fields to the user page in the admin, define an
    
  332. :class:`~django.contrib.admin.InlineModelAdmin` (for this example, we'll use a
    
  333. :class:`~django.contrib.admin.StackedInline`) in your app's ``admin.py`` and
    
  334. add it to a ``UserAdmin`` class which is registered with the
    
  335. :class:`~django.contrib.auth.models.User` class::
    
  336. 
    
  337.     from django.contrib import admin
    
  338.     from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
    
  339.     from django.contrib.auth.models import User
    
  340. 
    
  341.     from my_user_profile_app.models import Employee
    
  342. 
    
  343.     # Define an inline admin descriptor for Employee model
    
  344.     # which acts a bit like a singleton
    
  345.     class EmployeeInline(admin.StackedInline):
    
  346.         model = Employee
    
  347.         can_delete = False
    
  348.         verbose_name_plural = 'employee'
    
  349. 
    
  350.     # Define a new User admin
    
  351.     class UserAdmin(BaseUserAdmin):
    
  352.         inlines = (EmployeeInline,)
    
  353. 
    
  354.     # Re-register UserAdmin
    
  355.     admin.site.unregister(User)
    
  356.     admin.site.register(User, UserAdmin)
    
  357. 
    
  358. These profile models are not special in any way - they are just Django models
    
  359. that happen to have a one-to-one link with a user model. As such, they aren't
    
  360. auto created when a user is created, but
    
  361. a :attr:`django.db.models.signals.post_save` could be used to create or update
    
  362. related models as appropriate.
    
  363. 
    
  364. Using related models results in additional queries or joins to retrieve the
    
  365. related data. Depending on your needs, a custom user model that includes the
    
  366. related fields may be your better option, however, existing relations to the
    
  367. default user model within your project's apps may justify the extra database
    
  368. load.
    
  369. 
    
  370. .. _auth-custom-user:
    
  371. 
    
  372. Substituting a custom ``User`` model
    
  373. ====================================
    
  374. 
    
  375. Some kinds of projects may have authentication requirements for which Django's
    
  376. built-in :class:`~django.contrib.auth.models.User` model is not always
    
  377. appropriate. For instance, on some sites it makes more sense to use an email
    
  378. address as your identification token instead of a username.
    
  379. 
    
  380. Django allows you to override the default user model by providing a value for
    
  381. the :setting:`AUTH_USER_MODEL` setting that references a custom model::
    
  382. 
    
  383.      AUTH_USER_MODEL = 'myapp.MyUser'
    
  384. 
    
  385. This dotted pair describes the :attr:`~django.apps.AppConfig.label` of the
    
  386. Django app (which must be in your :setting:`INSTALLED_APPS`), and the name of
    
  387. the Django model that you wish to use as your user model.
    
  388. 
    
  389. Using a custom user model when starting a project
    
  390. -------------------------------------------------
    
  391. 
    
  392. If you're starting a new project, it's highly recommended to set up a custom
    
  393. user model, even if the default :class:`~django.contrib.auth.models.User` model
    
  394. is sufficient for you. This model behaves identically to the default user
    
  395. model, but you'll be able to customize it in the future if the need arises::
    
  396. 
    
  397.     from django.contrib.auth.models import AbstractUser
    
  398. 
    
  399.     class User(AbstractUser):
    
  400.         pass
    
  401. 
    
  402. Don't forget to point :setting:`AUTH_USER_MODEL` to it. Do this before creating
    
  403. any migrations or running ``manage.py migrate`` for the first time.
    
  404. 
    
  405. Also, register the model in the app's ``admin.py``::
    
  406. 
    
  407.     from django.contrib import admin
    
  408.     from django.contrib.auth.admin import UserAdmin
    
  409.     from .models import User
    
  410. 
    
  411.     admin.site.register(User, UserAdmin)
    
  412. 
    
  413. Changing to a custom user model mid-project
    
  414. -------------------------------------------
    
  415. 
    
  416. Changing :setting:`AUTH_USER_MODEL` after you've created database tables is
    
  417. significantly more difficult since it affects foreign keys and many-to-many
    
  418. relationships, for example.
    
  419. 
    
  420. This change can't be done automatically and requires manually fixing your
    
  421. schema, moving your data from the old user table, and possibly manually
    
  422. reapplying some migrations. See :ticket:`25313` for an outline of the steps.
    
  423. 
    
  424. Due to limitations of Django's dynamic dependency feature for swappable
    
  425. models, the model referenced by :setting:`AUTH_USER_MODEL` must be created in
    
  426. the first migration of its app (usually called ``0001_initial``); otherwise,
    
  427. you'll have dependency issues.
    
  428. 
    
  429. In addition, you may run into a ``CircularDependencyError`` when running your
    
  430. migrations as Django won't be able to automatically break the dependency loop
    
  431. due to the dynamic dependency. If you see this error, you should break the loop
    
  432. by moving the models depended on by your user model into a second migration.
    
  433. (You can try making two normal models that have a ``ForeignKey`` to each other
    
  434. and seeing how ``makemigrations`` resolves that circular dependency if you want
    
  435. to see how it's usually done.)
    
  436. 
    
  437. Reusable apps and ``AUTH_USER_MODEL``
    
  438. -------------------------------------
    
  439. 
    
  440. Reusable apps shouldn't implement a custom user model. A project may use many
    
  441. apps, and two reusable apps that implemented a custom user model couldn't be
    
  442. used together. If you need to store per user information in your app, use
    
  443. a :class:`~django.db.models.ForeignKey` or
    
  444. :class:`~django.db.models.OneToOneField` to ``settings.AUTH_USER_MODEL``
    
  445. as described below.
    
  446. 
    
  447. Referencing the ``User`` model
    
  448. ------------------------------
    
  449. 
    
  450. .. currentmodule:: django.contrib.auth
    
  451. 
    
  452. If you reference :class:`~django.contrib.auth.models.User` directly (for
    
  453. example, by referring to it in a foreign key), your code will not work in
    
  454. projects where the :setting:`AUTH_USER_MODEL` setting has been changed to a
    
  455. different user model.
    
  456. 
    
  457. .. function:: get_user_model()
    
  458. 
    
  459.     Instead of referring to :class:`~django.contrib.auth.models.User` directly,
    
  460.     you should reference the user model using
    
  461.     ``django.contrib.auth.get_user_model()``. This method will return the
    
  462.     currently active user model -- the custom user model if one is specified, or
    
  463.     :class:`~django.contrib.auth.models.User` otherwise.
    
  464. 
    
  465.     When you define a foreign key or many-to-many relations to the user model,
    
  466.     you should specify the custom model using the :setting:`AUTH_USER_MODEL`
    
  467.     setting. For example::
    
  468. 
    
  469.         from django.conf import settings
    
  470.         from django.db import models
    
  471. 
    
  472.         class Article(models.Model):
    
  473.             author = models.ForeignKey(
    
  474.                 settings.AUTH_USER_MODEL,
    
  475.                 on_delete=models.CASCADE,
    
  476.             )
    
  477. 
    
  478.     When connecting to signals sent by the user model, you should specify
    
  479.     the custom model using the :setting:`AUTH_USER_MODEL` setting. For example::
    
  480. 
    
  481.         from django.conf import settings
    
  482.         from django.db.models.signals import post_save
    
  483. 
    
  484.         def post_save_receiver(sender, instance, created, **kwargs):
    
  485.             pass
    
  486. 
    
  487.         post_save.connect(post_save_receiver, sender=settings.AUTH_USER_MODEL)
    
  488. 
    
  489.     Generally speaking, it's easiest to refer to the user model with the
    
  490.     :setting:`AUTH_USER_MODEL` setting in code that's executed at import time,
    
  491.     however, it's also possible to call ``get_user_model()`` while Django
    
  492.     is importing models, so you could use
    
  493.     ``models.ForeignKey(get_user_model(), ...)``.
    
  494. 
    
  495.     If your app is tested with multiple user models, using
    
  496.     ``@override_settings(AUTH_USER_MODEL=...)`` for example, and you cache the
    
  497.     result of ``get_user_model()`` in a module-level variable, you may need to
    
  498.     listen to the  :data:`~django.test.signals.setting_changed` signal to clear
    
  499.     the cache. For example::
    
  500. 
    
  501.         from django.apps import apps
    
  502.         from django.contrib.auth import get_user_model
    
  503.         from django.core.signals import setting_changed
    
  504.         from django.dispatch import receiver
    
  505. 
    
  506.         @receiver(setting_changed)
    
  507.         def user_model_swapped(*, setting, **kwargs):
    
  508.             if setting == 'AUTH_USER_MODEL':
    
  509.                 apps.clear_cache()
    
  510.                 from myapp import some_module
    
  511.                 some_module.UserModel = get_user_model()
    
  512. 
    
  513. .. _specifying-custom-user-model:
    
  514. 
    
  515. Specifying a custom user model
    
  516. ------------------------------
    
  517. 
    
  518. When you start your project with a custom user model, stop to consider if this
    
  519. is the right choice for your project.
    
  520. 
    
  521. Keeping all user related information in one model removes the need for
    
  522. additional or more complex database queries to retrieve related models. On the
    
  523. other hand, it may be more suitable to store app-specific user information in a
    
  524. model that has a relation with your custom user model. That allows each app to
    
  525. specify its own user data requirements without potentially conflicting or
    
  526. breaking assumptions by other apps. It also means that you would keep your user
    
  527. model as simple as possible, focused on authentication, and following the
    
  528. minimum requirements Django expects custom user models to meet.
    
  529. 
    
  530. If you use the default authentication backend, then your model must have a
    
  531. single unique field that can be used for identification purposes. This can
    
  532. be a username, an email address, or any other unique attribute. A non-unique
    
  533. username field is allowed if you use a custom authentication backend that
    
  534. can support it.
    
  535. 
    
  536. The easiest way to construct a compliant custom user model is to inherit from
    
  537. :class:`~django.contrib.auth.models.AbstractBaseUser`.
    
  538. :class:`~django.contrib.auth.models.AbstractBaseUser` provides the core
    
  539. implementation of a user model, including hashed passwords and tokenized
    
  540. password resets. You must then provide some key implementation details:
    
  541. 
    
  542. .. currentmodule:: django.contrib.auth
    
  543. 
    
  544. .. class:: models.CustomUser
    
  545. 
    
  546.     .. attribute:: USERNAME_FIELD
    
  547. 
    
  548.         A string describing the name of the field on the user model that is
    
  549.         used as the unique identifier. This will usually be a username of some
    
  550.         kind, but it can also be an email address, or any other unique
    
  551.         identifier. The field *must* be unique (e.g. have ``unique=True`` set
    
  552.         in its definition), unless you use a custom authentication backend that
    
  553.         can support non-unique usernames.
    
  554. 
    
  555.         In the following example, the field ``identifier`` is used
    
  556.         as the identifying field::
    
  557. 
    
  558.             class MyUser(AbstractBaseUser):
    
  559.                 identifier = models.CharField(max_length=40, unique=True)
    
  560.                 ...
    
  561.                 USERNAME_FIELD = 'identifier'
    
  562. 
    
  563.     .. attribute:: EMAIL_FIELD
    
  564. 
    
  565.         A string describing the name of the email field on the ``User`` model.
    
  566.         This value is returned by
    
  567.         :meth:`~models.AbstractBaseUser.get_email_field_name`.
    
  568. 
    
  569.     .. attribute:: REQUIRED_FIELDS
    
  570. 
    
  571.         A list of the field names that will be prompted for when creating a
    
  572.         user via the :djadmin:`createsuperuser` management command. The user
    
  573.         will be prompted to supply a value for each of these fields. It must
    
  574.         include any field for which :attr:`~django.db.models.Field.blank` is
    
  575.         ``False`` or undefined and may include additional fields you want
    
  576.         prompted for when a user is created interactively.
    
  577.         ``REQUIRED_FIELDS`` has no effect in other parts of Django, like
    
  578.         creating a user in the admin.
    
  579. 
    
  580.         For example, here is the partial definition for a user model that
    
  581.         defines two required fields - a date of birth and height::
    
  582. 
    
  583.             class MyUser(AbstractBaseUser):
    
  584.                 ...
    
  585.                 date_of_birth = models.DateField()
    
  586.                 height = models.FloatField()
    
  587.                 ...
    
  588.                 REQUIRED_FIELDS = ['date_of_birth', 'height']
    
  589. 
    
  590.         .. note::
    
  591. 
    
  592.             ``REQUIRED_FIELDS`` must contain all required fields on your user
    
  593.             model, but should *not* contain the ``USERNAME_FIELD`` or
    
  594.             ``password`` as these fields will always be prompted for.
    
  595. 
    
  596.     .. attribute:: is_active
    
  597. 
    
  598.         A boolean attribute that indicates whether the user is considered
    
  599.         "active".  This attribute is provided as an attribute on
    
  600.         ``AbstractBaseUser`` defaulting to ``True``. How you choose to
    
  601.         implement it will depend on the details of your chosen auth backends.
    
  602.         See the documentation of the :attr:`is_active attribute on the built-in
    
  603.         user model <django.contrib.auth.models.User.is_active>` for details.
    
  604. 
    
  605.     .. method:: get_full_name()
    
  606. 
    
  607.         Optional. A longer formal identifier for the user such as their full
    
  608.         name. If implemented, this appears alongside the username in an
    
  609.         object's history in :mod:`django.contrib.admin`.
    
  610. 
    
  611.     .. method:: get_short_name()
    
  612. 
    
  613.         Optional. A short, informal identifier for the user such as their
    
  614.         first name. If implemented, this replaces the username in the greeting
    
  615.         to the user in the header of :mod:`django.contrib.admin`.
    
  616. 
    
  617.     .. admonition:: Importing ``AbstractBaseUser``
    
  618. 
    
  619.         ``AbstractBaseUser`` and ``BaseUserManager`` are importable from
    
  620.         ``django.contrib.auth.base_user`` so that they can be imported without
    
  621.         including ``django.contrib.auth`` in :setting:`INSTALLED_APPS`.
    
  622. 
    
  623. The following attributes and methods are available on any subclass of
    
  624. :class:`~django.contrib.auth.models.AbstractBaseUser`:
    
  625. 
    
  626. .. class:: models.AbstractBaseUser
    
  627. 
    
  628.     .. method:: get_username()
    
  629. 
    
  630.         Returns the value of the field nominated by ``USERNAME_FIELD``.
    
  631. 
    
  632.     .. method:: clean()
    
  633. 
    
  634.         Normalizes the username by calling :meth:`normalize_username`. If you
    
  635.         override this method, be sure to call ``super()`` to retain the
    
  636.         normalization.
    
  637. 
    
  638.     .. classmethod:: get_email_field_name()
    
  639. 
    
  640.        Returns the name of the email field specified by the
    
  641.        :attr:`~models.CustomUser.EMAIL_FIELD` attribute. Defaults to
    
  642.        ``'email'`` if ``EMAIL_FIELD`` isn't specified.
    
  643. 
    
  644.     .. classmethod:: normalize_username(username)
    
  645. 
    
  646.         Applies NFKC Unicode normalization to usernames so that visually
    
  647.         identical characters with different Unicode code points are considered
    
  648.         identical.
    
  649. 
    
  650.     .. attribute:: models.AbstractBaseUser.is_authenticated
    
  651. 
    
  652.         Read-only attribute which is always ``True`` (as opposed to
    
  653.         ``AnonymousUser.is_authenticated`` which is always ``False``).
    
  654.         This is a way to tell if the user has been authenticated. This does not
    
  655.         imply any permissions and doesn't check if the user is active or has
    
  656.         a valid session. Even though normally you will check this attribute on
    
  657.         ``request.user`` to find out whether it has been populated by the
    
  658.         :class:`~django.contrib.auth.middleware.AuthenticationMiddleware`
    
  659.         (representing the currently logged-in user), you should know this
    
  660.         attribute is ``True`` for any :class:`~models.User` instance.
    
  661. 
    
  662.     .. attribute:: models.AbstractBaseUser.is_anonymous
    
  663. 
    
  664.         Read-only attribute which is always ``False``. This is a way of
    
  665.         differentiating :class:`~models.User` and :class:`~models.AnonymousUser`
    
  666.         objects. Generally, you should prefer using
    
  667.         :attr:`~models.User.is_authenticated` to this attribute.
    
  668. 
    
  669.     .. method:: models.AbstractBaseUser.set_password(raw_password)
    
  670. 
    
  671.         Sets the user's password to the given raw string, taking care of the
    
  672.         password hashing. Doesn't save the
    
  673.         :class:`~django.contrib.auth.models.AbstractBaseUser` object.
    
  674. 
    
  675.         When the raw_password is ``None``, the password will be set to an
    
  676.         unusable password, as if
    
  677.         :meth:`~django.contrib.auth.models.AbstractBaseUser.set_unusable_password()`
    
  678.         were used.
    
  679. 
    
  680.     .. method:: models.AbstractBaseUser.check_password(raw_password)
    
  681. 
    
  682.         Returns ``True`` if the given raw string is the correct password for
    
  683.         the user. (This takes care of the password hashing in making the
    
  684.         comparison.)
    
  685. 
    
  686.     .. method:: models.AbstractBaseUser.set_unusable_password()
    
  687. 
    
  688.         Marks the user as having no password set.  This isn't the same as
    
  689.         having a blank string for a password.
    
  690.         :meth:`~django.contrib.auth.models.AbstractBaseUser.check_password()` for this user
    
  691.         will never return ``True``. Doesn't save the
    
  692.         :class:`~django.contrib.auth.models.AbstractBaseUser` object.
    
  693. 
    
  694.         You may need this if authentication for your application takes place
    
  695.         against an existing external source such as an LDAP directory.
    
  696. 
    
  697.     .. method:: models.AbstractBaseUser.has_usable_password()
    
  698. 
    
  699.         Returns ``False`` if
    
  700.         :meth:`~django.contrib.auth.models.AbstractBaseUser.set_unusable_password()` has
    
  701.         been called for this user.
    
  702. 
    
  703.     .. method:: models.AbstractBaseUser.get_session_auth_hash()
    
  704. 
    
  705.         Returns an HMAC of the password field. Used for
    
  706.         :ref:`session-invalidation-on-password-change`.
    
  707. 
    
  708.     .. method:: models.AbstractBaseUser.get_session_auth_fallback_hash()
    
  709. 
    
  710.         .. versionadded:: 4.1.8
    
  711. 
    
  712.         Yields the HMAC of the password field using
    
  713.         :setting:`SECRET_KEY_FALLBACKS`. Used by ``get_user()``.
    
  714. 
    
  715. :class:`~models.AbstractUser` subclasses :class:`~models.AbstractBaseUser`:
    
  716. 
    
  717. .. class:: models.AbstractUser
    
  718. 
    
  719.     .. method:: clean()
    
  720. 
    
  721.         Normalizes the email by calling
    
  722.         :meth:`.BaseUserManager.normalize_email`. If you override this method,
    
  723.         be sure to call ``super()`` to retain the normalization.
    
  724. 
    
  725. Writing a manager for a custom user model
    
  726. -----------------------------------------
    
  727. 
    
  728. You should also define a custom manager for your user model. If your user model
    
  729. defines ``username``, ``email``, ``is_staff``, ``is_active``, ``is_superuser``,
    
  730. ``last_login``, and ``date_joined`` fields the same as Django's default user,
    
  731. you can install Django's :class:`~django.contrib.auth.models.UserManager`;
    
  732. however, if your user model defines different fields, you'll need to define a
    
  733. custom manager that extends :class:`~django.contrib.auth.models.BaseUserManager`
    
  734. providing two additional methods:
    
  735. 
    
  736. .. class:: models.CustomUserManager
    
  737. 
    
  738.     .. method:: models.CustomUserManager.create_user(username_field, password=None, **other_fields)
    
  739. 
    
  740.         The prototype of ``create_user()`` should accept the username field,
    
  741.         plus all required fields as arguments. For example, if your user model
    
  742.         uses ``email`` as the username field, and has ``date_of_birth`` as a
    
  743.         required field, then ``create_user`` should be defined as::
    
  744. 
    
  745.             def create_user(self, email, date_of_birth, password=None):
    
  746.                 # create user here
    
  747.                 ...
    
  748. 
    
  749.     .. method:: models.CustomUserManager.create_superuser(username_field, password=None, **other_fields)
    
  750. 
    
  751.         The prototype of ``create_superuser()`` should accept the username
    
  752.         field, plus all required fields as arguments. For example, if your user
    
  753.         model uses ``email`` as the username field, and has ``date_of_birth``
    
  754.         as a required field, then ``create_superuser`` should be defined as::
    
  755. 
    
  756.             def create_superuser(self, email, date_of_birth, password=None):
    
  757.                 # create superuser here
    
  758.                 ...
    
  759. 
    
  760. For a :class:`~.ForeignKey` in :attr:`.USERNAME_FIELD` or
    
  761. :attr:`.REQUIRED_FIELDS`, these methods receive the value of the
    
  762. :attr:`~.ForeignKey.to_field` (the :attr:`~django.db.models.Field.primary_key`
    
  763. by default) of an existing instance.
    
  764. 
    
  765. :class:`~django.contrib.auth.models.BaseUserManager` provides the following
    
  766. utility methods:
    
  767. 
    
  768. .. class:: models.BaseUserManager
    
  769. 
    
  770.     .. classmethod:: models.BaseUserManager.normalize_email(email)
    
  771. 
    
  772.         Normalizes email addresses by lowercasing the domain portion of the
    
  773.         email address.
    
  774. 
    
  775.     .. method:: models.BaseUserManager.get_by_natural_key(username)
    
  776. 
    
  777.         Retrieves a user instance using the contents of the field
    
  778.         nominated by ``USERNAME_FIELD``.
    
  779. 
    
  780.     .. method:: models.BaseUserManager.make_random_password(length=10, allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789')
    
  781. 
    
  782.         Returns a random password with the given length and given string of
    
  783.         allowed characters. Note that the default value of ``allowed_chars``
    
  784.         doesn't contain letters that can cause user confusion, including:
    
  785. 
    
  786.         * ``i``, ``l``, ``I``, and ``1`` (lowercase letter i, lowercase
    
  787.           letter L, uppercase letter i, and the number one)
    
  788.         * ``o``, ``O``, and ``0`` (lowercase letter o, uppercase letter o,
    
  789.           and zero)
    
  790. 
    
  791. Extending Django's default ``User``
    
  792. -----------------------------------
    
  793. 
    
  794. If you're entirely happy with Django's :class:`~django.contrib.auth.models.User`
    
  795. model, but you want to add some additional profile information, you could
    
  796. subclass :class:`django.contrib.auth.models.AbstractUser` and add your custom
    
  797. profile fields, although we'd recommend a separate model as described in
    
  798. :ref:`specifying-custom-user-model`. ``AbstractUser`` provides the full
    
  799. implementation of the default :class:`~django.contrib.auth.models.User` as an
    
  800. :ref:`abstract model <abstract-base-classes>`.
    
  801. 
    
  802. .. _custom-users-and-the-built-in-auth-forms:
    
  803. 
    
  804. Custom users and the built-in auth forms
    
  805. ----------------------------------------
    
  806. 
    
  807. Django's built-in :ref:`forms <built-in-auth-forms>` and :ref:`views
    
  808. <built-in-auth-views>` make certain assumptions about the user model that they
    
  809. are working with.
    
  810. 
    
  811. The following forms are compatible with any subclass of
    
  812. :class:`~django.contrib.auth.models.AbstractBaseUser`:
    
  813. 
    
  814. * :class:`~django.contrib.auth.forms.AuthenticationForm`: Uses the username
    
  815.   field specified by :attr:`~models.CustomUser.USERNAME_FIELD`.
    
  816. * :class:`~django.contrib.auth.forms.SetPasswordForm`
    
  817. * :class:`~django.contrib.auth.forms.PasswordChangeForm`
    
  818. * :class:`~django.contrib.auth.forms.AdminPasswordChangeForm`
    
  819. 
    
  820. The following forms make assumptions about the user model and can be used as-is
    
  821. if those assumptions are met:
    
  822. 
    
  823. * :class:`~django.contrib.auth.forms.PasswordResetForm`: Assumes that the user
    
  824.   model has a field that stores the user's email address with the name returned
    
  825.   by :meth:`~models.AbstractBaseUser.get_email_field_name` (``email`` by
    
  826.   default) that can be used to identify the user and a boolean field named
    
  827.   ``is_active`` to prevent password resets for inactive users.
    
  828. 
    
  829. Finally, the following forms are tied to
    
  830. :class:`~django.contrib.auth.models.User` and need to be rewritten or extended
    
  831. to work with a custom user model:
    
  832. 
    
  833. * :class:`~django.contrib.auth.forms.UserCreationForm`
    
  834. * :class:`~django.contrib.auth.forms.UserChangeForm`
    
  835. 
    
  836. If your custom user model is a subclass of ``AbstractUser``, then you can
    
  837. extend these forms in this manner::
    
  838. 
    
  839.     from django.contrib.auth.forms import UserCreationForm
    
  840.     from myapp.models import CustomUser
    
  841. 
    
  842.     class CustomUserCreationForm(UserCreationForm):
    
  843. 
    
  844.         class Meta(UserCreationForm.Meta):
    
  845.             model = CustomUser
    
  846.             fields = UserCreationForm.Meta.fields + ('custom_field',)
    
  847. 
    
  848. Custom users and :mod:`django.contrib.admin`
    
  849. --------------------------------------------
    
  850. 
    
  851. If you want your custom user model to also work with the admin, your user model
    
  852. must define some additional attributes and methods. These methods allow the
    
  853. admin to control access of the user to admin content:
    
  854. 
    
  855. .. class:: models.CustomUser
    
  856.     :noindex:
    
  857. 
    
  858. .. attribute:: is_staff
    
  859. 
    
  860.     Returns ``True`` if the user is allowed to have access to the admin site.
    
  861. 
    
  862. .. attribute:: is_active
    
  863. 
    
  864.     Returns ``True`` if the user account is currently active.
    
  865. 
    
  866. .. method:: has_perm(perm, obj=None):
    
  867. 
    
  868.     Returns ``True`` if the user has the named permission. If ``obj`` is
    
  869.     provided, the permission needs to be checked against a specific object
    
  870.     instance.
    
  871. 
    
  872. .. method:: has_module_perms(app_label):
    
  873. 
    
  874.     Returns ``True`` if the user has permission to access models in
    
  875.     the given app.
    
  876. 
    
  877. You will also need to register your custom user model with the admin. If
    
  878. your custom user model extends ``django.contrib.auth.models.AbstractUser``,
    
  879. you can use Django's existing ``django.contrib.auth.admin.UserAdmin``
    
  880. class. However, if your user model extends
    
  881. :class:`~django.contrib.auth.models.AbstractBaseUser`, you'll need to define
    
  882. a custom ``ModelAdmin`` class. It may be possible to subclass the default
    
  883. ``django.contrib.auth.admin.UserAdmin``; however, you'll need to
    
  884. override any of the definitions that refer to fields on
    
  885. ``django.contrib.auth.models.AbstractUser`` that aren't on your
    
  886. custom user class.
    
  887. 
    
  888. .. note::
    
  889. 
    
  890.     If you are using a custom ``ModelAdmin`` which is a subclass of
    
  891.     ``django.contrib.auth.admin.UserAdmin``, then you need to add your custom
    
  892.     fields to ``fieldsets`` (for fields to be used in editing users) and to
    
  893.     ``add_fieldsets`` (for fields to be used when creating a user). For
    
  894.     example::
    
  895. 
    
  896.         from django.contrib.auth.admin import UserAdmin
    
  897. 
    
  898.         class CustomUserAdmin(UserAdmin):
    
  899.             ...
    
  900.             fieldsets = UserAdmin.fieldsets + (
    
  901.                 (None, {'fields': ('custom_field',)}),
    
  902.             )
    
  903.             add_fieldsets = UserAdmin.add_fieldsets + (
    
  904.                 (None, {'fields': ('custom_field',)}),
    
  905.             )
    
  906. 
    
  907.     See :ref:`a full example <custom-users-admin-full-example>` for more
    
  908.     details.
    
  909. 
    
  910. Custom users and permissions
    
  911. ----------------------------
    
  912. 
    
  913. To make it easy to include Django's permission framework into your own user
    
  914. class, Django provides :class:`~django.contrib.auth.models.PermissionsMixin`.
    
  915. This is an abstract model you can include in the class hierarchy for your user
    
  916. model, giving you all the methods and database fields necessary to support
    
  917. Django's permission model.
    
  918. 
    
  919. :class:`~django.contrib.auth.models.PermissionsMixin` provides the following
    
  920. methods and attributes:
    
  921. 
    
  922. .. class:: models.PermissionsMixin
    
  923. 
    
  924.     .. attribute:: models.PermissionsMixin.is_superuser
    
  925. 
    
  926.         Boolean. Designates that this user has all permissions without
    
  927.         explicitly assigning them.
    
  928. 
    
  929.     .. method:: models.PermissionsMixin.get_user_permissions(obj=None)
    
  930. 
    
  931.         Returns a set of permission strings that the user has directly.
    
  932. 
    
  933.         If ``obj`` is passed in, only returns the user permissions for this
    
  934.         specific object.
    
  935. 
    
  936.     .. method:: models.PermissionsMixin.get_group_permissions(obj=None)
    
  937. 
    
  938.         Returns a set of permission strings that the user has, through their
    
  939.         groups.
    
  940. 
    
  941.         If ``obj`` is passed in, only returns the group permissions for
    
  942.         this specific object.
    
  943. 
    
  944.     .. method:: models.PermissionsMixin.get_all_permissions(obj=None)
    
  945. 
    
  946.         Returns a set of permission strings that the user has, both through
    
  947.         group and user permissions.
    
  948. 
    
  949.         If ``obj`` is passed in, only returns the permissions for this
    
  950.         specific object.
    
  951. 
    
  952.     .. method:: models.PermissionsMixin.has_perm(perm, obj=None)
    
  953. 
    
  954.         Returns ``True`` if the user has the specified permission, where
    
  955.         ``perm`` is in the format ``"<app label>.<permission codename>"`` (see
    
  956.         :ref:`permissions <topic-authorization>`). If :attr:`.User.is_active`
    
  957.         and :attr:`~.User.is_superuser` are both ``True``, this method always
    
  958.         returns ``True``.
    
  959. 
    
  960.         If ``obj`` is passed in, this method won't check for a permission for
    
  961.         the model, but for this specific object.
    
  962. 
    
  963.     .. method:: models.PermissionsMixin.has_perms(perm_list, obj=None)
    
  964. 
    
  965.         Returns ``True`` if the user has each of the specified permissions,
    
  966.         where each perm is in the format
    
  967.         ``"<app label>.<permission codename>"``. If :attr:`.User.is_active` and
    
  968.         :attr:`~.User.is_superuser` are both ``True``, this method always
    
  969.         returns ``True``.
    
  970. 
    
  971.         If ``obj`` is passed in, this method won't check for permissions for
    
  972.         the model, but for the specific object.
    
  973. 
    
  974.     .. method:: models.PermissionsMixin.has_module_perms(package_name)
    
  975. 
    
  976.         Returns ``True`` if the user has any permissions in the given package
    
  977.         (the Django app label). If :attr:`.User.is_active` and
    
  978.         :attr:`~.User.is_superuser` are both ``True``, this method always
    
  979.         returns ``True``.
    
  980. 
    
  981. .. admonition:: ``PermissionsMixin`` and ``ModelBackend``
    
  982. 
    
  983.     If you don't include the
    
  984.     :class:`~django.contrib.auth.models.PermissionsMixin`, you must ensure you
    
  985.     don't invoke the permissions methods on ``ModelBackend``. ``ModelBackend``
    
  986.     assumes that certain fields are available on your user model. If your user
    
  987.     model doesn't provide  those fields, you'll receive database errors when
    
  988.     you check permissions.
    
  989. 
    
  990. Custom users and proxy models
    
  991. -----------------------------
    
  992. 
    
  993. One limitation of custom user models is that installing a custom user model
    
  994. will break any proxy model extending :class:`~django.contrib.auth.models.User`.
    
  995. Proxy models must be based on a concrete base class; by defining a custom user
    
  996. model, you remove the ability of Django to reliably identify the base class.
    
  997. 
    
  998. If your project uses proxy models, you must either modify the proxy to extend
    
  999. the user model that's in use in your project, or merge your proxy's behavior
    
  1000. into your :class:`~django.contrib.auth.models.User` subclass.
    
  1001. 
    
  1002. .. _custom-users-admin-full-example:
    
  1003. 
    
  1004. A full example
    
  1005. --------------
    
  1006. 
    
  1007. Here is an example of an admin-compliant custom user app. This user model uses
    
  1008. an email address as the username, and has a required date of birth; it
    
  1009. provides no permission checking beyond an ``admin`` flag on the user account.
    
  1010. This model would be compatible with all the built-in auth forms and views,
    
  1011. except for the user creation forms. This example illustrates how most of the
    
  1012. components work together, but is not intended to be copied directly into
    
  1013. projects for production use.
    
  1014. 
    
  1015. This code would all live in a ``models.py`` file for a custom
    
  1016. authentication app::
    
  1017. 
    
  1018.     from django.db import models
    
  1019.     from django.contrib.auth.models import (
    
  1020.         BaseUserManager, AbstractBaseUser
    
  1021.     )
    
  1022. 
    
  1023. 
    
  1024.     class MyUserManager(BaseUserManager):
    
  1025.         def create_user(self, email, date_of_birth, password=None):
    
  1026.             """
    
  1027.             Creates and saves a User with the given email, date of
    
  1028.             birth and password.
    
  1029.             """
    
  1030.             if not email:
    
  1031.                 raise ValueError('Users must have an email address')
    
  1032. 
    
  1033.             user = self.model(
    
  1034.                 email=self.normalize_email(email),
    
  1035.                 date_of_birth=date_of_birth,
    
  1036.             )
    
  1037. 
    
  1038.             user.set_password(password)
    
  1039.             user.save(using=self._db)
    
  1040.             return user
    
  1041. 
    
  1042.         def create_superuser(self, email, date_of_birth, password=None):
    
  1043.             """
    
  1044.             Creates and saves a superuser with the given email, date of
    
  1045.             birth and password.
    
  1046.             """
    
  1047.             user = self.create_user(
    
  1048.                 email,
    
  1049.                 password=password,
    
  1050.                 date_of_birth=date_of_birth,
    
  1051.             )
    
  1052.             user.is_admin = True
    
  1053.             user.save(using=self._db)
    
  1054.             return user
    
  1055. 
    
  1056. 
    
  1057.     class MyUser(AbstractBaseUser):
    
  1058.         email = models.EmailField(
    
  1059.             verbose_name='email address',
    
  1060.             max_length=255,
    
  1061.             unique=True,
    
  1062.         )
    
  1063.         date_of_birth = models.DateField()
    
  1064.         is_active = models.BooleanField(default=True)
    
  1065.         is_admin = models.BooleanField(default=False)
    
  1066. 
    
  1067.         objects = MyUserManager()
    
  1068. 
    
  1069.         USERNAME_FIELD = 'email'
    
  1070.         REQUIRED_FIELDS = ['date_of_birth']
    
  1071. 
    
  1072.         def __str__(self):
    
  1073.             return self.email
    
  1074. 
    
  1075.         def has_perm(self, perm, obj=None):
    
  1076.             "Does the user have a specific permission?"
    
  1077.             # Simplest possible answer: Yes, always
    
  1078.             return True
    
  1079. 
    
  1080.         def has_module_perms(self, app_label):
    
  1081.             "Does the user have permissions to view the app `app_label`?"
    
  1082.             # Simplest possible answer: Yes, always
    
  1083.             return True
    
  1084. 
    
  1085.         @property
    
  1086.         def is_staff(self):
    
  1087.             "Is the user a member of staff?"
    
  1088.             # Simplest possible answer: All admins are staff
    
  1089.             return self.is_admin
    
  1090. 
    
  1091. Then, to register this custom user model with Django's admin, the following
    
  1092. code would be required in the app's ``admin.py`` file::
    
  1093. 
    
  1094.     from django import forms
    
  1095.     from django.contrib import admin
    
  1096.     from django.contrib.auth.models import Group
    
  1097.     from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
    
  1098.     from django.contrib.auth.forms import ReadOnlyPasswordHashField
    
  1099.     from django.core.exceptions import ValidationError
    
  1100. 
    
  1101.     from customauth.models import MyUser
    
  1102. 
    
  1103. 
    
  1104.     class UserCreationForm(forms.ModelForm):
    
  1105.         """A form for creating new users. Includes all the required
    
  1106.         fields, plus a repeated password."""
    
  1107.         password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
    
  1108.         password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
    
  1109. 
    
  1110.         class Meta:
    
  1111.             model = MyUser
    
  1112.             fields = ('email', 'date_of_birth')
    
  1113. 
    
  1114.         def clean_password2(self):
    
  1115.             # Check that the two password entries match
    
  1116.             password1 = self.cleaned_data.get("password1")
    
  1117.             password2 = self.cleaned_data.get("password2")
    
  1118.             if password1 and password2 and password1 != password2:
    
  1119.                 raise ValidationError("Passwords don't match")
    
  1120.             return password2
    
  1121. 
    
  1122.         def save(self, commit=True):
    
  1123.             # Save the provided password in hashed format
    
  1124.             user = super().save(commit=False)
    
  1125.             user.set_password(self.cleaned_data["password1"])
    
  1126.             if commit:
    
  1127.                 user.save()
    
  1128.             return user
    
  1129. 
    
  1130. 
    
  1131.     class UserChangeForm(forms.ModelForm):
    
  1132.         """A form for updating users. Includes all the fields on
    
  1133.         the user, but replaces the password field with admin's
    
  1134.         disabled password hash display field.
    
  1135.         """
    
  1136.         password = ReadOnlyPasswordHashField()
    
  1137. 
    
  1138.         class Meta:
    
  1139.             model = MyUser
    
  1140.             fields = ('email', 'password', 'date_of_birth', 'is_active', 'is_admin')
    
  1141. 
    
  1142. 
    
  1143.     class UserAdmin(BaseUserAdmin):
    
  1144.         # The forms to add and change user instances
    
  1145.         form = UserChangeForm
    
  1146.         add_form = UserCreationForm
    
  1147. 
    
  1148.         # The fields to be used in displaying the User model.
    
  1149.         # These override the definitions on the base UserAdmin
    
  1150.         # that reference specific fields on auth.User.
    
  1151.         list_display = ('email', 'date_of_birth', 'is_admin')
    
  1152.         list_filter = ('is_admin',)
    
  1153.         fieldsets = (
    
  1154.             (None, {'fields': ('email', 'password')}),
    
  1155.             ('Personal info', {'fields': ('date_of_birth',)}),
    
  1156.             ('Permissions', {'fields': ('is_admin',)}),
    
  1157.         )
    
  1158.         # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
    
  1159.         # overrides get_fieldsets to use this attribute when creating a user.
    
  1160.         add_fieldsets = (
    
  1161.             (None, {
    
  1162.                 'classes': ('wide',),
    
  1163.                 'fields': ('email', 'date_of_birth', 'password1', 'password2'),
    
  1164.             }),
    
  1165.         )
    
  1166.         search_fields = ('email',)
    
  1167.         ordering = ('email',)
    
  1168.         filter_horizontal = ()
    
  1169. 
    
  1170. 
    
  1171.     # Now register the new UserAdmin...
    
  1172.     admin.site.register(MyUser, UserAdmin)
    
  1173.     # ... and, since we're not using Django's built-in permissions,
    
  1174.     # unregister the Group model from admin.
    
  1175.     admin.site.unregister(Group)
    
  1176. 
    
  1177. Finally, specify the custom model as the default user model for your project
    
  1178. using the :setting:`AUTH_USER_MODEL` setting in your ``settings.py``::
    
  1179. 
    
  1180.     AUTH_USER_MODEL = 'customauth.MyUser'