customizing.txt 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100
  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>` -- 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 migrate <migrate>`. Your code is in charge of checking the
  214. value of these permissions when a 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 creating
  292. any migrations or running ``manage.py migrate`` for the first time.
  293. Changing this setting after you have tables created is not supported
  294. by :djadmin:`makemigrations` and will result in you having to manually
  295. write a set of migrations to fix your schema.
  296. Referencing the User model
  297. --------------------------
  298. .. currentmodule:: django.contrib.auth
  299. If you reference :class:`~django.contrib.auth.models.User` directly (for
  300. example, by referring to it in a foreign key), your code will not work in
  301. projects where the :setting:`AUTH_USER_MODEL` setting has been changed to a
  302. different User model.
  303. .. function:: get_user_model()
  304. Instead of referring to :class:`~django.contrib.auth.models.User` directly,
  305. you should reference the user model using
  306. ``django.contrib.auth.get_user_model()``. This method will return the
  307. currently active User model -- the custom User model if one is specified, or
  308. :class:`~django.contrib.auth.models.User` otherwise.
  309. When you define a foreign key or many-to-many relations to the User model,
  310. you should specify the custom model using the :setting:`AUTH_USER_MODEL`
  311. setting. For example::
  312. from django.conf import settings
  313. from django.db import models
  314. class Article(models.Model):
  315. author = models.ForeignKey(settings.AUTH_USER_MODEL)
  316. .. versionadded:: 1.7
  317. When connecting to signals sent by the User model, you should specify the
  318. custom model using the :setting:`AUTH_USER_MODEL` setting. For example::
  319. from django.conf import settings
  320. from django.db.models.signals import post_save
  321. def post_save_receiver(signal, sender, instance, **kwargs):
  322. pass
  323. post_save.connect(post_save_receiver, sender=settings.AUTH_USER_MODEL)
  324. Specifying a custom User model
  325. ------------------------------
  326. .. admonition:: Model design considerations
  327. Think carefully before handling information not directly related to
  328. authentication in your custom User Model.
  329. It may be better to store app-specific user information in a model
  330. that has a relation with the User model. That allows each app to specify
  331. its own user data requirements without risking conflicts with other
  332. apps. On the other hand, queries to retrieve this related information
  333. will involve a database join, which may have an effect on performance.
  334. Django expects your custom User model to meet some minimum requirements.
  335. 1. Your model must have an integer primary key.
  336. 2. Your model must have a single unique field that can be used for
  337. identification purposes. This can be a username, an email address,
  338. or any other unique attribute.
  339. 3. Your model must provide a way to address the user in a "short" and
  340. "long" form. The most common interpretation of this would be to use
  341. the user's given name as the "short" identifier, and the user's full
  342. name as the "long" identifier. However, there are no constraints on
  343. what these two methods return - if you want, they can return exactly
  344. the same value.
  345. The easiest way to construct a compliant custom User model is to inherit from
  346. :class:`~django.contrib.auth.models.AbstractBaseUser`.
  347. :class:`~django.contrib.auth.models.AbstractBaseUser` provides the core
  348. implementation of a ``User`` model, including hashed passwords and tokenized
  349. password resets. You must then provide some key implementation details:
  350. .. currentmodule:: django.contrib.auth
  351. .. class:: models.CustomUser
  352. .. attribute:: USERNAME_FIELD
  353. A string describing the name of the field on the User model that is
  354. used as the unique identifier. This will usually be a username of
  355. some kind, but it can also be an email address, or any other unique
  356. identifier. The field *must* be unique (i.e., have ``unique=True``
  357. set in its definition).
  358. In the following example, the field ``identifier`` is used
  359. as the identifying field::
  360. class MyUser(AbstractBaseUser):
  361. identifier = models.CharField(max_length=40, unique=True, db_index=True)
  362. ...
  363. USERNAME_FIELD = 'identifier'
  364. .. attribute:: REQUIRED_FIELDS
  365. A list of the field names that will be prompted for when creating a
  366. user via the :djadmin:`createsuperuser` management command. The user
  367. will be prompted to supply a value for each of these fields. It must
  368. include any field for which :attr:`~django.db.models.Field.blank` is
  369. ``False`` or undefined and may include additional fields you want
  370. prompted for when a user is created interactively. However, it will not
  371. work for :class:`~django.db.models.ForeignKey` fields.
  372. ``REQUIRED_FIELDS`` has no effect in other parts of Django, like
  373. creating a user in the admin.
  374. For example, here is the partial definition for a ``User`` model that
  375. defines two required fields - a date of birth and height::
  376. class MyUser(AbstractBaseUser):
  377. ...
  378. date_of_birth = models.DateField()
  379. height = models.FloatField()
  380. ...
  381. REQUIRED_FIELDS = ['date_of_birth', 'height']
  382. .. note::
  383. ``REQUIRED_FIELDS`` must contain all required fields on your User
  384. model, but should *not* contain the ``USERNAME_FIELD``.
  385. .. attribute:: is_active
  386. A boolean attribute that indicates whether the user is considered
  387. "active". This attribute is provided as an attribute on
  388. ``AbstractBaseUser`` defaulting to ``True``. How you choose to
  389. implement it will depend on the details of your chosen auth backends.
  390. See the documentation of the :attr:`is_active attribute on the built-in
  391. user model <django.contrib.auth.models.User.is_active>` for details.
  392. .. method:: get_full_name()
  393. A longer formal identifier for the user. A common interpretation
  394. would be the full name of the user, but it can be any string that
  395. identifies the user.
  396. .. method:: get_short_name()
  397. A short, informal identifier for the user. A common interpretation
  398. would be the first name of the user, but it can be any string that
  399. identifies the user in an informal way. It may also return the same
  400. value as :meth:`django.contrib.auth.models.User.get_full_name()`.
  401. The following methods are available on any subclass of
  402. :class:`~django.contrib.auth.models.AbstractBaseUser`:
  403. .. class:: models.AbstractBaseUser
  404. .. method:: get_username()
  405. Returns the value of the field nominated by ``USERNAME_FIELD``.
  406. .. method:: models.AbstractBaseUser.is_anonymous()
  407. Always returns ``False``. This is a way of differentiating
  408. from :class:`~django.contrib.auth.models.AnonymousUser` objects.
  409. Generally, you should prefer using
  410. :meth:`~django.contrib.auth.models.AbstractBaseUser.is_authenticated()` to this
  411. method.
  412. .. method:: models.AbstractBaseUser.is_authenticated()
  413. Always returns ``True``. This is a way to tell if the user has been
  414. authenticated. This does not imply any permissions, and doesn't check
  415. if the user is active - it only indicates that the user has provided a
  416. valid username and password.
  417. .. method:: models.AbstractBaseUser.set_password(raw_password)
  418. Sets the user's password to the given raw string, taking care of the
  419. password hashing. Doesn't save the
  420. :class:`~django.contrib.auth.models.AbstractBaseUser` object.
  421. When the raw_password is ``None``, the password will be set to an
  422. unusable password, as if
  423. :meth:`~django.contrib.auth.models.AbstractBaseUser.set_unusable_password()`
  424. were used.
  425. .. versionchanged:: 1.6
  426. In Django 1.4 and 1.5, a blank string was unintentionally stored
  427. as an unsable password as well.
  428. .. method:: models.AbstractBaseUser.check_password(raw_password)
  429. Returns ``True`` if the given raw string is the correct password for
  430. the user. (This takes care of the password hashing in making the
  431. comparison.)
  432. .. versionchanged:: 1.6
  433. In Django 1.4 and 1.5, a blank string was unintentionally
  434. considered to be an unusable password, resulting in this method
  435. returning ``False`` for such a password.
  436. .. method:: models.AbstractBaseUser.set_unusable_password()
  437. Marks the user as having no password set. This isn't the same as
  438. having a blank string for a password.
  439. :meth:`~django.contrib.auth.models.AbstractBaseUser.check_password()` for this user
  440. will never return ``True``. Doesn't save the
  441. :class:`~django.contrib.auth.models.AbstractBaseUser` object.
  442. You may need this if authentication for your application takes place
  443. against an existing external source such as an LDAP directory.
  444. .. method:: models.AbstractBaseUser.has_usable_password()
  445. Returns ``False`` if
  446. :meth:`~django.contrib.auth.models.AbstractBaseUser.set_unusable_password()` has
  447. been called for this user.
  448. You should also define a custom manager for your ``User`` model. If your
  449. ``User`` model defines ``username``, ``email``, ``is_staff``, ``is_active``,
  450. ``is_superuser``, ``last_login``, and ``date_joined`` fields the same as
  451. Django's default ``User``, you can just install Django's
  452. :class:`~django.contrib.auth.models.UserManager`; however, if your ``User``
  453. model defines different fields, you will need to define a custom manager that
  454. extends :class:`~django.contrib.auth.models.BaseUserManager` providing two
  455. additional methods:
  456. .. class:: models.CustomUserManager
  457. .. method:: models.CustomUserManager.create_user(*username_field*, password=None, \**other_fields)
  458. The prototype of ``create_user()`` should accept the username field,
  459. plus all required fields as arguments. For example, if your user model
  460. uses ``email`` as the username field, and has ``date_of_birth`` as a
  461. required field, then ``create_user`` should be defined as::
  462. def create_user(self, email, date_of_birth, password=None):
  463. # create user here
  464. ...
  465. .. method:: models.CustomUserManager.create_superuser(*username_field*, password, \**other_fields)
  466. The prototype of ``create_superuser()`` should accept the username
  467. field, plus all required fields as arguments. For example, if your user
  468. model uses ``email`` as the username field, and has ``date_of_birth``
  469. as a required field, then ``create_superuser`` should be defined as::
  470. def create_superuser(self, email, date_of_birth, password):
  471. # create superuser here
  472. ...
  473. Unlike ``create_user()``, ``create_superuser()`` *must* require the
  474. caller to provide a password.
  475. :class:`~django.contrib.auth.models.BaseUserManager` provides the following
  476. utility methods:
  477. .. class:: models.BaseUserManager
  478. .. method:: models.BaseUserManager.normalize_email(email)
  479. A ``classmethod`` that normalizes email addresses by lowercasing
  480. the domain portion of the email address.
  481. .. method:: models.BaseUserManager.get_by_natural_key(username)
  482. Retrieves a user instance using the contents of the field
  483. nominated by ``USERNAME_FIELD``.
  484. .. method:: models.BaseUserManager.make_random_password(length=10, allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789')
  485. Returns a random password with the given length and given string of
  486. allowed characters. Note that the default value of ``allowed_chars``
  487. doesn't contain letters that can cause user confusion, including:
  488. * ``i``, ``l``, ``I``, and ``1`` (lowercase letter i, lowercase
  489. letter L, uppercase letter i, and the number one)
  490. * ``o``, ``O``, and ``0`` (lowercase letter o, uppercase letter o,
  491. and zero)
  492. Extending Django's default User
  493. -------------------------------
  494. If you're entirely happy with Django's :class:`~django.contrib.auth.models.User`
  495. model and you just want to add some additional profile information, you can
  496. simply subclass ``django.contrib.auth.models.AbstractUser`` and add your
  497. custom profile fields. This class provides the full implementation of the
  498. default :class:`~django.contrib.auth.models.User` as an :ref:`abstract model
  499. <abstract-base-classes>`.
  500. .. _custom-users-and-the-built-in-auth-forms:
  501. Custom users and the built-in auth forms
  502. ----------------------------------------
  503. As you may expect, built-in Django's :ref:`forms <built-in-auth-forms>` and
  504. :ref:`views <built-in-auth-views>` make certain assumptions about the user
  505. model that they are working with.
  506. If your user model doesn't follow the same assumptions, it may be necessary to define
  507. a replacement form, and pass that form in as part of the configuration of the
  508. auth views.
  509. * :class:`~django.contrib.auth.forms.UserCreationForm`
  510. Depends on the :class:`~django.contrib.auth.models.User` model.
  511. Must be re-written for any custom user model.
  512. * :class:`~django.contrib.auth.forms.UserChangeForm`
  513. Depends on the :class:`~django.contrib.auth.models.User` model.
  514. Must be re-written for any custom user model.
  515. * :class:`~django.contrib.auth.forms.AuthenticationForm`
  516. Works with any subclass of :class:`~django.contrib.auth.models.AbstractBaseUser`,
  517. and will adapt to use the field defined in ``USERNAME_FIELD``.
  518. * :class:`~django.contrib.auth.forms.PasswordResetForm`
  519. Assumes that the user model has an integer primary key, has a field named
  520. ``email`` that can be used to identify the user, and a boolean field
  521. named ``is_active`` to prevent password resets for inactive users.
  522. * :class:`~django.contrib.auth.forms.SetPasswordForm`
  523. Works with any subclass of :class:`~django.contrib.auth.models.AbstractBaseUser`
  524. * :class:`~django.contrib.auth.forms.PasswordChangeForm`
  525. Works with any subclass of :class:`~django.contrib.auth.models.AbstractBaseUser`
  526. * :class:`~django.contrib.auth.forms.AdminPasswordChangeForm`
  527. Works with any subclass of :class:`~django.contrib.auth.models.AbstractBaseUser`
  528. Custom users and :mod:`django.contrib.admin`
  529. --------------------------------------------
  530. If you want your custom User model to also work with Admin, your User model must
  531. define some additional attributes and methods. These methods allow the admin to
  532. control access of the User to admin content:
  533. .. class:: models.CustomUser
  534. .. attribute:: is_staff
  535. Returns ``True`` if the user is allowed to have access to the admin site.
  536. .. attribute:: is_active
  537. Returns ``True`` if the user account is currently active.
  538. .. method:: has_perm(perm, obj=None):
  539. Returns ``True`` if the user has the named permission. If ``obj`` is
  540. provided, the permission needs to be checked against a specific object
  541. instance.
  542. .. method:: has_module_perms(app_label):
  543. Returns ``True`` if the user has permission to access models in
  544. the given app.
  545. You will also need to register your custom User model with the admin. If
  546. your custom User model extends ``django.contrib.auth.models.AbstractUser``,
  547. you can use Django's existing ``django.contrib.auth.admin.UserAdmin``
  548. class. However, if your User model extends
  549. :class:`~django.contrib.auth.models.AbstractBaseUser`, you'll need to define
  550. a custom ``ModelAdmin`` class. It may be possible to subclass the default
  551. ``django.contrib.auth.admin.UserAdmin``; however, you'll need to
  552. override any of the definitions that refer to fields on
  553. ``django.contrib.auth.models.AbstractUser`` that aren't on your
  554. custom User class.
  555. Custom users and permissions
  556. ----------------------------
  557. To make it easy to include Django's permission framework into your own User
  558. class, Django provides :class:`~django.contrib.auth.models.PermissionsMixin`.
  559. This is an abstract model you can include in the class hierarchy for your User
  560. model, giving you all the methods and database fields necessary to support
  561. Django's permission model.
  562. :class:`~django.contrib.auth.models.PermissionsMixin` provides the following
  563. methods and attributes:
  564. .. class:: models.PermissionsMixin
  565. .. attribute:: models.PermissionsMixin.is_superuser
  566. Boolean. Designates that this user has all permissions without
  567. explicitly assigning them.
  568. .. method:: models.PermissionsMixin.get_group_permissions(obj=None)
  569. Returns a set of permission strings that the user has, through his/her
  570. groups.
  571. If ``obj`` is passed in, only returns the group permissions for
  572. this specific object.
  573. .. method:: models.PermissionsMixin.get_all_permissions(obj=None)
  574. Returns a set of permission strings that the user has, both through
  575. group and user permissions.
  576. If ``obj`` is passed in, only returns the permissions for this
  577. specific object.
  578. .. method:: models.PermissionsMixin.has_perm(perm, obj=None)
  579. Returns ``True`` if the user has the specified permission, where
  580. ``perm`` is in the format ``"<app label>.<permission codename>"`` (see
  581. :ref:`permissions <topic-authorization>`). If the user is inactive, this method will
  582. always return ``False``.
  583. If ``obj`` is passed in, this method won't check for a permission for
  584. the model, but for this specific object.
  585. .. method:: models.PermissionsMixin.has_perms(perm_list, obj=None)
  586. Returns ``True`` if the user has each of the specified permissions,
  587. where each perm is in the format
  588. ``"<app label>.<permission codename>"``. If the user is inactive,
  589. this method will always return ``False``.
  590. If ``obj`` is passed in, this method won't check for permissions for
  591. the model, but for the specific object.
  592. .. method:: models.PermissionsMixin.has_module_perms(package_name)
  593. Returns ``True`` if the user has any permissions in the given package
  594. (the Django app label). If the user is inactive, this method will
  595. always return ``False``.
  596. .. admonition:: ModelBackend
  597. If you don't include the
  598. :class:`~django.contrib.auth.models.PermissionsMixin`, you must ensure you
  599. don't invoke the permissions methods on ``ModelBackend``. ``ModelBackend``
  600. assumes that certain fields are available on your user model. If your User
  601. model doesn't provide those fields, you will receive database errors when
  602. you check permissions.
  603. Custom users and Proxy models
  604. -----------------------------
  605. One limitation of custom User models is that installing a custom User model
  606. will break any proxy model extending :class:`~django.contrib.auth.models.User`.
  607. Proxy models must be based on a concrete base class; by defining a custom User
  608. model, you remove the ability of Django to reliably identify the base class.
  609. If your project uses proxy models, you must either modify the proxy to extend
  610. the User model that is currently in use in your project, or merge your proxy's
  611. behavior into your User subclass.
  612. Custom users and signals
  613. ------------------------
  614. Another limitation of custom User models is that you can't use
  615. :func:`django.contrib.auth.get_user_model()` as the sender or target of a signal
  616. handler. Instead, you must register the handler with the resulting User model.
  617. See :doc:`/topics/signals` for more information on registering and sending
  618. signals.
  619. Custom users and testing/fixtures
  620. ---------------------------------
  621. If you are writing an application that interacts with the User model, you must
  622. take some precautions to ensure that your test suite will run regardless of
  623. the User model that is being used by a project. Any test that instantiates an
  624. instance of User will fail if the User model has been swapped out. This
  625. includes any attempt to create an instance of User with a fixture.
  626. To ensure that your test suite will pass in any project configuration,
  627. ``django.contrib.auth.tests.utils`` defines a ``@skipIfCustomUser`` decorator.
  628. This decorator will cause a test case to be skipped if any User model other
  629. than the default Django user is in use. This decorator can be applied to a
  630. single test, or to an entire test class.
  631. Depending on your application, tests may also be needed to be added to ensure
  632. that the application works with *any* user model, not just the default User
  633. model. To assist with this, Django provides two substitute user models that
  634. can be used in test suites:
  635. .. class:: tests.custom_user.CustomUser
  636. A custom user model that uses an ``email`` field as the username, and has a basic
  637. admin-compliant permissions setup
  638. .. class:: tests.custom_user.ExtensionUser
  639. A custom user model that extends ``django.contrib.auth.models.AbstractUser``,
  640. adding a ``date_of_birth`` field.
  641. You can then use the ``@override_settings`` decorator to make that test run
  642. with the custom User model. For example, here is a skeleton for a test that
  643. would test three possible User models -- the default, plus the two User
  644. models provided by ``auth`` app::
  645. from django.contrib.auth.tests.utils import skipIfCustomUser
  646. from django.contrib.auth.tests.custom_user import CustomUser, ExtensionUser
  647. from django.test import TestCase, override_settings
  648. class ApplicationTestCase(TestCase):
  649. @skipIfCustomUser
  650. def test_normal_user(self):
  651. "Run tests for the normal user model"
  652. self.assertSomething()
  653. @override_settings(AUTH_USER_MODEL='auth.CustomUser')
  654. def test_custom_user(self):
  655. "Run tests for a custom user model with email-based authentication"
  656. self.assertSomething()
  657. @override_settings(AUTH_USER_MODEL='auth.ExtensionUser')
  658. def test_extension_user(self):
  659. "Run tests for a simple extension of the built-in User."
  660. self.assertSomething()
  661. .. versionchanged:: 1.6
  662. In Django 1.5, it wasn't necessary to explicitly import the test User models.
  663. A full example
  664. --------------
  665. Here is an example of an admin-compliant custom user app. This user model uses
  666. an email address as the username, and has a required date of birth; it
  667. provides no permission checking, beyond a simple ``admin`` flag on the user
  668. account. This model would be compatible with all the built-in auth forms and
  669. views, except for the User creation forms. This example illustrates how most of
  670. the components work together, but is not intended to be copied directly into
  671. projects for production use.
  672. This code would all live in a ``models.py`` file for a custom
  673. authentication app::
  674. from django.db import models
  675. from django.contrib.auth.models import (
  676. BaseUserManager, AbstractBaseUser
  677. )
  678. class MyUserManager(BaseUserManager):
  679. def create_user(self, email, date_of_birth, password=None):
  680. """
  681. Creates and saves a User with the given email, date of
  682. birth and password.
  683. """
  684. if not email:
  685. raise ValueError('Users must have an email address')
  686. user = self.model(
  687. email=self.normalize_email(email),
  688. date_of_birth=date_of_birth,
  689. )
  690. user.set_password(password)
  691. user.save(using=self._db)
  692. return user
  693. def create_superuser(self, email, date_of_birth, password):
  694. """
  695. Creates and saves a superuser with the given email, date of
  696. birth and password.
  697. """
  698. user = self.create_user(email,
  699. password=password,
  700. date_of_birth=date_of_birth
  701. )
  702. user.is_admin = True
  703. user.save(using=self._db)
  704. return user
  705. class MyUser(AbstractBaseUser):
  706. email = models.EmailField(
  707. verbose_name='email address',
  708. max_length=255,
  709. unique=True,
  710. db_index=True,
  711. )
  712. date_of_birth = models.DateField()
  713. is_active = models.BooleanField(default=True)
  714. is_admin = models.BooleanField(default=False)
  715. objects = MyUserManager()
  716. USERNAME_FIELD = 'email'
  717. REQUIRED_FIELDS = ['date_of_birth']
  718. def get_full_name(self):
  719. # The user is identified by their email address
  720. return self.email
  721. def get_short_name(self):
  722. # The user is identified by their email address
  723. return self.email
  724. # On Python 3: def __str__(self):
  725. def __unicode__(self):
  726. return self.email
  727. def has_perm(self, perm, obj=None):
  728. "Does the user have a specific permission?"
  729. # Simplest possible answer: Yes, always
  730. return True
  731. def has_module_perms(self, app_label):
  732. "Does the user have permissions to view the app `app_label`?"
  733. # Simplest possible answer: Yes, always
  734. return True
  735. @property
  736. def is_staff(self):
  737. "Is the user a member of staff?"
  738. # Simplest possible answer: All admins are staff
  739. return self.is_admin
  740. Then, to register this custom User model with Django's admin, the following
  741. code would be required in the app's ``admin.py`` file::
  742. from django import forms
  743. from django.contrib import admin
  744. from django.contrib.auth.models import Group
  745. from django.contrib.auth.admin import UserAdmin
  746. from django.contrib.auth.forms import ReadOnlyPasswordHashField
  747. from customauth.models import MyUser
  748. class UserCreationForm(forms.ModelForm):
  749. """A form for creating new users. Includes all the required
  750. fields, plus a repeated password."""
  751. password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
  752. password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
  753. class Meta:
  754. model = MyUser
  755. fields = ('email', 'date_of_birth')
  756. def clean_password2(self):
  757. # Check that the two password entries match
  758. password1 = self.cleaned_data.get("password1")
  759. password2 = self.cleaned_data.get("password2")
  760. if password1 and password2 and password1 != password2:
  761. raise forms.ValidationError("Passwords don't match")
  762. return password2
  763. def save(self, commit=True):
  764. # Save the provided password in hashed format
  765. user = super(UserCreationForm, self).save(commit=False)
  766. user.set_password(self.cleaned_data["password1"])
  767. if commit:
  768. user.save()
  769. return user
  770. class UserChangeForm(forms.ModelForm):
  771. """A form for updating users. Includes all the fields on
  772. the user, but replaces the password field with admin's
  773. password hash display field.
  774. """
  775. password = ReadOnlyPasswordHashField()
  776. class Meta:
  777. model = MyUser
  778. fields = ['email', 'password', 'date_of_birth', 'is_active', 'is_admin']
  779. def clean_password(self):
  780. # Regardless of what the user provides, return the initial value.
  781. # This is done here, rather than on the field, because the
  782. # field does not have access to the initial value
  783. return self.initial["password"]
  784. class MyUserAdmin(UserAdmin):
  785. # The forms to add and change user instances
  786. form = UserChangeForm
  787. add_form = UserCreationForm
  788. # The fields to be used in displaying the User model.
  789. # These override the definitions on the base UserAdmin
  790. # that reference specific fields on auth.User.
  791. list_display = ('email', 'date_of_birth', 'is_admin')
  792. list_filter = ('is_admin',)
  793. fieldsets = (
  794. (None, {'fields': ('email', 'password')}),
  795. ('Personal info', {'fields': ('date_of_birth',)}),
  796. ('Permissions', {'fields': ('is_admin',)}),
  797. )
  798. # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
  799. # overrides get_fieldsets to use this attribute when creating a user.
  800. add_fieldsets = (
  801. (None, {
  802. 'classes': ('wide',),
  803. 'fields': ('email', 'date_of_birth', 'password1', 'password2')}
  804. ),
  805. )
  806. search_fields = ('email',)
  807. ordering = ('email',)
  808. filter_horizontal = ()
  809. # Now register the new UserAdmin...
  810. admin.site.register(MyUser, MyUserAdmin)
  811. # ... and, since we're not using Django's built-in permissions,
  812. # unregister the Group model from admin.
  813. admin.site.unregister(Group)
  814. Finally, specify the custom model as the default user model for your project
  815. using the :setting:`AUTH_USER_MODEL` setting in your ``settings.py``::
  816. AUTH_USER_MODEL = 'customauth.MyUser'