customizing.txt 49 KB

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