customizing.txt 45 KB

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