auth.txt 15 KB

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