auth.txt 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. ``django.contrib.auth``
  2. =======================
  3. This document provides API reference material for the components of Django's
  4. authentication system. For more details on the usage of these components or
  5. how to customize authentication and authorization see the :doc:`authentication
  6. topic guide </topics/auth/index>`.
  7. .. currentmodule:: django.contrib.auth
  8. User
  9. ====
  10. Fields
  11. ------
  12. .. class:: models.User
  13. :class:`~django.contrib.auth.models.User` objects have the following
  14. fields:
  15. .. attribute:: username
  16. Required. 30 characters or fewer. Usernames may contain alphanumeric,
  17. ``_``, ``@``, ``+``, ``.`` and ``-`` characters.
  18. .. attribute:: first_name
  19. Optional. 30 characters or fewer.
  20. .. attribute:: last_name
  21. Optional. 30 characters or fewer.
  22. .. attribute:: email
  23. Optional. Email address.
  24. .. attribute:: password
  25. Required. A hash of, and metadata about, the password. (Django doesn't
  26. store the raw password.) Raw passwords can be arbitrarily long and can
  27. contain any character. See the :doc:`password documentation
  28. </topics/auth/passwords>`.
  29. .. attribute:: groups
  30. Many-to-many relationship to :class:`~django.contrib.auth.models.Group`
  31. .. attribute:: user_permissions
  32. Many-to-many relationship to :class:`~django.contrib.auth.models.Permission`
  33. .. attribute:: is_staff
  34. Boolean. Designates whether this user can access the admin site.
  35. .. attribute:: is_active
  36. Boolean. Designates whether this user account should be considered
  37. active. We recommend that you set this flag to ``False`` instead of
  38. deleting accounts; that way, if your applications have any foreign keys
  39. to users, the foreign keys won't break.
  40. This doesn't necessarily control whether or not the user can log in.
  41. Authentication backends aren't required to check for the ``is_active``
  42. flag, and the default backends do not. If you want to reject a login
  43. based on ``is_active`` being ``False``, it's up to you to check that in
  44. your own login view or a custom authentication backend. However, the
  45. :class:`~django.contrib.auth.forms.AuthenticationForm` used by the
  46. :func:`~django.contrib.auth.views.login` view (which is the default)
  47. *does* perform this check, as do the permission-checking methods such
  48. as :meth:`~django.contrib.auth.models.User.has_perm` and the
  49. authentication in the Django admin. All of those functions/methods will
  50. return ``False`` for inactive users.
  51. .. attribute:: is_superuser
  52. Boolean. Designates that this user has all permissions without
  53. explicitly assigning them.
  54. .. attribute:: last_login
  55. A datetime of the user's last login. Is set to the current date/time by
  56. default.
  57. .. attribute:: date_joined
  58. A datetime designating when the account was created. Is set to the
  59. current date/time by default when the account is created.
  60. Methods
  61. -------
  62. .. class:: models.User
  63. .. method:: get_username()
  64. Returns the username for the user. Since the User model can be swapped
  65. out, you should use this method instead of referencing the username
  66. attribute directly.
  67. .. method:: is_anonymous()
  68. Always returns ``False``. This is a way of differentiating
  69. :class:`~django.contrib.auth.models.User` and
  70. :class:`~django.contrib.auth.models.AnonymousUser` objects.
  71. Generally, you should prefer using
  72. :meth:`~django.contrib.auth.models.User.is_authenticated()` to this
  73. method.
  74. .. method:: is_authenticated()
  75. Always returns ``True`` (as opposed to
  76. ``AnonymousUser.is_authenticated()`` which always returns ``False``).
  77. This is a way to tell if the user has been authenticated. This does not
  78. imply any permissions, and doesn't check if the user is active - it
  79. only indicates that ``request.user`` has been populated by the
  80. :class:`~django.contrib.auth.middleware.AuthenticationMiddleware` with
  81. a :class:`~django.contrib.auth.models.User` object representing the
  82. currently logged-in user.
  83. .. method:: get_full_name()
  84. Returns the :attr:`~django.contrib.auth.models.User.first_name` plus
  85. the :attr:`~django.contrib.auth.models.User.last_name`, with a space in
  86. between.
  87. .. method:: set_password(raw_password)
  88. Sets the user's password to the given raw string, taking care of the
  89. password hashing. Doesn't save the
  90. :class:`~django.contrib.auth.models.User` object.
  91. When the ``raw_password`` is ``None``, the password will be set to an
  92. unusable password, as if
  93. :meth:`~django.contrib.auth.models.User.set_unusable_password()`
  94. were used.
  95. .. versionchanged:: 1.6
  96. In Django 1.4 and 1.5, a blank string was unintentionally stored
  97. as an unsable password.
  98. .. method:: check_password(raw_password)
  99. Returns ``True`` if the given raw string is the correct password for
  100. the user. (This takes care of the password hashing in making the
  101. comparison.)
  102. .. versionchanged:: 1.6
  103. In Django 1.4 and 1.5, a blank string was unintentionally
  104. considered to be an unusable password, resulting in this method
  105. returning ``False`` for such a password.
  106. .. method:: set_unusable_password()
  107. Marks the user as having no password set. This isn't the same as
  108. having a blank string for a password.
  109. :meth:`~django.contrib.auth.models.User.check_password()` for this user
  110. will never return ``True``. Doesn't save the
  111. :class:`~django.contrib.auth.models.User` object.
  112. You may need this if authentication for your application takes place
  113. against an existing external source such as an LDAP directory.
  114. .. method:: has_usable_password()
  115. Returns ``False`` if
  116. :meth:`~django.contrib.auth.models.User.set_unusable_password()` has
  117. been called for this user.
  118. .. method:: get_group_permissions(obj=None)
  119. Returns a set of permission strings that the user has, through his/her
  120. groups.
  121. If ``obj`` is passed in, only returns the group permissions for
  122. this specific object.
  123. .. method:: get_all_permissions(obj=None)
  124. Returns a set of permission strings that the user has, both through
  125. group and user permissions.
  126. If ``obj`` is passed in, only returns the permissions for this
  127. specific object.
  128. .. method:: has_perm(perm, obj=None)
  129. Returns ``True`` if the user has the specified permission, where perm
  130. is in the format ``"<app label>.<permission codename>"``. (see
  131. documentation on :ref:`permissions <topic-authorization>`). If the user is
  132. inactive, this method will always return ``False``.
  133. If ``obj`` is passed in, this method won't check for a permission for
  134. the model, but for this specific object.
  135. .. method:: has_perms(perm_list, obj=None)
  136. Returns ``True`` if the user has each of the specified permissions,
  137. where each perm is in the format
  138. ``"<app label>.<permission codename>"``. If the user is inactive,
  139. this method will always return ``False``.
  140. If ``obj`` is passed in, this method won't check for permissions for
  141. the model, but for the specific object.
  142. .. method:: has_module_perms(package_name)
  143. Returns ``True`` if the user has any permissions in the given package
  144. (the Django app label). If the user is inactive, this method will
  145. always return ``False``.
  146. .. method:: email_user(subject, message, from_email=None)
  147. Sends an email to the user. If ``from_email`` is ``None``, Django uses
  148. the :setting:`DEFAULT_FROM_EMAIL`.
  149. Manager methods
  150. ---------------
  151. .. class:: models.UserManager
  152. The :class:`~django.contrib.auth.models.User` model has a custom manager
  153. that has the following helper methods (in addition to the methods provided
  154. by :class:`~django.contrib.auth.models.BaseUserManager`):
  155. .. method:: create_user(username, email=None, password=None, **extra_fields)
  156. Creates, saves and returns a :class:`~django.contrib.auth.models.User`.
  157. The :attr:`~django.contrib.auth.models.User.username` and
  158. :attr:`~django.contrib.auth.models.User.password` are set as given. The
  159. domain portion of :attr:`~django.contrib.auth.models.User.email` is
  160. automatically converted to lowercase, and the returned
  161. :class:`~django.contrib.auth.models.User` object will have
  162. :attr:`~django.contrib.auth.models.User.is_active` set to ``True``.
  163. If no password is provided,
  164. :meth:`~django.contrib.auth.models.User.set_unusable_password()` will
  165. be called.
  166. The ``extra_fields`` keyword arguments are passed through to the
  167. :class:`~django.contrib.auth.models.User`’s ``__init__`` method to
  168. allow setting arbitrary fields on a :ref:`custom User model
  169. <auth-custom-user>`.
  170. See :ref:`Creating users <topics-auth-creating-users>` for example usage.
  171. .. method:: create_superuser(self, username, email, password, **extra_fields)
  172. Same as :meth:`create_user`, but sets :attr:`~models.User.is_staff` and
  173. :attr:`~models.User.is_superuser` to ``True``.
  174. Anonymous users
  175. ===============
  176. .. class:: models.AnonymousUser
  177. :class:`django.contrib.auth.models.AnonymousUser` is a class that
  178. implements the :class:`django.contrib.auth.models.User` interface, with
  179. these differences:
  180. * :ref:`id <automatic-primary-key-fields>` is always ``None``.
  181. * :attr:`~django.contrib.auth.models.User.is_staff` and
  182. :attr:`~django.contrib.auth.models.User.is_superuser` are always
  183. ``False``.
  184. * :attr:`~django.contrib.auth.models.User.is_active` is always ``False``.
  185. * :attr:`~django.contrib.auth.models.User.groups` and
  186. :attr:`~django.contrib.auth.models.User.user_permissions` are always
  187. empty.
  188. * :meth:`~django.contrib.auth.models.User.is_anonymous()` returns ``True``
  189. instead of ``False``.
  190. * :meth:`~django.contrib.auth.models.User.is_authenticated()` returns
  191. ``False`` instead of ``True``.
  192. * :meth:`~django.contrib.auth.models.User.set_password()`,
  193. :meth:`~django.contrib.auth.models.User.check_password()`,
  194. :meth:`~django.db.models.Model.save` and
  195. :meth:`~django.db.models.Model.delete()` raise
  196. :exc:`~exceptions.NotImplementedError`.
  197. In practice, you probably won't need to use
  198. :class:`~django.contrib.auth.models.AnonymousUser` objects on your own, but
  199. they're used by Web requests, as explained in the next section.
  200. Permission
  201. ==========
  202. .. class:: models.Permission
  203. Fields
  204. ------
  205. :class:`~django.contrib.auth.models.Permission` objects have the following
  206. fields:
  207. .. attribute:: name
  208. Required. 50 characters or fewer. Example: ``'Can vote'``.
  209. .. attribute:: content_type
  210. Required. A reference to the ``django_content_type`` database table, which
  211. contains a record for each installed Django model.
  212. .. attribute:: codename
  213. Required. 100 characters or fewer. Example: ``'can_vote'``.
  214. Methods
  215. -------
  216. :class:`~django.contrib.auth.models.Permission` objects have the standard
  217. data-access methods like any other :doc:`Django model </ref/models/instances>`.
  218. Group
  219. =====
  220. .. class:: models.Group
  221. Fields
  222. ------
  223. :class:`~django.contrib.auth.models.Group` objects have the following fields:
  224. .. attribute:: name
  225. Required. 80 characters or fewer. Any characters are permitted. Example:
  226. ``'Awesome Users'``.
  227. .. attribute:: permissions
  228. Many-to-many field to :class:`~django.contrib.auth.models.Permission`::
  229. group.permissions = [permission_list]
  230. group.permissions.add(permission, permission, ...)
  231. group.permissions.remove(permission, permission, ...)
  232. group.permissions.clear()
  233. .. _topics-auth-signals:
  234. Login and logout signals
  235. ========================
  236. .. module:: django.contrib.auth.signals
  237. The auth framework uses the following :doc:`signals </topics/signals>` that
  238. can be used for notification when a user logs in or out.
  239. .. function:: user_logged_in
  240. Sent when a user logs in successfully.
  241. Arguments sent with this signal:
  242. ``sender``
  243. The class of the user that just logged in.
  244. ``request``
  245. The current :class:`~django.http.HttpRequest` instance.
  246. ``user``
  247. The user instance that just logged in.
  248. .. function:: user_logged_out
  249. Sent when the logout method is called.
  250. ``sender``
  251. As above: the class of the user that just logged out or ``None``
  252. if the user was not authenticated.
  253. ``request``
  254. The current :class:`~django.http.HttpRequest` instance.
  255. ``user``
  256. The user instance that just logged out or ``None`` if the
  257. user was not authenticated.
  258. .. function:: user_login_failed
  259. .. versionadded:: 1.5
  260. Sent when the user failed to login successfully
  261. ``sender``
  262. The name of the module used for authentication.
  263. ``credentials``
  264. A dictionary of keyword arguments containing the user credentials that were
  265. passed to :func:`~django.contrib.auth.authenticate()` or your own custom
  266. authentication backend. Credentials matching a set of 'sensitive' patterns,
  267. (including password) will not be sent in the clear as part of the signal.
  268. .. _authentication-backends-reference:
  269. Authentication backends
  270. =======================
  271. .. module:: django.contrib.auth.backends
  272. :synopsis: Django's built-in authentication backend classes.
  273. This section details the authentication backends that come with Django. For
  274. information on how to use them and how to write your own authentication
  275. backends, see the :ref:`Other authentication sources section
  276. <authentication-backends>` of the :doc:`User authentication guide
  277. </topics/auth/index>`.
  278. Available authentication backends
  279. ---------------------------------
  280. The following backends are available in :mod:`django.contrib.auth.backends`:
  281. .. class:: ModelBackend
  282. This is the default authentication backend used by Django. It
  283. authenticates using credentials consisting of a user identifier and
  284. password. For Django's default user model, the user identifier is the
  285. username, for custom user models it is the field specified by
  286. USERNAME_FIELD (see :doc:`Customizing Users and authentication
  287. </topics/auth/customizing>`).
  288. It also handles the default permissions model as defined for
  289. :class:`~django.contrib.auth.models.User` and
  290. :class:`~django.contrib.auth.models.PermissionsMixin`.
  291. .. class:: RemoteUserBackend
  292. Use this backend to take advantage of external-to-Django-handled
  293. authentication. It authenticates using usernames passed in
  294. :attr:`request.META['REMOTE_USER'] <django.http.HttpRequest.META>`. See
  295. the :doc:`Authenticating against REMOTE_USER </howto/auth-remote-user>`
  296. documentation.