customizing.txt 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114
  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. To customize
  6. authentication to your projects needs involves 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
  11. to be authenticated against a different service than Django's default.
  12. You can give your models :ref:`custom permissions <custom-permissions>` that can be
  13. checked through Django's authorization system.
  14. You can :ref:`extend <extending-user>` the default User model, or :ref:`substitute
  15. <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 re-uses 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 simple
  66. way to do that is simply 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(**credentials)``, as well as a set of
  71. optional permission related :ref:`authorization methods <authorization_methods>`.
  72. The ``get_user`` method takes a ``user_id`` -- which could be a username,
  73. database ID or whatever, but has to be the primary key of your ``User`` object
  74. -- and returns a ``User`` object.
  75. The ``authenticate`` method takes credentials as keyword arguments. Most of
  76. the time, it'll just look like this::
  77. class MyBackend(object):
  78. def authenticate(self, username=None, password=None):
  79. # Check the username/password and return a User.
  80. ...
  81. But it could also authenticate a token, like so::
  82. class MyBackend(object):
  83. def authenticate(self, token=None):
  84. # Check the token and return a User.
  85. ...
  86. Either way, ``authenticate`` should check the credentials it gets, and it
  87. should return a ``User`` object that matches those credentials, if the
  88. credentials are valid. If they're not valid, it should return ``None``.
  89. The Django admin is tightly coupled to the Django :ref:`User object
  90. <user-objects>`. The best way to deal with this is to create a Django ``User``
  91. object for each user that exists for your backend (e.g., in your LDAP
  92. directory, your external SQL database, etc.) You can either write a script to
  93. do this in advance, or your ``authenticate`` method can do it the first time a
  94. user logs in.
  95. Here's an example backend that authenticates against a username and password
  96. variable defined in your ``settings.py`` file and creates a Django ``User``
  97. object the first time a user authenticates::
  98. from django.conf import settings
  99. from django.contrib.auth.hashers import check_password
  100. from django.contrib.auth.models import User
  101. class SettingsBackend(object):
  102. """
  103. Authenticate against the settings ADMIN_LOGIN and ADMIN_PASSWORD.
  104. Use the login name, and a hash of the password. For example:
  105. ADMIN_LOGIN = 'admin'
  106. ADMIN_PASSWORD = 'pbkdf2_sha256$30000$Vo0VlMnkR4Bk$qEvtdyZRWTcOsCnI/oQ7fVOu1XAURIZYoOZ3iq8Dr4M='
  107. """
  108. def authenticate(self, username=None, password=None):
  109. login_valid = (settings.ADMIN_LOGIN == username)
  110. pwd_valid = check_password(password, settings.ADMIN_PASSWORD)
  111. if login_valid and pwd_valid:
  112. try:
  113. user = User.objects.get(username=username)
  114. except User.DoesNotExist:
  115. # Create a new user. Note that we can set password
  116. # to anything, because it won't be checked; the password
  117. # from settings.py will.
  118. user = User(username=username, password='get from settings.py')
  119. user.is_staff = True
  120. user.is_superuser = True
  121. user.save()
  122. return user
  123. return None
  124. def get_user(self, user_id):
  125. try:
  126. return User.objects.get(pk=user_id)
  127. except User.DoesNotExist:
  128. return None
  129. .. _authorization_methods:
  130. Handling authorization in custom backends
  131. -----------------------------------------
  132. Custom auth backends can provide their own permissions.
  133. The user model will delegate permission lookup functions
  134. (:meth:`~django.contrib.auth.models.User.get_group_permissions()`,
  135. :meth:`~django.contrib.auth.models.User.get_all_permissions()`,
  136. :meth:`~django.contrib.auth.models.User.has_perm()`, and
  137. :meth:`~django.contrib.auth.models.User.has_module_perms()`) to any
  138. authentication backend that implements these functions.
  139. The permissions given to the user will be the superset of all permissions
  140. returned by all backends. That is, Django grants a permission to a user that
  141. any one backend grants.
  142. If a backend raises a :class:`~django.core.exceptions.PermissionDenied`
  143. exception in :meth:`~django.contrib.auth.models.User.has_perm()` or
  144. :meth:`~django.contrib.auth.models.User.has_module_perms()`, the authorization
  145. will immediately fail and Django won't check the backends that follow.
  146. The simple backend above could implement permissions for the magic admin
  147. fairly simply::
  148. class SettingsBackend(object):
  149. ...
  150. def has_perm(self, user_obj, perm, obj=None):
  151. if user_obj.username == settings.ADMIN_LOGIN:
  152. return True
  153. else:
  154. return False
  155. This gives full permissions to the user granted access in the above example.
  156. Notice that in addition to the same arguments given to the associated
  157. :class:`django.contrib.auth.models.User` functions, the backend auth functions
  158. all take the user object, which may be an anonymous user, as an argument.
  159. A full authorization implementation can be found in the ``ModelBackend`` class
  160. in `django/contrib/auth/backends.py`_, which is the default backend and queries
  161. the ``auth_permission`` table most of the time. If you wish to provide
  162. custom behavior for only part of the backend API, you can take advantage of
  163. Python inheritance and subclass ``ModelBackend`` instead of implementing the
  164. complete API in a custom backend.
  165. .. _django/contrib/auth/backends.py: https://github.com/django/django/blob/master/django/contrib/auth/backends.py
  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 re-usable 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 a 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. .. versionchanged:: 1.10
  200. In older versions, the :class:`~django.contrib.auth.backends.ModelBackend`
  201. allowed inactive users to authenticate.
  202. Handling object permissions
  203. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  204. Django's permission framework has a foundation for object permissions, though
  205. there is no implementation for it in the core. That means that checking for
  206. object permissions will always return ``False`` or an empty list (depending on
  207. the check performed). An authentication backend will receive the keyword
  208. parameters ``obj`` and ``user_obj`` for each object related authorization
  209. method and can return the object level permission as appropriate.
  210. .. _custom-permissions:
  211. Custom permissions
  212. ==================
  213. To create custom permissions for a given model object, use the ``permissions``
  214. :ref:`model Meta attribute <meta-options>`.
  215. This example Task model creates three custom permissions, i.e., actions users
  216. can or cannot do with Task instances, specific to your application::
  217. class Task(models.Model):
  218. ...
  219. class Meta:
  220. permissions = (
  221. ("view_task", "Can see available tasks"),
  222. ("change_task_status", "Can change the status of tasks"),
  223. ("close_task", "Can remove a task by setting its status as closed"),
  224. )
  225. The only thing this does is create those extra permissions when you run
  226. :djadmin:`manage.py migrate <migrate>` (the function that creates permissions
  227. is connected to the :data:`~django.db.models.signals.post_migrate` signal).
  228. Your code is in charge of checking the value of these permissions when a user
  229. is trying to access the functionality provided by the application (viewing
  230. tasks, changing the status of tasks, closing tasks.) Continuing the above
  231. example, the following checks if a user may view tasks::
  232. user.has_perm('app.view_task')
  233. .. _extending-user:
  234. Extending the existing ``User`` model
  235. =====================================
  236. There are two ways to extend the default
  237. :class:`~django.contrib.auth.models.User` model without substituting your own
  238. model. If the changes you need are purely behavioral, and don't require any
  239. change to what is stored in the database, you can create a :ref:`proxy model
  240. <proxy-models>` based on :class:`~django.contrib.auth.models.User`. This
  241. allows for any of the features offered by proxy models including default
  242. ordering, custom managers, or custom model methods.
  243. If you wish to store information related to ``User``, you can use a
  244. :class:`~django.db.models.OneToOneField` to a model containing the fields for
  245. additional information. This one-to-one model is often called a profile model,
  246. as it might store non-auth related information about a site user. For example
  247. you might create an Employee model::
  248. from django.contrib.auth.models import User
  249. class Employee(models.Model):
  250. user = models.OneToOneField(User, on_delete=models.CASCADE)
  251. department = models.CharField(max_length=100)
  252. Assuming an existing Employee Fred Smith who has both a User and Employee
  253. model, you can access the related information using Django's standard related
  254. model conventions::
  255. >>> u = User.objects.get(username='fsmith')
  256. >>> freds_department = u.employee.department
  257. To add a profile model's fields to the user page in the admin, define an
  258. :class:`~django.contrib.admin.InlineModelAdmin` (for this example, we'll use a
  259. :class:`~django.contrib.admin.StackedInline`) in your app's ``admin.py`` and
  260. add it to a ``UserAdmin`` class which is registered with the
  261. :class:`~django.contrib.auth.models.User` class::
  262. from django.contrib import admin
  263. from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
  264. from django.contrib.auth.models import User
  265. from my_user_profile_app.models import Employee
  266. # Define an inline admin descriptor for Employee model
  267. # which acts a bit like a singleton
  268. class EmployeeInline(admin.StackedInline):
  269. model = Employee
  270. can_delete = False
  271. verbose_name_plural = 'employee'
  272. # Define a new User admin
  273. class UserAdmin(BaseUserAdmin):
  274. inlines = (EmployeeInline, )
  275. # Re-register UserAdmin
  276. admin.site.unregister(User)
  277. admin.site.register(User, UserAdmin)
  278. These profile models are not special in any way - they are just Django models that
  279. happen to have a one-to-one link with a User model. As such, they do not get
  280. auto created when a user is created, but
  281. a :attr:`django.db.models.signals.post_save` could be used to create or update
  282. related models as appropriate.
  283. Note that using related models results in additional queries or joins to
  284. retrieve the related data, and depending on your needs substituting the User
  285. model and adding the related fields may be your better option. However
  286. existing links to the default User model within your project's apps may justify
  287. the extra database load.
  288. .. _auth-custom-user:
  289. Substituting a custom ``User`` model
  290. ====================================
  291. Some kinds of projects may have authentication requirements for which Django's
  292. built-in :class:`~django.contrib.auth.models.User` model is not always
  293. appropriate. For instance, on some sites it makes more sense to use an email
  294. address as your identification token instead of a username.
  295. Django allows you to override the default User model by providing a value for
  296. the :setting:`AUTH_USER_MODEL` setting that references a custom model::
  297. AUTH_USER_MODEL = 'myapp.MyUser'
  298. This dotted pair describes the name of the Django app (which must be in your
  299. :setting:`INSTALLED_APPS`), and the name of the Django model that you wish to
  300. use as your User model.
  301. .. warning::
  302. Changing :setting:`AUTH_USER_MODEL` has a big effect on your database
  303. structure. It changes the tables that are available, and it will affect the
  304. construction of foreign keys and many-to-many relationships. If you intend
  305. to set :setting:`AUTH_USER_MODEL`, you should set it before creating
  306. any migrations or running ``manage.py migrate`` for the first time.
  307. Changing this setting after you have tables created is not supported
  308. by :djadmin:`makemigrations` and will result in you having to manually
  309. fix your schema, port your data from the old user table, and possibly
  310. manually reapply some migrations.
  311. .. warning::
  312. Due to limitations of Django's dynamic dependency feature for swappable
  313. models, you must ensure that the model referenced by :setting:`AUTH_USER_MODEL`
  314. is created in the first migration of its app (usually called ``0001_initial``);
  315. otherwise, you will have dependency issues.
  316. In addition, you may run into a CircularDependencyError when running your
  317. migrations as Django won't be able to automatically break the dependency
  318. loop due to the dynamic dependency. If you see this error, you should
  319. break the loop by moving the models depended on by your User model
  320. into a second migration (you can try making two normal models that
  321. have a ForeignKey to each other and seeing how ``makemigrations`` resolves that
  322. circular dependency if you want to see how it's usually done)
  323. .. admonition:: Reusable apps and ``AUTH_USER_MODEL``
  324. Reusable apps shouldn't implement a custom user model. A project may use
  325. many apps, and two reusable apps that implemented a custom user model
  326. couldn't be used together. If you need to store per user information in your
  327. app, use a :class:`~django.db.models.ForeignKey` or
  328. :class:`~django.db.models.OneToOneField` to ``settings.AUTH_USER_MODEL``
  329. as described below.
  330. Referencing the ``User`` model
  331. ------------------------------
  332. .. currentmodule:: django.contrib.auth
  333. If you reference :class:`~django.contrib.auth.models.User` directly (for
  334. example, by referring to it in a foreign key), your code will not work in
  335. projects where the :setting:`AUTH_USER_MODEL` setting has been changed to a
  336. different User model.
  337. .. function:: get_user_model()
  338. Instead of referring to :class:`~django.contrib.auth.models.User` directly,
  339. you should reference the user model using
  340. ``django.contrib.auth.get_user_model()``. This method will return the
  341. currently active User model -- the custom User model if one is specified, or
  342. :class:`~django.contrib.auth.models.User` otherwise.
  343. When you define a foreign key or many-to-many relations to the User model,
  344. you should specify the custom model using the :setting:`AUTH_USER_MODEL`
  345. setting. For example::
  346. from django.conf import settings
  347. from django.db import models
  348. class Article(models.Model):
  349. author = models.ForeignKey(
  350. settings.AUTH_USER_MODEL,
  351. on_delete=models.CASCADE,
  352. )
  353. When connecting to signals sent by the ``User`` model, you should specify
  354. the custom model using the :setting:`AUTH_USER_MODEL` setting. For example::
  355. from django.conf import settings
  356. from django.db.models.signals import post_save
  357. def post_save_receiver(sender, instance, created, **kwargs):
  358. pass
  359. post_save.connect(post_save_receiver, sender=settings.AUTH_USER_MODEL)
  360. Generally speaking, you should reference the User model with the
  361. :setting:`AUTH_USER_MODEL` setting in code that is executed at import
  362. time. ``get_user_model()`` only works once Django has imported all models.
  363. .. _specifying-custom-user-model:
  364. Specifying a custom ``User`` model
  365. ----------------------------------
  366. .. admonition:: Model design considerations
  367. Think carefully before handling information not directly related to
  368. authentication in your custom User Model.
  369. It may be better to store app-specific user information in a model
  370. that has a relation with the User model. That allows each app to specify
  371. its own user data requirements without risking conflicts with other
  372. apps. On the other hand, queries to retrieve this related information
  373. will involve a database join, which may have an effect on performance.
  374. Django expects your custom User model to meet some minimum requirements.
  375. #. If you use the default authentication backend, then your model must have a
  376. single unique field that can be used for identification purposes. This can
  377. be a username, an email address, or any other unique attribute. A non-unique
  378. username field is allowed if you use a custom authentication backend that
  379. can support it.
  380. #. Your model must provide a way to address the user in a "short" and
  381. "long" form. The most common interpretation of this would be to use
  382. the user's given name as the "short" identifier, and the user's full
  383. name as the "long" identifier. However, there are no constraints on
  384. what these two methods return - if you want, they can return exactly
  385. the same value.
  386. The easiest way to construct a compliant custom User model is to inherit from
  387. :class:`~django.contrib.auth.models.AbstractBaseUser`.
  388. :class:`~django.contrib.auth.models.AbstractBaseUser` provides the core
  389. implementation of a ``User`` model, including hashed passwords and tokenized
  390. password resets. You must then provide some key implementation details:
  391. .. currentmodule:: django.contrib.auth
  392. .. class:: models.CustomUser
  393. .. attribute:: USERNAME_FIELD
  394. A string describing the name of the field on the User model that is
  395. used as the unique identifier. This will usually be a username of some
  396. kind, but it can also be an email address, or any other unique
  397. identifier. The field *must* be unique (i.e., have ``unique=True`` set
  398. in its definition), unless you use a custom authentication backend that
  399. can support non-unique usernames.
  400. In the following example, the field ``identifier`` is used
  401. as the identifying field::
  402. class MyUser(AbstractBaseUser):
  403. identifier = models.CharField(max_length=40, unique=True)
  404. ...
  405. USERNAME_FIELD = 'identifier'
  406. :attr:`USERNAME_FIELD` now supports
  407. :class:`~django.db.models.ForeignKey`\s. Since there is no way to pass
  408. model instances during the :djadmin:`createsuperuser` prompt, expect the
  409. user to enter the value of :attr:`~django.db.models.ForeignKey.to_field`
  410. value (the :attr:`~django.db.models.Field.primary_key` by default) of an
  411. existing instance.
  412. .. attribute:: REQUIRED_FIELDS
  413. A list of the field names that will be prompted for when creating a
  414. user via the :djadmin:`createsuperuser` management command. The user
  415. will be prompted to supply a value for each of these fields. It must
  416. include any field for which :attr:`~django.db.models.Field.blank` is
  417. ``False`` or undefined and may include additional fields you want
  418. prompted for when a user is created interactively.
  419. ``REQUIRED_FIELDS`` has no effect in other parts of Django, like
  420. creating a user in the admin.
  421. For example, here is the partial definition for a ``User`` model that
  422. defines two required fields - a date of birth and height::
  423. class MyUser(AbstractBaseUser):
  424. ...
  425. date_of_birth = models.DateField()
  426. height = models.FloatField()
  427. ...
  428. REQUIRED_FIELDS = ['date_of_birth', 'height']
  429. .. note::
  430. ``REQUIRED_FIELDS`` must contain all required fields on your
  431. ``User`` model, but should *not* contain the ``USERNAME_FIELD`` or
  432. ``password`` as these fields will always be prompted for.
  433. :attr:`REQUIRED_FIELDS` now supports
  434. :class:`~django.db.models.ForeignKey`\s. Since there is no way to pass
  435. model instances during the :djadmin:`createsuperuser` prompt, expect the
  436. user to enter the value of :attr:`~django.db.models.ForeignKey.to_field`
  437. value (the :attr:`~django.db.models.Field.primary_key` by default) of an
  438. existing instance.
  439. .. attribute:: is_active
  440. A boolean attribute that indicates whether the user is considered
  441. "active". This attribute is provided as an attribute on
  442. ``AbstractBaseUser`` defaulting to ``True``. How you choose to
  443. implement it will depend on the details of your chosen auth backends.
  444. See the documentation of the :attr:`is_active attribute on the built-in
  445. user model <django.contrib.auth.models.User.is_active>` for details.
  446. .. method:: get_full_name()
  447. A longer formal identifier for the user. A common interpretation
  448. would be the full name of the user, but it can be any string that
  449. identifies the user.
  450. .. method:: get_short_name()
  451. A short, informal identifier for the user. A common interpretation
  452. would be the first name of the user, but it can be any string that
  453. identifies the user in an informal way. It may also return the same
  454. value as :meth:`django.contrib.auth.models.User.get_full_name()`.
  455. .. admonition:: Importing ``AbstractBaseUser``
  456. ``AbstractBaseUser`` and ``BaseUserManager`` are importable from
  457. ``django.contrib.auth.base_user`` so that they can be imported without
  458. including ``django.contrib.auth`` in :setting:`INSTALLED_APPS`.
  459. The following attributes and methods are available on any subclass of
  460. :class:`~django.contrib.auth.models.AbstractBaseUser`:
  461. .. class:: models.AbstractBaseUser
  462. .. method:: get_username()
  463. Returns the value of the field nominated by ``USERNAME_FIELD``.
  464. .. attribute:: models.AbstractBaseUser.is_authenticated
  465. Read-only attribute which is always ``True`` (as opposed to
  466. ``AnonymousUser.is_authenticated`` which is always ``False``).
  467. This is a way to tell if the user has been authenticated. This does not
  468. imply any permissions and doesn't check if the user is active or has
  469. a valid session. Even though normally you will check this attribute on
  470. ``request.user`` to find out whether it has been populated by the
  471. :class:`~django.contrib.auth.middleware.AuthenticationMiddleware`
  472. (representing the currently logged-in user), you should know this
  473. attribute is ``True`` for any :class:`~models.User` instance.
  474. .. versionchanged:: 1.10
  475. In older versions, this was a method. Backwards-compatibility
  476. support for using it as a method will be removed in Django 2.0.
  477. .. attribute:: models.AbstractBaseUser.is_anonymous
  478. Read-only attribute which is always ``False``. This is a way of
  479. differentiating :class:`~models.User` and :class:`~models.AnonymousUser`
  480. objects. Generally, you should prefer using
  481. :attr:`~models.User.is_authenticated` to this attribute.
  482. .. versionchanged:: 1.10
  483. In older versions, this was a method. Backwards-compatibility
  484. support for using it as a method will be removed in Django 2.0.
  485. .. method:: models.AbstractBaseUser.set_password(raw_password)
  486. Sets the user's password to the given raw string, taking care of the
  487. password hashing. Doesn't save the
  488. :class:`~django.contrib.auth.models.AbstractBaseUser` object.
  489. When the raw_password is ``None``, the password will be set to an
  490. unusable password, as if
  491. :meth:`~django.contrib.auth.models.AbstractBaseUser.set_unusable_password()`
  492. were used.
  493. .. method:: models.AbstractBaseUser.check_password(raw_password)
  494. Returns ``True`` if the given raw string is the correct password for
  495. the user. (This takes care of the password hashing in making the
  496. comparison.)
  497. .. method:: models.AbstractBaseUser.set_unusable_password()
  498. Marks the user as having no password set. This isn't the same as
  499. having a blank string for a password.
  500. :meth:`~django.contrib.auth.models.AbstractBaseUser.check_password()` for this user
  501. will never return ``True``. Doesn't save the
  502. :class:`~django.contrib.auth.models.AbstractBaseUser` object.
  503. You may need this if authentication for your application takes place
  504. against an existing external source such as an LDAP directory.
  505. .. method:: models.AbstractBaseUser.has_usable_password()
  506. Returns ``False`` if
  507. :meth:`~django.contrib.auth.models.AbstractBaseUser.set_unusable_password()` has
  508. been called for this user.
  509. .. method:: models.AbstractBaseUser.get_session_auth_hash()
  510. Returns an HMAC of the password field. Used for
  511. :ref:`session-invalidation-on-password-change`.
  512. You should also define a custom manager for your ``User`` model. If your
  513. ``User`` model defines ``username``, ``email``, ``is_staff``, ``is_active``,
  514. ``is_superuser``, ``last_login``, and ``date_joined`` fields the same as
  515. Django's default ``User``, you can just install Django's
  516. :class:`~django.contrib.auth.models.UserManager`; however, if your ``User``
  517. model defines different fields, you will need to define a custom manager that
  518. extends :class:`~django.contrib.auth.models.BaseUserManager` providing two
  519. additional methods:
  520. .. class:: models.CustomUserManager
  521. .. method:: models.CustomUserManager.create_user(*username_field*, password=None, \**other_fields)
  522. The prototype of ``create_user()`` should accept the username field,
  523. plus all required fields as arguments. For example, if your user model
  524. uses ``email`` as the username field, and has ``date_of_birth`` as a
  525. required field, then ``create_user`` should be defined as::
  526. def create_user(self, email, date_of_birth, password=None):
  527. # create user here
  528. ...
  529. .. method:: models.CustomUserManager.create_superuser(*username_field*, password, \**other_fields)
  530. The prototype of ``create_superuser()`` should accept the username
  531. field, plus all required fields as arguments. For example, if your user
  532. model uses ``email`` as the username field, and has ``date_of_birth``
  533. as a required field, then ``create_superuser`` should be defined as::
  534. def create_superuser(self, email, date_of_birth, password):
  535. # create superuser here
  536. ...
  537. Unlike ``create_user()``, ``create_superuser()`` *must* require the
  538. caller to provide a password.
  539. :class:`~django.contrib.auth.models.BaseUserManager` provides the following
  540. utility methods:
  541. .. class:: models.BaseUserManager
  542. .. classmethod:: models.BaseUserManager.normalize_email(email)
  543. Normalizes email addresses by lowercasing the domain portion of the
  544. email address.
  545. .. classmethod:: models.BaseUserManager.normalize_username(email)
  546. .. versionadded:: 1.10
  547. Applies NFKC Unicode normalization to usernames so that visually
  548. identical characters with different Unicode code points are considered
  549. identical.
  550. .. method:: models.BaseUserManager.get_by_natural_key(username)
  551. Retrieves a user instance using the contents of the field
  552. nominated by ``USERNAME_FIELD``.
  553. .. method:: models.BaseUserManager.make_random_password(length=10, allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789')
  554. Returns a random password with the given length and given string of
  555. allowed characters. Note that the default value of ``allowed_chars``
  556. doesn't contain letters that can cause user confusion, including:
  557. * ``i``, ``l``, ``I``, and ``1`` (lowercase letter i, lowercase
  558. letter L, uppercase letter i, and the number one)
  559. * ``o``, ``O``, and ``0`` (lowercase letter o, uppercase letter o,
  560. and zero)
  561. Extending Django's default ``User``
  562. -----------------------------------
  563. If you're entirely happy with Django's :class:`~django.contrib.auth.models.User`
  564. model and you just want to add some additional profile information, you could
  565. simply subclass ``django.contrib.auth.models.AbstractUser`` and add your
  566. custom profile fields, although we'd recommend a separate model as described in
  567. the "Model design considerations" note of :ref:`specifying-custom-user-model`.
  568. ``AbstractUser`` provides the full implementation of the default
  569. :class:`~django.contrib.auth.models.User` as an :ref:`abstract model
  570. <abstract-base-classes>`.
  571. .. _custom-users-and-the-built-in-auth-forms:
  572. Custom users and the built-in auth forms
  573. ----------------------------------------
  574. Django's built-in :ref:`forms <built-in-auth-forms>` and :ref:`views
  575. <built-in-auth-views>` make certain assumptions about the user model that they
  576. are working with.
  577. The following forms are compatible with any subclass of
  578. :class:`~django.contrib.auth.models.AbstractBaseUser`:
  579. * :class:`~django.contrib.auth.forms.AuthenticationForm`: Uses the username
  580. field specified by :attr:`~models.CustomUser.USERNAME_FIELD`.
  581. * :class:`~django.contrib.auth.forms.SetPasswordForm`
  582. * :class:`~django.contrib.auth.forms.PasswordChangeForm`
  583. * :class:`~django.contrib.auth.forms.AdminPasswordChangeForm`
  584. The following forms make assumptions about the user model and can be used as-is
  585. if those assumptions are met:
  586. * :class:`~django.contrib.auth.forms.PasswordResetForm`: Assumes that the user
  587. model has a field named ``email`` that can be used to identify the user and a
  588. boolean field named ``is_active`` to prevent password resets for inactive
  589. users.
  590. Finally, the following forms are tied to
  591. :class:`~django.contrib.auth.models.User` and need to be rewritten or extended
  592. to work with a custom user model:
  593. * :class:`~django.contrib.auth.forms.UserCreationForm`
  594. * :class:`~django.contrib.auth.forms.UserChangeForm`
  595. If your custom user model is a simple subclass of ``AbstractUser``, then you
  596. can extend these forms in this manner::
  597. from django.contrib.auth.forms import UserCreationForm
  598. from myapp.models import CustomUser
  599. class CustomUserCreationForm(UserCreationForm):
  600. class Meta(UserCreationForm.Meta):
  601. model = CustomUser
  602. fields = UserCreationForm.Meta.fields + ('custom_field',)
  603. Custom users and :mod:`django.contrib.admin`
  604. --------------------------------------------
  605. If you want your custom User model to also work with Admin, your User model must
  606. define some additional attributes and methods. These methods allow the admin to
  607. control access of the User to admin content:
  608. .. class:: models.CustomUser
  609. .. attribute:: is_staff
  610. Returns ``True`` if the user is allowed to have access to the admin site.
  611. .. attribute:: is_active
  612. Returns ``True`` if the user account is currently active.
  613. .. method:: has_perm(perm, obj=None):
  614. Returns ``True`` if the user has the named permission. If ``obj`` is
  615. provided, the permission needs to be checked against a specific object
  616. instance.
  617. .. method:: has_module_perms(app_label):
  618. Returns ``True`` if the user has permission to access models in
  619. the given app.
  620. You will also need to register your custom User model with the admin. If
  621. your custom User model extends ``django.contrib.auth.models.AbstractUser``,
  622. you can use Django's existing ``django.contrib.auth.admin.UserAdmin``
  623. class. However, if your User model extends
  624. :class:`~django.contrib.auth.models.AbstractBaseUser`, you'll need to define
  625. a custom ``ModelAdmin`` class. It may be possible to subclass the default
  626. ``django.contrib.auth.admin.UserAdmin``; however, you'll need to
  627. override any of the definitions that refer to fields on
  628. ``django.contrib.auth.models.AbstractUser`` that aren't on your
  629. custom User class.
  630. Custom users and permissions
  631. ----------------------------
  632. To make it easy to include Django's permission framework into your own User
  633. class, Django provides :class:`~django.contrib.auth.models.PermissionsMixin`.
  634. This is an abstract model you can include in the class hierarchy for your User
  635. model, giving you all the methods and database fields necessary to support
  636. Django's permission model.
  637. :class:`~django.contrib.auth.models.PermissionsMixin` provides the following
  638. methods and attributes:
  639. .. class:: models.PermissionsMixin
  640. .. attribute:: models.PermissionsMixin.is_superuser
  641. Boolean. Designates that this user has all permissions without
  642. explicitly assigning them.
  643. .. method:: models.PermissionsMixin.get_group_permissions(obj=None)
  644. Returns a set of permission strings that the user has, through their
  645. groups.
  646. If ``obj`` is passed in, only returns the group permissions for
  647. this specific object.
  648. .. method:: models.PermissionsMixin.get_all_permissions(obj=None)
  649. Returns a set of permission strings that the user has, both through
  650. group and user permissions.
  651. If ``obj`` is passed in, only returns the permissions for this
  652. specific object.
  653. .. method:: models.PermissionsMixin.has_perm(perm, obj=None)
  654. Returns ``True`` if the user has the specified permission, where
  655. ``perm`` is in the format ``"<app label>.<permission codename>"`` (see
  656. :ref:`permissions <topic-authorization>`). If the user is inactive, this method will
  657. always return ``False``.
  658. If ``obj`` is passed in, this method won't check for a permission for
  659. the model, but for this specific object.
  660. .. method:: models.PermissionsMixin.has_perms(perm_list, obj=None)
  661. Returns ``True`` if the user has each of the specified permissions,
  662. where each perm is in the format
  663. ``"<app label>.<permission codename>"``. If the user is inactive,
  664. this method will always return ``False``.
  665. If ``obj`` is passed in, this method won't check for permissions for
  666. the model, but for the specific object.
  667. .. method:: models.PermissionsMixin.has_module_perms(package_name)
  668. Returns ``True`` if the user has any permissions in the given package
  669. (the Django app label). If the user is inactive, this method will
  670. always return ``False``.
  671. .. admonition:: ``PermissionsMixin`` and ``ModelBackend``
  672. If you don't include the
  673. :class:`~django.contrib.auth.models.PermissionsMixin`, you must ensure you
  674. don't invoke the permissions methods on ``ModelBackend``. ``ModelBackend``
  675. assumes that certain fields are available on your user model. If your
  676. ``User`` model doesn't provide those fields, you will receive database
  677. errors when you check permissions.
  678. Custom users and proxy models
  679. -----------------------------
  680. One limitation of custom User models is that installing a custom User model
  681. will break any proxy model extending :class:`~django.contrib.auth.models.User`.
  682. Proxy models must be based on a concrete base class; by defining a custom User
  683. model, you remove the ability of Django to reliably identify the base class.
  684. If your project uses proxy models, you must either modify the proxy to extend
  685. the User model that is currently in use in your project, or merge your proxy's
  686. behavior into your User subclass.
  687. A full example
  688. --------------
  689. Here is an example of an admin-compliant custom user app. This user model uses
  690. an email address as the username, and has a required date of birth; it
  691. provides no permission checking, beyond a simple ``admin`` flag on the user
  692. account. This model would be compatible with all the built-in auth forms and
  693. views, except for the User creation forms. This example illustrates how most of
  694. the components work together, but is not intended to be copied directly into
  695. projects for production use.
  696. This code would all live in a ``models.py`` file for a custom
  697. authentication app::
  698. from django.db import models
  699. from django.contrib.auth.models import (
  700. BaseUserManager, AbstractBaseUser
  701. )
  702. class MyUserManager(BaseUserManager):
  703. def create_user(self, email, date_of_birth, password=None):
  704. """
  705. Creates and saves a User with the given email, date of
  706. birth and password.
  707. """
  708. if not email:
  709. raise ValueError('Users must have an email address')
  710. user = self.model(
  711. email=self.normalize_email(email),
  712. date_of_birth=date_of_birth,
  713. )
  714. user.set_password(password)
  715. user.save(using=self._db)
  716. return user
  717. def create_superuser(self, email, date_of_birth, password):
  718. """
  719. Creates and saves a superuser with the given email, date of
  720. birth and password.
  721. """
  722. user = self.create_user(email,
  723. password=password,
  724. date_of_birth=date_of_birth
  725. )
  726. user.is_admin = True
  727. user.save(using=self._db)
  728. return user
  729. class MyUser(AbstractBaseUser):
  730. email = models.EmailField(
  731. verbose_name='email address',
  732. max_length=255,
  733. unique=True,
  734. )
  735. date_of_birth = models.DateField()
  736. is_active = models.BooleanField(default=True)
  737. is_admin = models.BooleanField(default=False)
  738. objects = MyUserManager()
  739. USERNAME_FIELD = 'email'
  740. REQUIRED_FIELDS = ['date_of_birth']
  741. def get_full_name(self):
  742. # The user is identified by their email address
  743. return self.email
  744. def get_short_name(self):
  745. # The user is identified by their email address
  746. return self.email
  747. def __str__(self): # __unicode__ on Python 2
  748. return self.email
  749. def has_perm(self, perm, obj=None):
  750. "Does the user have a specific permission?"
  751. # Simplest possible answer: Yes, always
  752. return True
  753. def has_module_perms(self, app_label):
  754. "Does the user have permissions to view the app `app_label`?"
  755. # Simplest possible answer: Yes, always
  756. return True
  757. @property
  758. def is_staff(self):
  759. "Is the user a member of staff?"
  760. # Simplest possible answer: All admins are staff
  761. return self.is_admin
  762. Then, to register this custom User model with Django's admin, the following
  763. code would be required in the app's ``admin.py`` file::
  764. from django import forms
  765. from django.contrib import admin
  766. from django.contrib.auth.models import Group
  767. from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
  768. from django.contrib.auth.forms import ReadOnlyPasswordHashField
  769. from customauth.models import MyUser
  770. class UserCreationForm(forms.ModelForm):
  771. """A form for creating new users. Includes all the required
  772. fields, plus a repeated password."""
  773. password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
  774. password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
  775. class Meta:
  776. model = MyUser
  777. fields = ('email', 'date_of_birth')
  778. def clean_password2(self):
  779. # Check that the two password entries match
  780. password1 = self.cleaned_data.get("password1")
  781. password2 = self.cleaned_data.get("password2")
  782. if password1 and password2 and password1 != password2:
  783. raise forms.ValidationError("Passwords don't match")
  784. return password2
  785. def save(self, commit=True):
  786. # Save the provided password in hashed format
  787. user = super(UserCreationForm, self).save(commit=False)
  788. user.set_password(self.cleaned_data["password1"])
  789. if commit:
  790. user.save()
  791. return user
  792. class UserChangeForm(forms.ModelForm):
  793. """A form for updating users. Includes all the fields on
  794. the user, but replaces the password field with admin's
  795. password hash display field.
  796. """
  797. password = ReadOnlyPasswordHashField()
  798. class Meta:
  799. model = MyUser
  800. fields = ('email', 'password', 'date_of_birth', 'is_active', 'is_admin')
  801. def clean_password(self):
  802. # Regardless of what the user provides, return the initial value.
  803. # This is done here, rather than on the field, because the
  804. # field does not have access to the initial value
  805. return self.initial["password"]
  806. class UserAdmin(BaseUserAdmin):
  807. # The forms to add and change user instances
  808. form = UserChangeForm
  809. add_form = UserCreationForm
  810. # The fields to be used in displaying the User model.
  811. # These override the definitions on the base UserAdmin
  812. # that reference specific fields on auth.User.
  813. list_display = ('email', 'date_of_birth', 'is_admin')
  814. list_filter = ('is_admin',)
  815. fieldsets = (
  816. (None, {'fields': ('email', 'password')}),
  817. ('Personal info', {'fields': ('date_of_birth',)}),
  818. ('Permissions', {'fields': ('is_admin',)}),
  819. )
  820. # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
  821. # overrides get_fieldsets to use this attribute when creating a user.
  822. add_fieldsets = (
  823. (None, {
  824. 'classes': ('wide',),
  825. 'fields': ('email', 'date_of_birth', 'password1', 'password2')}
  826. ),
  827. )
  828. search_fields = ('email',)
  829. ordering = ('email',)
  830. filter_horizontal = ()
  831. # Now register the new UserAdmin...
  832. admin.site.register(MyUser, UserAdmin)
  833. # ... and, since we're not using Django's built-in permissions,
  834. # unregister the Group model from admin.
  835. admin.site.unregister(Group)
  836. Finally, specify the custom model as the default user model for your project
  837. using the :setting:`AUTH_USER_MODEL` setting in your ``settings.py``::
  838. AUTH_USER_MODEL = 'customauth.MyUser'