auth.txt 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  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 or has
  79. a valid session. Even though normally you will call this method on
  80. ``request.user`` to find out whether it has been populated by the
  81. :class:`~django.contrib.auth.middleware.AuthenticationMiddleware`
  82. (representing the currently logged-in user), you should know this method
  83. returns ``True`` for any :class:`~django.contrib.auth.models.User`
  84. instance.
  85. .. method:: get_full_name()
  86. Returns the :attr:`~django.contrib.auth.models.User.first_name` plus
  87. the :attr:`~django.contrib.auth.models.User.last_name`, with a space in
  88. between.
  89. .. method:: get_short_name()
  90. Returns the :attr:`~django.contrib.auth.models.User.first_name`.
  91. .. method:: set_password(raw_password)
  92. Sets the user's password to the given raw string, taking care of the
  93. password hashing. Doesn't save the
  94. :class:`~django.contrib.auth.models.User` object.
  95. When the ``raw_password`` is ``None``, the password will be set to an
  96. unusable password, as if
  97. :meth:`~django.contrib.auth.models.User.set_unusable_password()`
  98. were used.
  99. .. versionchanged:: 1.6
  100. In Django 1.4 and 1.5, a blank string was unintentionally stored
  101. as an unusable password.
  102. .. method:: check_password(raw_password)
  103. Returns ``True`` if the given raw string is the correct password for
  104. the user. (This takes care of the password hashing in making the
  105. comparison.)
  106. .. versionchanged:: 1.6
  107. In Django 1.4 and 1.5, a blank string was unintentionally
  108. considered to be an unusable password, resulting in this method
  109. returning ``False`` for such a password.
  110. .. method:: set_unusable_password()
  111. Marks the user as having no password set. This isn't the same as
  112. having a blank string for a password.
  113. :meth:`~django.contrib.auth.models.User.check_password()` for this user
  114. will never return ``True``. Doesn't save the
  115. :class:`~django.contrib.auth.models.User` object.
  116. You may need this if authentication for your application takes place
  117. against an existing external source such as an LDAP directory.
  118. .. method:: has_usable_password()
  119. Returns ``False`` if
  120. :meth:`~django.contrib.auth.models.User.set_unusable_password()` has
  121. been called for this user.
  122. .. method:: get_group_permissions(obj=None)
  123. Returns a set of permission strings that the user has, through his/her
  124. groups.
  125. If ``obj`` is passed in, only returns the group permissions for
  126. this specific object.
  127. .. method:: get_all_permissions(obj=None)
  128. Returns a set of permission strings that the user has, both through
  129. group and user permissions.
  130. If ``obj`` is passed in, only returns the permissions for this
  131. specific object.
  132. .. method:: has_perm(perm, obj=None)
  133. Returns ``True`` if the user has the specified permission, where perm
  134. is in the format ``"<app label>.<permission codename>"``. (see
  135. documentation on :ref:`permissions <topic-authorization>`). If the user is
  136. inactive, this method will always return ``False``.
  137. If ``obj`` is passed in, this method won't check for a permission for
  138. the model, but for this specific object.
  139. .. method:: has_perms(perm_list, obj=None)
  140. Returns ``True`` if the user has each of the specified permissions,
  141. where each perm is in the format
  142. ``"<app label>.<permission codename>"``. If the user is inactive,
  143. this method will always return ``False``.
  144. If ``obj`` is passed in, this method won't check for permissions for
  145. the model, but for the specific object.
  146. .. method:: has_module_perms(package_name)
  147. Returns ``True`` if the user has any permissions in the given package
  148. (the Django app label). If the user is inactive, this method will
  149. always return ``False``.
  150. .. method:: email_user(subject, message, from_email=None, **kwargs)
  151. Sends an email to the user. If ``from_email`` is ``None``, Django uses
  152. the :setting:`DEFAULT_FROM_EMAIL`.
  153. .. versionchanged:: 1.7
  154. Any ``**kwargs`` are passed to the underlying
  155. :meth:`~django.core.mail.send_mail()` call.
  156. Manager methods
  157. ---------------
  158. .. class:: models.UserManager
  159. The :class:`~django.contrib.auth.models.User` model has a custom manager
  160. that has the following helper methods (in addition to the methods provided
  161. by :class:`~django.contrib.auth.models.BaseUserManager`):
  162. .. method:: create_user(username, email=None, password=None, **extra_fields)
  163. Creates, saves and returns a :class:`~django.contrib.auth.models.User`.
  164. The :attr:`~django.contrib.auth.models.User.username` and
  165. :attr:`~django.contrib.auth.models.User.password` are set as given. The
  166. domain portion of :attr:`~django.contrib.auth.models.User.email` is
  167. automatically converted to lowercase, and the returned
  168. :class:`~django.contrib.auth.models.User` object will have
  169. :attr:`~django.contrib.auth.models.User.is_active` set to ``True``.
  170. If no password is provided,
  171. :meth:`~django.contrib.auth.models.User.set_unusable_password()` will
  172. be called.
  173. The ``extra_fields`` keyword arguments are passed through to the
  174. :class:`~django.contrib.auth.models.User`’s ``__init__`` method to
  175. allow setting arbitrary fields on a :ref:`custom User model
  176. <auth-custom-user>`.
  177. See :ref:`Creating users <topics-auth-creating-users>` for example usage.
  178. .. method:: create_superuser(username, email, password, **extra_fields)
  179. Same as :meth:`create_user`, but sets :attr:`~models.User.is_staff` and
  180. :attr:`~models.User.is_superuser` to ``True``.
  181. Anonymous users
  182. ===============
  183. .. class:: models.AnonymousUser
  184. :class:`django.contrib.auth.models.AnonymousUser` is a class that
  185. implements the :class:`django.contrib.auth.models.User` interface, with
  186. these differences:
  187. * :ref:`id <automatic-primary-key-fields>` is always ``None``.
  188. * :attr:`~django.contrib.auth.models.User.is_staff` and
  189. :attr:`~django.contrib.auth.models.User.is_superuser` are always
  190. ``False``.
  191. * :attr:`~django.contrib.auth.models.User.is_active` is always ``False``.
  192. * :attr:`~django.contrib.auth.models.User.groups` and
  193. :attr:`~django.contrib.auth.models.User.user_permissions` are always
  194. empty.
  195. * :meth:`~django.contrib.auth.models.User.is_anonymous()` returns ``True``
  196. instead of ``False``.
  197. * :meth:`~django.contrib.auth.models.User.is_authenticated()` returns
  198. ``False`` instead of ``True``.
  199. * :meth:`~django.contrib.auth.models.User.set_password()`,
  200. :meth:`~django.contrib.auth.models.User.check_password()`,
  201. :meth:`~django.db.models.Model.save` and
  202. :meth:`~django.db.models.Model.delete()` raise
  203. :exc:`~exceptions.NotImplementedError`.
  204. In practice, you probably won't need to use
  205. :class:`~django.contrib.auth.models.AnonymousUser` objects on your own, but
  206. they're used by Web requests, as explained in the next section.
  207. Permission
  208. ==========
  209. .. class:: models.Permission
  210. Fields
  211. ------
  212. :class:`~django.contrib.auth.models.Permission` objects have the following
  213. fields:
  214. .. attribute:: name
  215. Required. 50 characters or fewer. Example: ``'Can vote'``.
  216. .. attribute:: content_type
  217. Required. A reference to the ``django_content_type`` database table, which
  218. contains a record for each installed Django model.
  219. .. attribute:: codename
  220. Required. 100 characters or fewer. Example: ``'can_vote'``.
  221. Methods
  222. -------
  223. :class:`~django.contrib.auth.models.Permission` objects have the standard
  224. data-access methods like any other :doc:`Django model </ref/models/instances>`.
  225. Group
  226. =====
  227. .. class:: models.Group
  228. Fields
  229. ------
  230. :class:`~django.contrib.auth.models.Group` objects have the following fields:
  231. .. attribute:: name
  232. Required. 80 characters or fewer. Any characters are permitted. Example:
  233. ``'Awesome Users'``.
  234. .. attribute:: permissions
  235. Many-to-many field to :class:`~django.contrib.auth.models.Permission`::
  236. group.permissions = [permission_list]
  237. group.permissions.add(permission, permission, ...)
  238. group.permissions.remove(permission, permission, ...)
  239. group.permissions.clear()
  240. .. _topics-auth-signals:
  241. Login and logout signals
  242. ========================
  243. .. module:: django.contrib.auth.signals
  244. The auth framework uses the following :doc:`signals </topics/signals>` that
  245. can be used for notification when a user logs in or out.
  246. .. function:: user_logged_in
  247. Sent when a user logs in successfully.
  248. Arguments sent with this signal:
  249. ``sender``
  250. The class of the user that just logged in.
  251. ``request``
  252. The current :class:`~django.http.HttpRequest` instance.
  253. ``user``
  254. The user instance that just logged in.
  255. .. function:: user_logged_out
  256. Sent when the logout method is called.
  257. ``sender``
  258. As above: the class of the user that just logged out or ``None``
  259. if the user was not authenticated.
  260. ``request``
  261. The current :class:`~django.http.HttpRequest` instance.
  262. ``user``
  263. The user instance that just logged out or ``None`` if the
  264. user was not authenticated.
  265. .. function:: user_login_failed
  266. Sent when the user failed to login successfully
  267. ``sender``
  268. The name of the module used for authentication.
  269. ``credentials``
  270. A dictionary of keyword arguments containing the user credentials that were
  271. passed to :func:`~django.contrib.auth.authenticate()` or your own custom
  272. authentication backend. Credentials matching a set of 'sensitive' patterns,
  273. (including password) will not be sent in the clear as part of the signal.
  274. .. _authentication-backends-reference:
  275. Authentication backends
  276. =======================
  277. .. module:: django.contrib.auth.backends
  278. :synopsis: Django's built-in authentication backend classes.
  279. This section details the authentication backends that come with Django. For
  280. information on how to use them and how to write your own authentication
  281. backends, see the :ref:`Other authentication sources section
  282. <authentication-backends>` of the :doc:`User authentication guide
  283. </topics/auth/index>`.
  284. Available authentication backends
  285. ---------------------------------
  286. The following backends are available in :mod:`django.contrib.auth.backends`:
  287. .. class:: ModelBackend
  288. This is the default authentication backend used by Django. It
  289. authenticates using credentials consisting of a user identifier and
  290. password. For Django's default user model, the user identifier is the
  291. username, for custom user models it is the field specified by
  292. USERNAME_FIELD (see :doc:`Customizing Users and authentication
  293. </topics/auth/customizing>`).
  294. It also handles the default permissions model as defined for
  295. :class:`~django.contrib.auth.models.User` and
  296. :class:`~django.contrib.auth.models.PermissionsMixin`.
  297. .. class:: RemoteUserBackend
  298. Use this backend to take advantage of external-to-Django-handled
  299. authentication. It authenticates using usernames passed in
  300. :attr:`request.META['REMOTE_USER'] <django.http.HttpRequest.META>`. See
  301. the :doc:`Authenticating against REMOTE_USER </howto/auth-remote-user>`
  302. documentation.