customizing.txt 49 KB

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