customizing.txt 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082
  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 extendible 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>` above -- 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 tuple 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. .. note::
  56. Once a user has authenticated, Django stores which backend was used to
  57. authenticate the user in the user's session, and re-uses the same backend
  58. for the duration of that session whenever access to the currently
  59. authenticated user is needed. This effectively means that authentication
  60. sources are cached on a per-session basis, so if you change
  61. :setting:`AUTHENTICATION_BACKENDS`, you'll need to clear out session data if
  62. you need to force users to re-authenticate using different methods. A simple
  63. way to do that is simply to execute ``Session.objects.all().delete()``.
  64. .. versionadded:: 1.6
  65. If a backend raises a :class:`~django.core.exceptions.PermissionDenied`
  66. exception, authentication will immediately fail. Django won't check the
  67. backends that follow.
  68. Writing an authentication backend
  69. ---------------------------------
  70. An authentication backend is a class that implements two required methods:
  71. ``get_user(user_id)`` and ``authenticate(**credentials)``, as well as a set of
  72. optional permission related :ref:`authorization methods <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 credentials as keyword arguments. Most of
  77. the time, it'll just look like this::
  78. class MyBackend(object):
  79. def authenticate(self, 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, 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. The Django admin system is tightly coupled to the Django ``User`` object
  91. described at the beginning of this document. For now, the best way to deal with
  92. this is to create a Django ``User`` object for each user that exists for your
  93. backend (e.g., in your LDAP directory, your external SQL database, etc.) You
  94. can either write a script to do this in advance, or your ``authenticate``
  95. method can do it the first time a user logs in.
  96. Here's an example backend that authenticates against a username and password
  97. variable defined in your ``settings.py`` file and creates a Django ``User``
  98. object the first time a user authenticates::
  99. from django.conf import settings
  100. from django.contrib.auth.models import User, check_password
  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 = 'sha1$4e987$afbcf42e21bd417fb71db8c66b321e9fc33051de'
  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. The simple backend above could implement permissions for the magic admin
  143. fairly simply::
  144. class SettingsBackend(object):
  145. ...
  146. def has_perm(self, user_obj, perm, obj=None):
  147. if user_obj.username == settings.ADMIN_LOGIN:
  148. return True
  149. else:
  150. return False
  151. This gives full permissions to the user granted access in the above example.
  152. Notice that in addition to the same arguments given to the associated
  153. :class:`django.contrib.auth.models.User` functions, the backend auth functions
  154. all take the user object, which may be an anonymous user, as an argument.
  155. A full authorization implementation can be found in the ``ModelBackend`` class
  156. in `django/contrib/auth/backends.py`_, which is the default backend and queries
  157. the ``auth_permission`` table most of the time. If you wish to provide
  158. custom behavior for only part of the backend API, you can take advantage of
  159. Python inheritance and subclass ``ModelBackend`` instead of implementing the
  160. complete API in a custom backend.
  161. .. _django/contrib/auth/backends.py: https://github.com/django/django/blob/master/django/contrib/auth/backends.py
  162. .. _anonymous_auth:
  163. Authorization for anonymous users
  164. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  165. An anonymous user is one that is not authenticated i.e. they have provided no
  166. valid authentication details. However, that does not necessarily mean they are
  167. not authorized to do anything. At the most basic level, most Web sites
  168. authorize anonymous users to browse most of the site, and many allow anonymous
  169. posting of comments etc.
  170. Django's permission framework does not have a place to store permissions for
  171. anonymous users. However, the user object passed to an authentication backend
  172. may be an :class:`django.contrib.auth.models.AnonymousUser` object, allowing
  173. the backend to specify custom authorization behavior for anonymous users. This
  174. is especially useful for the authors of re-usable apps, who can delegate all
  175. questions of authorization to the auth backend, rather than needing settings,
  176. for example, to control anonymous access.
  177. .. _inactive_auth:
  178. Authorization for inactive users
  179. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  180. An inactive user is a one that is authenticated but has its attribute
  181. ``is_active`` set to ``False``. However this does not mean they are not
  182. authorized to do anything. For example they are allowed to activate their
  183. account.
  184. The support for anonymous users in the permission system allows for a scenario
  185. where anonymous users have permissions to do something while inactive
  186. authenticated users do not.
  187. Do not forget to test for the ``is_active`` attribute of the user in your own
  188. backend permission methods.
  189. Handling object permissions
  190. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  191. Django's permission framework has a foundation for object permissions, though
  192. there is no implementation for it in the core. That means that checking for
  193. object permissions will always return ``False`` or an empty list (depending on
  194. the check performed). An authentication backend will receive the keyword
  195. parameters ``obj`` and ``user_obj`` for each object related authorization
  196. method and can return the object level permission as appropriate.
  197. .. _custom-permissions:
  198. Custom permissions
  199. ==================
  200. To create custom permissions for a given model object, use the ``permissions``
  201. :ref:`model Meta attribute <meta-options>`.
  202. This example Task model creates three custom permissions, i.e., actions users
  203. can or cannot do with Task instances, specific to your application::
  204. class Task(models.Model):
  205. ...
  206. class Meta:
  207. permissions = (
  208. ("view_task", "Can see available tasks"),
  209. ("change_task_status", "Can change the status of tasks"),
  210. ("close_task", "Can remove a task by setting its status as closed"),
  211. )
  212. The only thing this does is create those extra permissions when you run
  213. :djadmin:`manage.py syncdb <syncdb>`. Your code is in charge of checking the
  214. value of these permissions when an user is trying to access the functionality
  215. provided by the application (viewing tasks, changing the status of tasks,
  216. closing tasks.) Continuing the above example, the following checks if a user may
  217. view tasks::
  218. user.has_perm('app.view_task')
  219. .. _extending-user:
  220. Extending the existing User model
  221. =================================
  222. There are two ways to extend the default
  223. :class:`~django.contrib.auth.models.User` model without substituting your own
  224. model. If the changes you need are purely behavioral, and don't require any
  225. change to what is stored in the database, you can create a :ref:`proxy model
  226. <proxy-models>` based on :class:`~django.contrib.auth.models.User`. This
  227. allows for any of the features offered by proxy models including default
  228. ordering, custom managers, or custom model methods.
  229. If you wish to store information related to ``User``, you can use a :ref:`one-to-one
  230. relationship <ref-onetoone>` to a model containing the fields for
  231. additional information. This one-to-one model is often called a profile model,
  232. as it might store non-auth related information about a site user. For example
  233. you might create an Employee model::
  234. from django.contrib.auth.models import User
  235. class Employee(models.Model):
  236. user = models.OneToOneField(User)
  237. department = models.CharField(max_length=100)
  238. Assuming an existing Employee Fred Smith who has both a User and Employee
  239. model, you can access the related information using Django's standard related
  240. model conventions::
  241. >>> u = User.objects.get(username='fsmith')
  242. >>> freds_department = u.employee.department
  243. To add a profile model's fields to the user page in the admin, define an
  244. :class:`~django.contrib.admin.InlineModelAdmin` (for this example, we'll use a
  245. :class:`~django.contrib.admin.StackedInline`) in your app's ``admin.py`` and
  246. add it to a ``UserAdmin`` class which is registered with the
  247. :class:`~django.contrib.auth.models.User` class::
  248. from django.contrib import admin
  249. from django.contrib.auth.admin import UserAdmin
  250. from django.contrib.auth.models import User
  251. from my_user_profile_app.models import Employee
  252. # Define an inline admin descriptor for Employee model
  253. # which acts a bit like a singleton
  254. class EmployeeInline(admin.StackedInline):
  255. model = Employee
  256. can_delete = False
  257. verbose_name_plural = 'employee'
  258. # Define a new User admin
  259. class UserAdmin(UserAdmin):
  260. inlines = (EmployeeInline, )
  261. # Re-register UserAdmin
  262. admin.site.unregister(User)
  263. admin.site.register(User, UserAdmin)
  264. These profile models are not special in any way - they are just Django models that
  265. happen to have a one-to-one link with a User model. As such, they do not get
  266. auto created when a user is created, but
  267. a :attr:`django.db.models.signals.post_save` could be used to create or update
  268. related models as appropriate.
  269. Note that using related models results in additional queries or joins to
  270. retrieve the related data, and depending on your needs substituting the User
  271. model and adding the related fields may be your better option. However
  272. existing links to the default User model within your project's apps may justify
  273. the extra database load.
  274. .. _auth-custom-user:
  275. Substituting a custom User model
  276. ================================
  277. Some kinds of projects may have authentication requirements for which Django's
  278. built-in :class:`~django.contrib.auth.models.User` model is not always
  279. appropriate. For instance, on some sites it makes more sense to use an email
  280. address as your identification token instead of a username.
  281. Django allows you to override the default User model by providing a value for
  282. the :setting:`AUTH_USER_MODEL` setting that references a custom model::
  283. AUTH_USER_MODEL = 'myapp.MyUser'
  284. This dotted pair describes the name of the Django app (which must be in your
  285. :setting:`INSTALLED_APPS`), and the name of the Django model that you wish to
  286. use as your User model.
  287. .. warning::
  288. Changing :setting:`AUTH_USER_MODEL` has a big effect on your database
  289. structure. It changes the tables that are available, and it will affect the
  290. construction of foreign keys and many-to-many relationships. If you intend
  291. to set :setting:`AUTH_USER_MODEL`, you should set it before running
  292. ``manage.py syncdb`` for the first time.
  293. If you have an existing project and you want to migrate to using a custom
  294. User model, you may need to look into using a migration tool like South_
  295. to ease the transition.
  296. .. _South: http://south.aeracode.org
  297. Referencing the User model
  298. --------------------------
  299. .. currentmodule:: django.contrib.auth
  300. If you reference :class:`~django.contrib.auth.models.User` directly (for
  301. example, by referring to it in a foreign key), your code will not work in
  302. projects where the :setting:`AUTH_USER_MODEL` setting has been changed to a
  303. different User model.
  304. .. function:: get_user_model()
  305. Instead of referring to :class:`~django.contrib.auth.models.User` directly,
  306. you should reference the user model using
  307. ``django.contrib.auth.get_user_model()``. This method will return the
  308. currently active User model -- the custom User model if one is specified, or
  309. :class:`~django.contrib.auth.models.User` otherwise.
  310. When you define a foreign key or many-to-many relations to the User model,
  311. you should specify the custom model using the :setting:`AUTH_USER_MODEL`
  312. setting. For example::
  313. from django.conf import settings
  314. from django.db import models
  315. class Article(models.Model):
  316. author = models.ForeignKey(settings.AUTH_USER_MODEL)
  317. Specifying a custom User model
  318. ------------------------------
  319. .. admonition:: Model design considerations
  320. Think carefully before handling information not directly related to
  321. authentication in your custom User Model.
  322. It may be better to store app-specific user information in a model
  323. that has a relation with the User model. That allows each app to specify
  324. its own user data requirements without risking conflicts with other
  325. apps. On the other hand, queries to retrieve this related information
  326. will involve a database join, which may have an effect on performance.
  327. Django expects your custom User model to meet some minimum requirements.
  328. 1. Your model must have an integer primary key.
  329. 2. Your model must have a single unique field that can be used for
  330. identification purposes. This can be a username, an email address,
  331. or any other unique attribute.
  332. 3. Your model must provide a way to address the user in a "short" and
  333. "long" form. The most common interpretation of this would be to use
  334. the user's given name as the "short" identifier, and the user's full
  335. name as the "long" identifier. However, there are no constraints on
  336. what these two methods return - if you want, they can return exactly
  337. the same value.
  338. The easiest way to construct a compliant custom User model is to inherit from
  339. :class:`~django.contrib.auth.models.AbstractBaseUser`.
  340. :class:`~django.contrib.auth.models.AbstractBaseUser` provides the core
  341. implementation of a ``User`` model, including hashed passwords and tokenized
  342. password resets. You must then provide some key implementation details:
  343. .. currentmodule:: django.contrib.auth
  344. .. class:: models.CustomUser
  345. .. attribute:: USERNAME_FIELD
  346. A string describing the name of the field on the User model that is
  347. used as the unique identifier. This will usually be a username of
  348. some kind, but it can also be an email address, or any other unique
  349. identifier. The field *must* be unique (i.e., have ``unique=True``
  350. set in its definition).
  351. In the following example, the field ``identifier`` is used
  352. as the identifying field::
  353. class MyUser(AbstractBaseUser):
  354. identifier = models.CharField(max_length=40, unique=True, db_index=True)
  355. ...
  356. USERNAME_FIELD = 'identifier'
  357. .. attribute:: REQUIRED_FIELDS
  358. A list of the field names that *must* be provided when creating a user
  359. via the :djadmin:`createsuperuser` management command. The user will be
  360. prompted to supply a value for each of these fields. It should include
  361. any field for which :attr:`~django.db.models.Field.blank` is ``False``
  362. or undefined, but may include additional fields you want prompted for
  363. when a user is created interactively. However, it will not work for
  364. :class:`~django.db.models.ForeignKey` fields.
  365. For example, here is the partial definition for a ``User`` model that
  366. defines two required fields - a date of birth and height::
  367. class MyUser(AbstractBaseUser):
  368. ...
  369. date_of_birth = models.DateField()
  370. height = models.FloatField()
  371. ...
  372. REQUIRED_FIELDS = ['date_of_birth', 'height']
  373. .. note::
  374. ``REQUIRED_FIELDS`` must contain all required fields on your User
  375. model, but should *not* contain the ``USERNAME_FIELD``.
  376. .. attribute:: is_active
  377. A boolean attribute that indicates whether the user is considered
  378. "active". This attribute is provided as an attribute on
  379. ``AbstractBaseUser`` defaulting to ``True``. How you choose to
  380. implement it will depend on the details of your chosen auth backends.
  381. See the documentation of the :attr:`attribute on the builtin user model
  382. <django.contrib.auth.models.User.is_active>` for details.
  383. .. method:: get_full_name()
  384. A longer formal identifier for the user. A common interpretation
  385. would be the full name name of the user, but it can be any string that
  386. identifies the user.
  387. .. method:: get_short_name()
  388. A short, informal identifier for the user. A common interpretation
  389. would be the first name of the user, but it can be any string that
  390. identifies the user in an informal way. It may also return the same
  391. value as :meth:`django.contrib.auth.models.User.get_full_name()`.
  392. The following methods are available on any subclass of
  393. :class:`~django.contrib.auth.models.AbstractBaseUser`:
  394. .. class:: models.AbstractBaseUser
  395. .. method:: get_username()
  396. Returns the value of the field nominated by ``USERNAME_FIELD``.
  397. .. method:: models.AbstractBaseUser.is_anonymous()
  398. Always returns ``False``. This is a way of differentiating
  399. from :class:`~django.contrib.auth.models.AnonymousUser` objects.
  400. Generally, you should prefer using
  401. :meth:`~django.contrib.auth.models.AbstractBaseUser.is_authenticated()` to this
  402. method.
  403. .. method:: models.AbstractBaseUser.is_authenticated()
  404. Always returns ``True``. This is a way to tell if the user has been
  405. authenticated. This does not imply any permissions, and doesn't check
  406. if the user is active - it only indicates that the user has provided a
  407. valid username and password.
  408. .. method:: models.AbstractBaseUser.set_password(raw_password)
  409. Sets the user's password to the given raw string, taking care of the
  410. password hashing. Doesn't save the
  411. :class:`~django.contrib.auth.models.AbstractBaseUser` object.
  412. When the raw_password is ``None``, the password will be set to an
  413. unusable password, as if
  414. :meth:`~django.contrib.auth.models.AbstractBaseUser.set_unusable_password()`
  415. were used.
  416. .. versionchanged:: 1.6
  417. In Django 1.4 and 1.5, a blank string was unintentionally stored
  418. as an unsable password as well.
  419. .. method:: models.AbstractBaseUser.check_password(raw_password)
  420. Returns ``True`` if the given raw string is the correct password for
  421. the user. (This takes care of the password hashing in making the
  422. comparison.)
  423. .. versionchanged:: 1.6
  424. In Django 1.4 and 1.5, a blank string was unintentionally
  425. considered to be an unusable password, resulting in this method
  426. returning ``False`` for such a password.
  427. .. method:: models.AbstractBaseUser.set_unusable_password()
  428. Marks the user as having no password set. This isn't the same as
  429. having a blank string for a password.
  430. :meth:`~django.contrib.auth.models.AbstractBaseUser.check_password()` for this user
  431. will never return ``True``. Doesn't save the
  432. :class:`~django.contrib.auth.models.AbstractBaseUser` object.
  433. You may need this if authentication for your application takes place
  434. against an existing external source such as an LDAP directory.
  435. .. method:: models.AbstractBaseUser.has_usable_password()
  436. Returns ``False`` if
  437. :meth:`~django.contrib.auth.models.AbstractBaseUser.set_unusable_password()` has
  438. been called for this user.
  439. You should also define a custom manager for your ``User`` model. If your
  440. ``User`` model defines ``username``, ``email``, ``is_staff``, ``is_active``,
  441. ``is_superuser``, ``last_login``, and ``date_joined`` fields the same as
  442. Django's default ``User``, you can just install Django's
  443. :class:`~django.contrib.auth.models.UserManager`; however, if your ``User``
  444. model defines different fields, you will need to define a custom manager that
  445. extends :class:`~django.contrib.auth.models.BaseUserManager` providing two
  446. additional methods:
  447. .. class:: models.CustomUserManager
  448. .. method:: models.CustomUserManager.create_user(*username_field*, password=None, \**other_fields)
  449. The prototype of ``create_user()`` should accept the username field,
  450. plus all required fields as arguments. For example, if your user model
  451. uses ``email`` as the username field, and has ``date_of_birth`` as a
  452. required fields, then ``create_user`` should be defined as::
  453. def create_user(self, email, date_of_birth, password=None):
  454. # create user here
  455. ...
  456. .. method:: models.CustomUserManager.create_superuser(*username_field*, password, \**other_fields)
  457. The prototype of ``create_superuser()`` should accept the username
  458. field, plus all required fields as arguments. For example, if your user
  459. model uses ``email`` as the username field, and has ``date_of_birth``
  460. as a required fields, then ``create_superuser`` should be defined as::
  461. def create_superuser(self, email, date_of_birth, password):
  462. # create superuser here
  463. ...
  464. Unlike ``create_user()``, ``create_superuser()`` *must* require the
  465. caller to provider a password.
  466. :class:`~django.contrib.auth.models.BaseUserManager` provides the following
  467. utility methods:
  468. .. class:: models.BaseUserManager
  469. .. method:: models.BaseUserManager.normalize_email(email)
  470. A classmethod that normalizes email addresses by lowercasing
  471. the domain portion of the email address.
  472. .. method:: models.BaseUserManager.get_by_natural_key(username)
  473. Retrieves a user instance using the contents of the field
  474. nominated by ``USERNAME_FIELD``.
  475. .. method:: models.BaseUserManager.make_random_password(length=10, allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789')
  476. Returns a random password with the given length and given string of
  477. allowed characters. (Note that the default value of ``allowed_chars``
  478. doesn't contain letters that can cause user confusion, including:
  479. * ``i``, ``l``, ``I``, and ``1`` (lowercase letter i, lowercase
  480. letter L, uppercase letter i, and the number one)
  481. * ``o``, ``O``, and ``0`` (uppercase letter o, lowercase letter o,
  482. and zero)
  483. Extending Django's default User
  484. -------------------------------
  485. If you're entirely happy with Django's :class:`~django.contrib.auth.models.User`
  486. model and you just want to add some additional profile information, you can
  487. simply subclass ``django.contrib.auth.models.AbstractUser`` and add your
  488. custom profile fields. This class provides the full implementation of the
  489. default :class:`~django.contrib.auth.models.User` as an :ref:`abstract model
  490. <abstract-base-classes>`.
  491. .. _custom-users-and-the-built-in-auth-forms:
  492. Custom users and the built-in auth forms
  493. ----------------------------------------
  494. As you may expect, built-in Django's :ref:`forms <built-in-auth-forms>` and
  495. :ref:`views <built-in-auth-views>` make certain assumptions about the user
  496. model that they are working with.
  497. If your user model doesn't follow the same assumptions, it may be necessary to define
  498. a replacement form, and pass that form in as part of the configuration of the
  499. auth views.
  500. * :class:`~django.contrib.auth.forms.UserCreationForm`
  501. Depends on the :class:`~django.contrib.auth.models.User` model.
  502. Must be re-written for any custom user model.
  503. * :class:`~django.contrib.auth.forms.UserChangeForm`
  504. Depends on the :class:`~django.contrib.auth.models.User` model.
  505. Must be re-written for any custom user model.
  506. * :class:`~django.contrib.auth.forms.AuthenticationForm`
  507. Works with any subclass of :class:`~django.contrib.auth.models.AbstractBaseUser`,
  508. and will adapt to use the field defined in ``USERNAME_FIELD``.
  509. * :class:`~django.contrib.auth.forms.PasswordResetForm`
  510. Assumes that the user model has an integer primary key, has a field named
  511. ``email`` that can be used to identify the user, and a boolean field
  512. named ``is_active`` to prevent password resets for inactive users.
  513. * :class:`~django.contrib.auth.forms.SetPasswordForm`
  514. Works with any subclass of :class:`~django.contrib.auth.models.AbstractBaseUser`
  515. * :class:`~django.contrib.auth.forms.PasswordChangeForm`
  516. Works with any subclass of :class:`~django.contrib.auth.models.AbstractBaseUser`
  517. * :class:`~django.contrib.auth.forms.AdminPasswordChangeForm`
  518. Works with any subclass of :class:`~django.contrib.auth.models.AbstractBaseUser`
  519. Custom users and :mod:`django.contrib.admin`
  520. --------------------------------------------
  521. If you want your custom User model to also work with Admin, your User model must
  522. define some additional attributes and methods. These methods allow the admin to
  523. control access of the User to admin content:
  524. .. class:: models.CustomUser
  525. .. attribute:: is_staff
  526. Returns ``True`` if the user is allowed to have access to the admin site.
  527. .. attribute:: is_active
  528. Returns ``True`` if the user account is currently active.
  529. .. method:: has_perm(perm, obj=None):
  530. Returns ``True`` if the user has the named permission. If ``obj`` is
  531. provided, the permission needs to be checked against a specific object
  532. instance.
  533. .. method:: has_module_perms(app_label):
  534. Returns ``True`` if the user has permission to access models in
  535. the given app.
  536. You will also need to register your custom User model with the admin. If
  537. your custom User model extends ``django.contrib.auth.models.AbstractUser``,
  538. you can use Django's existing ``django.contrib.auth.admin.UserAdmin``
  539. class. However, if your User model extends
  540. :class:`~django.contrib.auth.models.AbstractBaseUser`, you'll need to define
  541. a custom ModelAdmin class. It may be possible to subclass the default
  542. ``django.contrib.auth.admin.UserAdmin``; however, you'll need to
  543. override any of the definitions that refer to fields on
  544. ``django.contrib.auth.models.AbstractUser`` that aren't on your
  545. custom User class.
  546. Custom users and permissions
  547. ----------------------------
  548. To make it easy to include Django's permission framework into your own User
  549. class, Django provides :class:`~django.contrib.auth.models.PermissionsMixin`.
  550. This is an abstract model you can include in the class hierarchy for your User
  551. model, giving you all the methods and database fields necessary to support
  552. Django's permission model.
  553. :class:`~django.contrib.auth.models.PermissionsMixin` provides the following
  554. methods and attributes:
  555. .. class:: models.PermissionsMixin
  556. .. attribute:: models.PermissionsMixin.is_superuser
  557. Boolean. Designates that this user has all permissions without
  558. explicitly assigning them.
  559. .. method:: models.PermissionsMixin.get_group_permissions(obj=None)
  560. Returns a set of permission strings that the user has, through his/her
  561. groups.
  562. If ``obj`` is passed in, only returns the group permissions for
  563. this specific object.
  564. .. method:: models.PermissionsMixin.get_all_permissions(obj=None)
  565. Returns a set of permission strings that the user has, both through
  566. group and user permissions.
  567. If ``obj`` is passed in, only returns the permissions for this
  568. specific object.
  569. .. method:: models.PermissionsMixin.has_perm(perm, obj=None)
  570. Returns ``True`` if the user has the specified permission, where perm is
  571. in the format ``"<app label>.<permission codename>"`` (see
  572. :ref:`permissions <topic-authorization>`). If the user is inactive, this method will
  573. always return ``False``.
  574. If ``obj`` is passed in, this method won't check for a permission for
  575. the model, but for this specific object.
  576. .. method:: models.PermissionsMixin.has_perms(perm_list, obj=None)
  577. Returns ``True`` if the user has each of the specified permissions,
  578. where each perm is in the format
  579. ``"<app label>.<permission codename>"``. If the user is inactive,
  580. this method will always return ``False``.
  581. If ``obj`` is passed in, this method won't check for permissions for
  582. the model, but for the specific object.
  583. .. method:: models.PermissionsMixin.has_module_perms(package_name)
  584. Returns ``True`` if the user has any permissions in the given package
  585. (the Django app label). If the user is inactive, this method will
  586. always return ``False``.
  587. .. admonition:: ModelBackend
  588. If you don't include the
  589. :class:`~django.contrib.auth.models.PermissionsMixin`, you must ensure you
  590. don't invoke the permissions methods on ``ModelBackend``. ``ModelBackend``
  591. assumes that certain fields are available on your user model. If your User
  592. model doesn't provide those fields, you will receive database errors when
  593. you check permissions.
  594. Custom users and Proxy models
  595. -----------------------------
  596. One limitation of custom User models is that installing a custom User model
  597. will break any proxy model extending :class:`~django.contrib.auth.models.User`.
  598. Proxy models must be based on a concrete base class; by defining a custom User
  599. model, you remove the ability of Django to reliably identify the base class.
  600. If your project uses proxy models, you must either modify the proxy to extend
  601. the User model that is currently in use in your project, or merge your proxy's
  602. behavior into your User subclass.
  603. Custom users and signals
  604. ------------------------
  605. Another limitation of custom User models is that you can't use
  606. :func:`django.contrib.auth.get_user_model()` as the sender or target of a signal
  607. handler. Instead, you must register the handler with the resulting User model.
  608. See :doc:`/topics/signals` for more information on registering an sending
  609. signals.
  610. Custom users and testing/fixtures
  611. ---------------------------------
  612. If you are writing an application that interacts with the User model, you must
  613. take some precautions to ensure that your test suite will run regardless of
  614. the User model that is being used by a project. Any test that instantiates an
  615. instance of User will fail if the User model has been swapped out. This
  616. includes any attempt to create an instance of User with a fixture.
  617. To ensure that your test suite will pass in any project configuration,
  618. ``django.contrib.auth.tests.utils`` defines a ``@skipIfCustomUser`` decorator.
  619. This decorator will cause a test case to be skipped if any User model other
  620. than the default Django user is in use. This decorator can be applied to a
  621. single test, or to an entire test class.
  622. Depending on your application, tests may also be needed to be added to ensure
  623. that the application works with *any* user model, not just the default User
  624. model. To assist with this, Django provides two substitute user models that
  625. can be used in test suites:
  626. * ``django.contrib.auth.tests.custom_user.CustomUser``, a custom user
  627. model that uses an ``email`` field as the username, and has a basic
  628. admin-compliant permissions setup
  629. * ``django.contrib.auth.tests.custom_user.ExtensionUser``, a custom
  630. user model that extends ``django.contrib.auth.models.AbstractUser``,
  631. adding a ``date_of_birth`` field.
  632. You can then use the ``@override_settings`` decorator to make that test run
  633. with the custom User model. For example, here is a skeleton for a test that
  634. would test three possible User models -- the default, plus the two User
  635. models provided by ``auth`` app::
  636. from django.contrib.auth.tests.utils import skipIfCustomUser
  637. from django.test import TestCase
  638. from django.test.utils import override_settings
  639. class ApplicationTestCase(TestCase):
  640. @skipIfCustomUser
  641. def test_normal_user(self):
  642. "Run tests for the normal user model"
  643. self.assertSomething()
  644. @override_settings(AUTH_USER_MODEL='auth.CustomUser')
  645. def test_custom_user(self):
  646. "Run tests for a custom user model with email-based authentication"
  647. self.assertSomething()
  648. @override_settings(AUTH_USER_MODEL='auth.ExtensionUser')
  649. def test_extension_user(self):
  650. "Run tests for a simple extension of the built-in User."
  651. self.assertSomething()
  652. A full example
  653. --------------
  654. Here is an example of an admin-compliant custom user app. This user model uses
  655. an email address as the username, and has a required date of birth; it
  656. provides no permission checking, beyond a simple ``admin`` flag on the user
  657. account. This model would be compatible with all the built-in auth forms and
  658. views, except for the User creation forms. This example illustrates how most of
  659. the components work together, but is not intended to be copied directly into
  660. projects for production use.
  661. This code would all live in a ``models.py`` file for a custom
  662. authentication app::
  663. from django.db import models
  664. from django.contrib.auth.models import (
  665. BaseUserManager, AbstractBaseUser
  666. )
  667. class MyUserManager(BaseUserManager):
  668. def create_user(self, email, date_of_birth, password=None):
  669. """
  670. Creates and saves a User with the given email, date of
  671. birth and password.
  672. """
  673. if not email:
  674. raise ValueError('Users must have an email address')
  675. user = self.model(
  676. email=self.normalize_email(email),
  677. date_of_birth=date_of_birth,
  678. )
  679. user.set_password(password)
  680. user.save(using=self._db)
  681. return user
  682. def create_superuser(self, email, date_of_birth, password):
  683. """
  684. Creates and saves a superuser with the given email, date of
  685. birth and password.
  686. """
  687. user = self.create_user(email,
  688. password=password,
  689. date_of_birth=date_of_birth
  690. )
  691. user.is_admin = True
  692. user.save(using=self._db)
  693. return user
  694. class MyUser(AbstractBaseUser):
  695. email = models.EmailField(
  696. verbose_name='email address',
  697. max_length=255,
  698. unique=True,
  699. db_index=True,
  700. )
  701. date_of_birth = models.DateField()
  702. is_active = models.BooleanField(default=True)
  703. is_admin = models.BooleanField(default=False)
  704. objects = MyUserManager()
  705. USERNAME_FIELD = 'email'
  706. REQUIRED_FIELDS = ['date_of_birth']
  707. def get_full_name(self):
  708. # The user is identified by their email address
  709. return self.email
  710. def get_short_name(self):
  711. # The user is identified by their email address
  712. return self.email
  713. # On Python 3: def __str__(self):
  714. def __unicode__(self):
  715. return self.email
  716. def has_perm(self, perm, obj=None):
  717. "Does the user have a specific permission?"
  718. # Simplest possible answer: Yes, always
  719. return True
  720. def has_module_perms(self, app_label):
  721. "Does the user have permissions to view the app `app_label`?"
  722. # Simplest possible answer: Yes, always
  723. return True
  724. @property
  725. def is_staff(self):
  726. "Is the user a member of staff?"
  727. # Simplest possible answer: All admins are staff
  728. return self.is_admin
  729. Then, to register this custom User model with Django's admin, the following
  730. code would be required in the app's ``admin.py`` file::
  731. from django import forms
  732. from django.contrib import admin
  733. from django.contrib.auth.models import Group
  734. from django.contrib.auth.admin import UserAdmin
  735. from django.contrib.auth.forms import ReadOnlyPasswordHashField
  736. from customauth.models import MyUser
  737. class UserCreationForm(forms.ModelForm):
  738. """A form for creating new users. Includes all the required
  739. fields, plus a repeated password."""
  740. password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
  741. password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
  742. class Meta:
  743. model = MyUser
  744. fields = ('email', 'date_of_birth')
  745. def clean_password2(self):
  746. # Check that the two password entries match
  747. password1 = self.cleaned_data.get("password1")
  748. password2 = self.cleaned_data.get("password2")
  749. if password1 and password2 and password1 != password2:
  750. raise forms.ValidationError("Passwords don't match")
  751. return password2
  752. def save(self, commit=True):
  753. # Save the provided password in hashed format
  754. user = super(UserCreationForm, self).save(commit=False)
  755. user.set_password(self.cleaned_data["password1"])
  756. if commit:
  757. user.save()
  758. return user
  759. class UserChangeForm(forms.ModelForm):
  760. """A form for updating users. Includes all the fields on
  761. the user, but replaces the password field with admin's
  762. password hash display field.
  763. """
  764. password = ReadOnlyPasswordHashField()
  765. class Meta:
  766. model = MyUser
  767. fields = ['email', 'password', 'date_of_birth', 'is_active', 'is_admin']
  768. def clean_password(self):
  769. # Regardless of what the user provides, return the initial value.
  770. # This is done here, rather than on the field, because the
  771. # field does not have access to the initial value
  772. return self.initial["password"]
  773. class MyUserAdmin(UserAdmin):
  774. # The forms to add and change user instances
  775. form = UserChangeForm
  776. add_form = UserCreationForm
  777. # The fields to be used in displaying the User model.
  778. # These override the definitions on the base UserAdmin
  779. # that reference specific fields on auth.User.
  780. list_display = ('email', 'date_of_birth', 'is_admin')
  781. list_filter = ('is_admin',)
  782. fieldsets = (
  783. (None, {'fields': ('email', 'password')}),
  784. ('Personal info', {'fields': ('date_of_birth',)}),
  785. ('Permissions', {'fields': ('is_admin',)}),
  786. )
  787. # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
  788. # overrides get_fieldsets to use this attribute when creating a user.
  789. add_fieldsets = (
  790. (None, {
  791. 'classes': ('wide',),
  792. 'fields': ('email', 'date_of_birth', 'password1', 'password2')}
  793. ),
  794. )
  795. search_fields = ('email',)
  796. ordering = ('email',)
  797. filter_horizontal = ()
  798. # Now register the new UserAdmin...
  799. admin.site.register(MyUser, MyUserAdmin)
  800. # ... and, since we're not using Django's builtin permissions,
  801. # unregister the Group model from admin.
  802. admin.site.unregister(Group)
  803. Finally, specify the custom model as the default user model for your project
  804. using the :setting:`AUTH_USER_MODEL` setting in your ``settings.py``::
  805. AUTH_USER_MODEL = 'customauth.MyUser'