customizing.txt 49 KB

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