default.txt 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872
  1. ======================================
  2. Using the Django authentication system
  3. ======================================
  4. .. currentmodule:: django.contrib.auth
  5. This document explains the usage of Django's authentication system in its
  6. default configuration. This configuration has evolved to serve the most common
  7. project needs, handling a reasonably wide range of tasks, and has a careful
  8. implementation of passwords and permissions. For projects where authentication
  9. needs differ from the default, Django supports extensive :doc:`extension and
  10. customization </topics/auth/customizing>` of authentication.
  11. Django authentication provides both authentication and authorization together
  12. and is generally referred to as the authentication system, as these features
  13. are somewhat coupled.
  14. .. _user-objects:
  15. ``User`` objects
  16. ================
  17. :class:`~django.contrib.auth.models.User` objects are the core of the
  18. authentication system. They typically represent the people interacting with
  19. your site and are used to enable things like restricting access, registering
  20. user profiles, associating content with creators etc. Only one class of user
  21. exists in Django's authentication framework, i.e., :attr:`'superusers'
  22. <django.contrib.auth.models.User.is_superuser>` or admin :attr:`'staff'
  23. <django.contrib.auth.models.User.is_staff>` users are just user objects with
  24. special attributes set, not different classes of user objects.
  25. The primary attributes of the default user are:
  26. * :attr:`~django.contrib.auth.models.User.username`
  27. * :attr:`~django.contrib.auth.models.User.password`
  28. * :attr:`~django.contrib.auth.models.User.email`
  29. * :attr:`~django.contrib.auth.models.User.first_name`
  30. * :attr:`~django.contrib.auth.models.User.last_name`
  31. See the :class:`full API documentation <django.contrib.auth.models.User>` for
  32. full reference, the documentation that follows is more task oriented.
  33. .. _topics-auth-creating-users:
  34. Creating users
  35. --------------
  36. The most direct way to create users is to use the included
  37. :meth:`~django.contrib.auth.models.UserManager.create_user` helper function:
  38. .. code-block:: pycon
  39. >>> from django.contrib.auth.models import User
  40. >>> user = User.objects.create_user("john", "lennon@thebeatles.com", "johnpassword")
  41. # At this point, user is a User object that has already been saved
  42. # to the database. You can continue to change its attributes
  43. # if you want to change other fields.
  44. >>> user.last_name = "Lennon"
  45. >>> user.save()
  46. If you have the Django admin installed, you can also :ref:`create users
  47. interactively <auth-admin>`.
  48. .. _topics-auth-creating-superusers:
  49. Creating superusers
  50. -------------------
  51. Create superusers using the :djadmin:`createsuperuser` command:
  52. .. console::
  53. $ python manage.py createsuperuser --username=joe --email=joe@example.com
  54. You will be prompted for a password. After you enter one, the user will be
  55. created immediately. If you leave off the :option:`--username <createsuperuser
  56. --username>` or :option:`--email <createsuperuser --email>` options, it will
  57. prompt you for those values.
  58. Changing passwords
  59. ------------------
  60. Django does not store raw (clear text) passwords on the user model, but only
  61. a hash (see :doc:`documentation of how passwords are managed
  62. </topics/auth/passwords>` for full details). Because of this, do not attempt to
  63. manipulate the password attribute of the user directly. This is why a helper
  64. function is used when creating a user.
  65. To change a user's password, you have several options:
  66. :djadmin:`manage.py changepassword *username* <changepassword>` offers a method
  67. of changing a user's password from the command line. It prompts you to
  68. change the password of a given user which you must enter twice. If
  69. they both match, the new password will be changed immediately. If you
  70. do not supply a user, the command will attempt to change the password
  71. whose username matches the current system user.
  72. You can also change a password programmatically, using
  73. :meth:`~django.contrib.auth.models.User.set_password()`:
  74. .. code-block:: pycon
  75. >>> from django.contrib.auth.models import User
  76. >>> u = User.objects.get(username="john")
  77. >>> u.set_password("new password")
  78. >>> u.save()
  79. If you have the Django admin installed, you can also change user's passwords
  80. on the :ref:`authentication system's admin pages <auth-admin>`.
  81. Django also provides :ref:`views <built-in-auth-views>` and :ref:`forms
  82. <built-in-auth-forms>` that may be used to allow users to change their own
  83. passwords.
  84. Changing a user's password will log out all their sessions. See
  85. :ref:`session-invalidation-on-password-change` for details.
  86. Authenticating users
  87. --------------------
  88. .. function:: authenticate(request=None, **credentials)
  89. .. function:: aauthenticate(request=None, **credentials)
  90. *Asynchronous version*: ``aauthenticate()``
  91. Use :func:`~django.contrib.auth.authenticate()` to verify a set of
  92. credentials. It takes credentials as keyword arguments, ``username`` and
  93. ``password`` for the default case, checks them against each
  94. :ref:`authentication backend <authentication-backends>`, and returns a
  95. :class:`~django.contrib.auth.models.User` object if the credentials are
  96. valid for a backend. If the credentials aren't valid for any backend or if
  97. a backend raises :class:`~django.core.exceptions.PermissionDenied`, it
  98. returns ``None``. For example::
  99. from django.contrib.auth import authenticate
  100. user = authenticate(username="john", password="secret")
  101. if user is not None:
  102. # A backend authenticated the credentials
  103. ...
  104. else:
  105. # No backend authenticated the credentials
  106. ...
  107. ``request`` is an optional :class:`~django.http.HttpRequest` which is
  108. passed on the ``authenticate()`` method of the authentication backends.
  109. .. note::
  110. This is a low level way to authenticate a set of credentials; for
  111. example, it's used by the
  112. :class:`~django.contrib.auth.middleware.RemoteUserMiddleware`. Unless
  113. you are writing your own authentication system, you probably won't use
  114. this. Rather if you're looking for a way to login a user, use the
  115. :class:`~django.contrib.auth.views.LoginView`.
  116. .. versionchanged:: 5.0
  117. ``aauthenticate()`` function was added.
  118. .. _topic-authorization:
  119. Permissions and Authorization
  120. =============================
  121. Django comes with a built-in permissions system. It provides a way to assign
  122. permissions to specific users and groups of users.
  123. It's used by the Django admin site, but you're welcome to use it in your own
  124. code.
  125. The Django admin site uses permissions as follows:
  126. * Access to view objects is limited to users with the "view" or "change"
  127. permission for that type of object.
  128. * Access to view the "add" form and add an object is limited to users with
  129. the "add" permission for that type of object.
  130. * Access to view the change list, view the "change" form and change an
  131. object is limited to users with the "change" permission for that type of
  132. object.
  133. * Access to delete an object is limited to users with the "delete"
  134. permission for that type of object.
  135. Permissions can be set not only per type of object, but also per specific
  136. object instance. By using the
  137. :meth:`~django.contrib.admin.ModelAdmin.has_view_permission`,
  138. :meth:`~django.contrib.admin.ModelAdmin.has_add_permission`,
  139. :meth:`~django.contrib.admin.ModelAdmin.has_change_permission` and
  140. :meth:`~django.contrib.admin.ModelAdmin.has_delete_permission` methods provided
  141. by the :class:`~django.contrib.admin.ModelAdmin` class, it is possible to
  142. customize permissions for different object instances of the same type.
  143. :class:`~django.contrib.auth.models.User` objects have two many-to-many
  144. fields: ``groups`` and ``user_permissions``.
  145. :class:`~django.contrib.auth.models.User` objects can access their related
  146. objects in the same way as any other :doc:`Django model
  147. </topics/db/models>`::
  148. myuser.groups.set([group_list])
  149. myuser.groups.add(group, group, ...)
  150. myuser.groups.remove(group, group, ...)
  151. myuser.groups.clear()
  152. myuser.user_permissions.set([permission_list])
  153. myuser.user_permissions.add(permission, permission, ...)
  154. myuser.user_permissions.remove(permission, permission, ...)
  155. myuser.user_permissions.clear()
  156. Default permissions
  157. -------------------
  158. When ``django.contrib.auth`` is listed in your :setting:`INSTALLED_APPS`
  159. setting, it will ensure that four default permissions -- add, change, delete,
  160. and view -- are created for each Django model defined in one of your installed
  161. applications.
  162. These permissions will be created when you run :djadmin:`manage.py migrate
  163. <migrate>`; the first time you run ``migrate`` after adding
  164. ``django.contrib.auth`` to :setting:`INSTALLED_APPS`, the default permissions
  165. will be created for all previously-installed models, as well as for any new
  166. models being installed at that time. Afterward, it will create default
  167. permissions for new models each time you run :djadmin:`manage.py migrate
  168. <migrate>` (the function that creates permissions is connected to the
  169. :data:`~django.db.models.signals.post_migrate` signal).
  170. Assuming you have an application with an
  171. :attr:`~django.db.models.Options.app_label` ``foo`` and a model named ``Bar``,
  172. to test for basic permissions you should use:
  173. * add: ``user.has_perm('foo.add_bar')``
  174. * change: ``user.has_perm('foo.change_bar')``
  175. * delete: ``user.has_perm('foo.delete_bar')``
  176. * view: ``user.has_perm('foo.view_bar')``
  177. The :class:`~django.contrib.auth.models.Permission` model is rarely accessed
  178. directly.
  179. Groups
  180. ------
  181. :class:`django.contrib.auth.models.Group` models are a generic way of
  182. categorizing users so you can apply permissions, or some other label, to those
  183. users. A user can belong to any number of groups.
  184. A user in a group automatically has the permissions granted to that group. For
  185. example, if the group ``Site editors`` has the permission
  186. ``can_edit_home_page``, any user in that group will have that permission.
  187. Beyond permissions, groups are a convenient way to categorize users to give
  188. them some label, or extended functionality. For example, you could create a
  189. group ``'Special users'``, and you could write code that could, say, give them
  190. access to a members-only portion of your site, or send them members-only email
  191. messages.
  192. Programmatically creating permissions
  193. -------------------------------------
  194. While :ref:`custom permissions <custom-permissions>` can be defined within
  195. a model's ``Meta`` class, you can also create permissions directly. For
  196. example, you can create the ``can_publish`` permission for a ``BlogPost`` model
  197. in ``myapp``::
  198. from myapp.models import BlogPost
  199. from django.contrib.auth.models import Permission
  200. from django.contrib.contenttypes.models import ContentType
  201. content_type = ContentType.objects.get_for_model(BlogPost)
  202. permission = Permission.objects.create(
  203. codename="can_publish",
  204. name="Can Publish Posts",
  205. content_type=content_type,
  206. )
  207. The permission can then be assigned to a
  208. :class:`~django.contrib.auth.models.User` via its ``user_permissions``
  209. attribute or to a :class:`~django.contrib.auth.models.Group` via its
  210. ``permissions`` attribute.
  211. .. admonition:: Proxy models need their own content type
  212. If you want to create :ref:`permissions for a proxy model
  213. <proxy-models-permissions-topic>`, pass ``for_concrete_model=False`` to
  214. :meth:`.ContentTypeManager.get_for_model` to get the appropriate
  215. ``ContentType``::
  216. content_type = ContentType.objects.get_for_model(
  217. BlogPostProxy, for_concrete_model=False
  218. )
  219. Permission caching
  220. ------------------
  221. The :class:`~django.contrib.auth.backends.ModelBackend` caches permissions on
  222. the user object after the first time they need to be fetched for a permissions
  223. check. This is typically fine for the request-response cycle since permissions
  224. aren't typically checked immediately after they are added (in the admin, for
  225. example). If you are adding permissions and checking them immediately
  226. afterward, in a test or view for example, the easiest solution is to re-fetch
  227. the user from the database. For example::
  228. from django.contrib.auth.models import Permission, User
  229. from django.contrib.contenttypes.models import ContentType
  230. from django.shortcuts import get_object_or_404
  231. from myapp.models import BlogPost
  232. def user_gains_perms(request, user_id):
  233. user = get_object_or_404(User, pk=user_id)
  234. # any permission check will cache the current set of permissions
  235. user.has_perm("myapp.change_blogpost")
  236. content_type = ContentType.objects.get_for_model(BlogPost)
  237. permission = Permission.objects.get(
  238. codename="change_blogpost",
  239. content_type=content_type,
  240. )
  241. user.user_permissions.add(permission)
  242. # Checking the cached permission set
  243. user.has_perm("myapp.change_blogpost") # False
  244. # Request new instance of User
  245. # Be aware that user.refresh_from_db() won't clear the cache.
  246. user = get_object_or_404(User, pk=user_id)
  247. # Permission cache is repopulated from the database
  248. user.has_perm("myapp.change_blogpost") # True
  249. ...
  250. .. _proxy-models-permissions-topic:
  251. Proxy models
  252. ------------
  253. Proxy models work exactly the same way as concrete models. Permissions are
  254. created using the own content type of the proxy model. Proxy models don't
  255. inherit the permissions of the concrete model they subclass::
  256. class Person(models.Model):
  257. class Meta:
  258. permissions = [("can_eat_pizzas", "Can eat pizzas")]
  259. class Student(Person):
  260. class Meta:
  261. proxy = True
  262. permissions = [("can_deliver_pizzas", "Can deliver pizzas")]
  263. .. code-block:: pycon
  264. >>> # Fetch the content type for the proxy model.
  265. >>> content_type = ContentType.objects.get_for_model(Student, for_concrete_model=False)
  266. >>> student_permissions = Permission.objects.filter(content_type=content_type)
  267. >>> [p.codename for p in student_permissions]
  268. ['add_student', 'change_student', 'delete_student', 'view_student',
  269. 'can_deliver_pizzas']
  270. >>> for permission in student_permissions:
  271. ... user.user_permissions.add(permission)
  272. ...
  273. >>> user.has_perm("app.add_person")
  274. False
  275. >>> user.has_perm("app.can_eat_pizzas")
  276. False
  277. >>> user.has_perms(("app.add_student", "app.can_deliver_pizzas"))
  278. True
  279. .. _auth-web-requests:
  280. Authentication in web requests
  281. ==============================
  282. Django uses :doc:`sessions </topics/http/sessions>` and middleware to hook the
  283. authentication system into :class:`request objects <django.http.HttpRequest>`.
  284. These provide a :attr:`request.user <django.http.HttpRequest.user>` attribute
  285. and a :meth:`request.auser <django.http.HttpRequest.auser>` async method
  286. on every request which represents the current user. If the current user has not
  287. logged in, this attribute will be set to an instance
  288. of :class:`~django.contrib.auth.models.AnonymousUser`, otherwise it will be an
  289. instance of :class:`~django.contrib.auth.models.User`.
  290. You can tell them apart with
  291. :attr:`~django.contrib.auth.models.User.is_authenticated`, like so::
  292. if request.user.is_authenticated:
  293. # Do something for authenticated users.
  294. ...
  295. else:
  296. # Do something for anonymous users.
  297. ...
  298. Or in an asynchronous view::
  299. user = await request.auser()
  300. if user.is_authenticated:
  301. # Do something for authenticated users.
  302. ...
  303. else:
  304. # Do something for anonymous users.
  305. ...
  306. .. versionchanged:: 5.0
  307. The :meth:`.HttpRequest.auser` method was added.
  308. .. _how-to-log-a-user-in:
  309. How to log a user in
  310. --------------------
  311. If you have an authenticated user you want to attach to the current session
  312. - this is done with a :func:`~django.contrib.auth.login` function.
  313. .. function:: login(request, user, backend=None)
  314. .. function:: alogin(request, user, backend=None)
  315. *Asynchronous version*: ``alogin()``
  316. To log a user in, from a view, use :func:`~django.contrib.auth.login()`. It
  317. takes an :class:`~django.http.HttpRequest` object and a
  318. :class:`~django.contrib.auth.models.User` object.
  319. :func:`~django.contrib.auth.login()` saves the user's ID in the session,
  320. using Django's session framework.
  321. Note that any data set during the anonymous session is retained in the
  322. session after a user logs in.
  323. This example shows how you might use both
  324. :func:`~django.contrib.auth.authenticate()` and
  325. :func:`~django.contrib.auth.login()`::
  326. from django.contrib.auth import authenticate, login
  327. def my_view(request):
  328. username = request.POST["username"]
  329. password = request.POST["password"]
  330. user = authenticate(request, username=username, password=password)
  331. if user is not None:
  332. login(request, user)
  333. # Redirect to a success page.
  334. ...
  335. else:
  336. # Return an 'invalid login' error message.
  337. ...
  338. .. versionchanged:: 5.0
  339. ``alogin()`` function was added.
  340. Selecting the authentication backend
  341. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  342. When a user logs in, the user's ID and the backend that was used for
  343. authentication are saved in the user's session. This allows the same
  344. :ref:`authentication backend <authentication-backends>` to fetch the user's
  345. details on a future request. The authentication backend to save in the session
  346. is selected as follows:
  347. #. Use the value of the optional ``backend`` argument, if provided.
  348. #. Use the value of the ``user.backend`` attribute, if present. This allows
  349. pairing :func:`~django.contrib.auth.authenticate()` and
  350. :func:`~django.contrib.auth.login()`:
  351. :func:`~django.contrib.auth.authenticate()`
  352. sets the ``user.backend`` attribute on the user object it returns.
  353. #. Use the ``backend`` in :setting:`AUTHENTICATION_BACKENDS`, if there is only
  354. one.
  355. #. Otherwise, raise an exception.
  356. In cases 1 and 2, the value of the ``backend`` argument or the ``user.backend``
  357. attribute should be a dotted import path string (like that found in
  358. :setting:`AUTHENTICATION_BACKENDS`), not the actual backend class.
  359. How to log a user out
  360. ---------------------
  361. .. function:: logout(request)
  362. .. function:: alogout(request)
  363. *Asynchronous version*: ``alogout()``
  364. To log out a user who has been logged in via
  365. :func:`django.contrib.auth.login()`, use
  366. :func:`django.contrib.auth.logout()` within your view. It takes an
  367. :class:`~django.http.HttpRequest` object and has no return value.
  368. Example::
  369. from django.contrib.auth import logout
  370. def logout_view(request):
  371. logout(request)
  372. # Redirect to a success page.
  373. Note that :func:`~django.contrib.auth.logout()` doesn't throw any errors if
  374. the user wasn't logged in.
  375. When you call :func:`~django.contrib.auth.logout()`, the session data for
  376. the current request is completely cleaned out. All existing data is
  377. removed. This is to prevent another person from using the same web browser
  378. to log in and have access to the previous user's session data. If you want
  379. to put anything into the session that will be available to the user
  380. immediately after logging out, do that *after* calling
  381. :func:`django.contrib.auth.logout()`.
  382. .. versionchanged:: 5.0
  383. ``alogout()`` function was added.
  384. Limiting access to logged-in users
  385. ----------------------------------
  386. The raw way
  387. ~~~~~~~~~~~
  388. The raw way to limit access to pages is to check
  389. :attr:`request.user.is_authenticated
  390. <django.contrib.auth.models.User.is_authenticated>` and either redirect to a
  391. login page::
  392. from django.conf import settings
  393. from django.shortcuts import redirect
  394. def my_view(request):
  395. if not request.user.is_authenticated:
  396. return redirect(f"{settings.LOGIN_URL}?next={request.path}")
  397. # ...
  398. ...or display an error message::
  399. from django.shortcuts import render
  400. def my_view(request):
  401. if not request.user.is_authenticated:
  402. return render(request, "myapp/login_error.html")
  403. # ...
  404. .. currentmodule:: django.contrib.auth.decorators
  405. The ``login_required`` decorator
  406. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  407. .. function:: login_required(redirect_field_name='next', login_url=None)
  408. As a shortcut, you can use the convenient
  409. :func:`~django.contrib.auth.decorators.login_required` decorator::
  410. from django.contrib.auth.decorators import login_required
  411. @login_required
  412. def my_view(request): ...
  413. :func:`~django.contrib.auth.decorators.login_required` does the following:
  414. * If the user isn't logged in, redirect to
  415. :setting:`settings.LOGIN_URL <LOGIN_URL>`, passing the current absolute
  416. path in the query string. Example: ``/accounts/login/?next=/polls/3/``.
  417. * If the user is logged in, execute the view normally. The view code is
  418. free to assume the user is logged in.
  419. By default, the path that the user should be redirected to upon
  420. successful authentication is stored in a query string parameter called
  421. ``"next"``. If you would prefer to use a different name for this parameter,
  422. :func:`~django.contrib.auth.decorators.login_required` takes an
  423. optional ``redirect_field_name`` parameter::
  424. from django.contrib.auth.decorators import login_required
  425. @login_required(redirect_field_name="my_redirect_field")
  426. def my_view(request): ...
  427. Note that if you provide a value to ``redirect_field_name``, you will most
  428. likely need to customize your login template as well, since the template
  429. context variable which stores the redirect path will use the value of
  430. ``redirect_field_name`` as its key rather than ``"next"`` (the default).
  431. :func:`~django.contrib.auth.decorators.login_required` also takes an
  432. optional ``login_url`` parameter. Example::
  433. from django.contrib.auth.decorators import login_required
  434. @login_required(login_url="/accounts/login/")
  435. def my_view(request): ...
  436. Note that if you don't specify the ``login_url`` parameter, you'll need to
  437. ensure that the :setting:`settings.LOGIN_URL <LOGIN_URL>` and your login
  438. view are properly associated. For example, using the defaults, add the
  439. following lines to your URLconf::
  440. from django.contrib.auth import views as auth_views
  441. path("accounts/login/", auth_views.LoginView.as_view()),
  442. The :setting:`settings.LOGIN_URL <LOGIN_URL>` also accepts view function
  443. names and :ref:`named URL patterns <naming-url-patterns>`. This allows you
  444. to freely remap your login view within your URLconf without having to
  445. update the setting.
  446. .. note::
  447. The ``login_required`` decorator does NOT check the ``is_active`` flag on a
  448. user, but the default :setting:`AUTHENTICATION_BACKENDS` reject inactive
  449. users.
  450. .. seealso::
  451. If you are writing custom views for Django's admin (or need the same
  452. authorization check that the built-in views use), you may find the
  453. :func:`django.contrib.admin.views.decorators.staff_member_required`
  454. decorator a useful alternative to ``login_required()``.
  455. .. currentmodule:: django.contrib.auth.mixins
  456. The ``LoginRequiredMixin`` mixin
  457. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  458. When using :doc:`class-based views </topics/class-based-views/index>`, you can
  459. achieve the same behavior as with ``login_required`` by using the
  460. ``LoginRequiredMixin``. This mixin should be at the leftmost position in the
  461. inheritance list.
  462. .. class:: LoginRequiredMixin
  463. If a view is using this mixin, all requests by non-authenticated users will
  464. be redirected to the login page or shown an HTTP 403 Forbidden error,
  465. depending on the
  466. :attr:`~django.contrib.auth.mixins.AccessMixin.raise_exception` parameter.
  467. You can set any of the parameters of
  468. :class:`~django.contrib.auth.mixins.AccessMixin` to customize the handling
  469. of unauthorized users::
  470. from django.contrib.auth.mixins import LoginRequiredMixin
  471. class MyView(LoginRequiredMixin, View):
  472. login_url = "/login/"
  473. redirect_field_name = "redirect_to"
  474. .. note::
  475. Just as the ``login_required`` decorator, this mixin does NOT check the
  476. ``is_active`` flag on a user, but the default
  477. :setting:`AUTHENTICATION_BACKENDS` reject inactive users.
  478. .. currentmodule:: django.contrib.auth.decorators
  479. Limiting access to logged-in users that pass a test
  480. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  481. To limit access based on certain permissions or some other test, you'd do
  482. essentially the same thing as described in the previous section.
  483. You can run your test on :attr:`request.user <django.http.HttpRequest.user>` in
  484. the view directly. For example, this view checks to make sure the user has an
  485. email in the desired domain and if not, redirects to the login page::
  486. from django.shortcuts import redirect
  487. def my_view(request):
  488. if not request.user.email.endswith("@example.com"):
  489. return redirect("/login/?next=%s" % request.path)
  490. # ...
  491. .. function:: user_passes_test(test_func, login_url=None, redirect_field_name='next')
  492. As a shortcut, you can use the convenient ``user_passes_test`` decorator
  493. which performs a redirect when the callable returns ``False``::
  494. from django.contrib.auth.decorators import user_passes_test
  495. def email_check(user):
  496. return user.email.endswith("@example.com")
  497. @user_passes_test(email_check)
  498. def my_view(request): ...
  499. :func:`~django.contrib.auth.decorators.user_passes_test` takes a required
  500. argument: a callable that takes a
  501. :class:`~django.contrib.auth.models.User` object and returns ``True`` if
  502. the user is allowed to view the page. Note that
  503. :func:`~django.contrib.auth.decorators.user_passes_test` does not
  504. automatically check that the :class:`~django.contrib.auth.models.User` is
  505. not anonymous.
  506. :func:`~django.contrib.auth.decorators.user_passes_test` takes two
  507. optional arguments:
  508. ``login_url``
  509. Lets you specify the URL that users who don't pass the test will be
  510. redirected to. It may be a login page and defaults to
  511. :setting:`settings.LOGIN_URL <LOGIN_URL>` if you don't specify one.
  512. ``redirect_field_name``
  513. Same as for :func:`~django.contrib.auth.decorators.login_required`.
  514. Setting it to ``None`` removes it from the URL, which you may want to do
  515. if you are redirecting users that don't pass the test to a non-login
  516. page where there's no "next page".
  517. For example::
  518. @user_passes_test(email_check, login_url="/login/")
  519. def my_view(request): ...
  520. .. currentmodule:: django.contrib.auth.mixins
  521. .. class:: UserPassesTestMixin
  522. When using :doc:`class-based views </topics/class-based-views/index>`, you
  523. can use the ``UserPassesTestMixin`` to do this.
  524. .. method:: test_func()
  525. You have to override the ``test_func()`` method of the class to
  526. provide the test that is performed. Furthermore, you can set any of the
  527. parameters of :class:`~django.contrib.auth.mixins.AccessMixin` to
  528. customize the handling of unauthorized users::
  529. from django.contrib.auth.mixins import UserPassesTestMixin
  530. class MyView(UserPassesTestMixin, View):
  531. def test_func(self):
  532. return self.request.user.email.endswith("@example.com")
  533. .. method:: get_test_func()
  534. You can also override the ``get_test_func()`` method to have the mixin
  535. use a differently named function for its checks (instead of
  536. :meth:`test_func`).
  537. .. admonition:: Stacking ``UserPassesTestMixin``
  538. Due to the way ``UserPassesTestMixin`` is implemented, you cannot stack
  539. them in your inheritance list. The following does NOT work::
  540. class TestMixin1(UserPassesTestMixin):
  541. def test_func(self):
  542. return self.request.user.email.endswith("@example.com")
  543. class TestMixin2(UserPassesTestMixin):
  544. def test_func(self):
  545. return self.request.user.username.startswith("django")
  546. class MyView(TestMixin1, TestMixin2, View): ...
  547. If ``TestMixin1`` would call ``super()`` and take that result into
  548. account, ``TestMixin1`` wouldn't work standalone anymore.
  549. .. currentmodule:: django.contrib.auth.decorators
  550. The ``permission_required`` decorator
  551. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  552. .. function:: permission_required(perm, login_url=None, raise_exception=False)
  553. It's a relatively common task to check whether a user has a particular
  554. permission. For that reason, Django provides a shortcut for that case: the
  555. :func:`~django.contrib.auth.decorators.permission_required()` decorator.::
  556. from django.contrib.auth.decorators import permission_required
  557. @permission_required("polls.add_choice")
  558. def my_view(request): ...
  559. Just like the :meth:`~django.contrib.auth.models.User.has_perm` method,
  560. permission names take the form ``"<app label>.<permission codename>"``
  561. (i.e. ``polls.add_choice`` for a permission on a model in the ``polls``
  562. application).
  563. The decorator may also take an iterable of permissions, in which case the
  564. user must have all of the permissions in order to access the view.
  565. Note that :func:`~django.contrib.auth.decorators.permission_required()`
  566. also takes an optional ``login_url`` parameter::
  567. from django.contrib.auth.decorators import permission_required
  568. @permission_required("polls.add_choice", login_url="/loginpage/")
  569. def my_view(request): ...
  570. As in the :func:`~django.contrib.auth.decorators.login_required` decorator,
  571. ``login_url`` defaults to :setting:`settings.LOGIN_URL <LOGIN_URL>`.
  572. If the ``raise_exception`` parameter is given, the decorator will raise
  573. :exc:`~django.core.exceptions.PermissionDenied`, prompting :ref:`the 403
  574. (HTTP Forbidden) view<http_forbidden_view>` instead of redirecting to the
  575. login page.
  576. If you want to use ``raise_exception`` but also give your users a chance to
  577. login first, you can add the
  578. :func:`~django.contrib.auth.decorators.login_required` decorator::
  579. from django.contrib.auth.decorators import login_required, permission_required
  580. @login_required
  581. @permission_required("polls.add_choice", raise_exception=True)
  582. def my_view(request): ...
  583. This also avoids a redirect loop when :class:`.LoginView`'s
  584. ``redirect_authenticated_user=True`` and the logged-in user doesn't have
  585. all of the required permissions.
  586. .. currentmodule:: django.contrib.auth.mixins
  587. The ``PermissionRequiredMixin`` mixin
  588. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  589. To apply permission checks to :doc:`class-based views
  590. </ref/class-based-views/index>`, you can use the ``PermissionRequiredMixin``:
  591. .. class:: PermissionRequiredMixin
  592. This mixin, just like the ``permission_required``
  593. decorator, checks whether the user accessing a view has all given
  594. permissions. You should specify the permission (or an iterable of
  595. permissions) using the ``permission_required`` parameter::
  596. from django.contrib.auth.mixins import PermissionRequiredMixin
  597. class MyView(PermissionRequiredMixin, View):
  598. permission_required = "polls.add_choice"
  599. # Or multiple of permissions:
  600. permission_required = ["polls.view_choice", "polls.change_choice"]
  601. You can set any of the parameters of
  602. :class:`~django.contrib.auth.mixins.AccessMixin` to customize the handling
  603. of unauthorized users.
  604. You may also override these methods:
  605. .. method:: get_permission_required()
  606. Returns an iterable of permission names used by the mixin. Defaults to
  607. the ``permission_required`` attribute, converted to a tuple if
  608. necessary.
  609. .. method:: has_permission()
  610. Returns a boolean denoting whether the current user has permission to
  611. execute the decorated view. By default, this returns the result of
  612. calling :meth:`~django.contrib.auth.models.User.has_perms()` with the
  613. list of permissions returned by :meth:`get_permission_required()`.
  614. Redirecting unauthorized requests in class-based views
  615. ------------------------------------------------------
  616. To ease the handling of access restrictions in :doc:`class-based views
  617. </ref/class-based-views/index>`, the ``AccessMixin`` can be used to configure
  618. the behavior of a view when access is denied. Authenticated users are denied
  619. access with an HTTP 403 Forbidden response. Anonymous users are redirected to
  620. the login page or shown an HTTP 403 Forbidden response, depending on the
  621. :attr:`~django.contrib.auth.mixins.AccessMixin.raise_exception` attribute.
  622. .. class:: AccessMixin
  623. .. attribute:: login_url
  624. Default return value for :meth:`get_login_url`. Defaults to ``None``
  625. in which case :meth:`get_login_url` falls back to
  626. :setting:`settings.LOGIN_URL <LOGIN_URL>`.
  627. .. attribute:: permission_denied_message
  628. Default return value for :meth:`get_permission_denied_message`.
  629. Defaults to an empty string.
  630. .. attribute:: redirect_field_name
  631. Default return value for :meth:`get_redirect_field_name`. Defaults to
  632. ``"next"``.
  633. .. attribute:: raise_exception
  634. If this attribute is set to ``True``, a
  635. :class:`~django.core.exceptions.PermissionDenied` exception is raised
  636. when the conditions are not met. When ``False`` (the default),
  637. anonymous users are redirected to the login page.
  638. .. method:: get_login_url()
  639. Returns the URL that users who don't pass the test will be redirected
  640. to. Returns :attr:`login_url` if set, or :setting:`settings.LOGIN_URL
  641. <LOGIN_URL>` otherwise.
  642. .. method:: get_permission_denied_message()
  643. When :attr:`raise_exception` is ``True``, this method can be used to
  644. control the error message passed to the error handler for display to
  645. the user. Returns the :attr:`permission_denied_message` attribute by
  646. default.
  647. .. method:: get_redirect_field_name()
  648. Returns the name of the query parameter that will contain the URL the
  649. user should be redirected to after a successful login. If you set this
  650. to ``None``, a query parameter won't be added. Returns the
  651. :attr:`redirect_field_name` attribute by default.
  652. .. method:: handle_no_permission()
  653. Depending on the value of ``raise_exception``, the method either raises
  654. a :exc:`~django.core.exceptions.PermissionDenied` exception or
  655. redirects the user to the ``login_url``, optionally including the
  656. ``redirect_field_name`` if it is set.
  657. .. currentmodule:: django.contrib.auth
  658. .. _session-invalidation-on-password-change:
  659. Session invalidation on password change
  660. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  661. If your :setting:`AUTH_USER_MODEL` inherits from
  662. :class:`~django.contrib.auth.models.AbstractBaseUser` or implements its own
  663. :meth:`~django.contrib.auth.models.AbstractBaseUser.get_session_auth_hash()`
  664. method, authenticated sessions will include the hash returned by this function.
  665. In the :class:`~django.contrib.auth.models.AbstractBaseUser` case, this is an
  666. HMAC of the password field. Django verifies that the hash in the session for
  667. each request matches the one that's computed during the request. This allows a
  668. user to log out all of their sessions by changing their password.
  669. The default password change views included with Django,
  670. :class:`~django.contrib.auth.views.PasswordChangeView` and the
  671. ``user_change_password`` view in the :mod:`django.contrib.auth` admin, update
  672. the session with the new password hash so that a user changing their own
  673. password won't log themselves out. If you have a custom password change view
  674. and wish to have similar behavior, use the :func:`update_session_auth_hash`
  675. function.
  676. .. function:: update_session_auth_hash(request, user)
  677. .. function:: aupdate_session_auth_hash(request, user)
  678. *Asynchronous version*: ``aupdate_session_auth_hash()``
  679. This function takes the current request and the updated user object from
  680. which the new session hash will be derived and updates the session hash
  681. appropriately. It also rotates the session key so that a stolen session
  682. cookie will be invalidated.
  683. Example usage::
  684. from django.contrib.auth import update_session_auth_hash
  685. def password_change(request):
  686. if request.method == "POST":
  687. form = PasswordChangeForm(user=request.user, data=request.POST)
  688. if form.is_valid():
  689. form.save()
  690. update_session_auth_hash(request, form.user)
  691. else:
  692. ...
  693. .. versionchanged:: 5.0
  694. ``aupdate_session_auth_hash()`` function was added.
  695. .. note::
  696. Since
  697. :meth:`~django.contrib.auth.models.AbstractBaseUser.get_session_auth_hash()`
  698. is based on :setting:`SECRET_KEY`, secret key values must be
  699. rotated to avoid invalidating existing sessions when updating your site to
  700. use a new secret. See :setting:`SECRET_KEY_FALLBACKS` for details.
  701. .. _built-in-auth-views:
  702. Authentication Views
  703. --------------------
  704. .. module:: django.contrib.auth.views
  705. Django provides several views that you can use for handling login, logout, and
  706. password management. These make use of the :ref:`stock auth forms
  707. <built-in-auth-forms>` but you can pass in your own forms as well.
  708. Django provides no default template for the authentication views. You should
  709. create your own templates for the views you want to use. The template context
  710. is documented in each view, see :ref:`all-authentication-views`.
  711. .. _using-the-views:
  712. Using the views
  713. ~~~~~~~~~~~~~~~
  714. There are different methods to implement these views in your project. The
  715. easiest way is to include the provided URLconf in ``django.contrib.auth.urls``
  716. in your own URLconf, for example::
  717. urlpatterns = [
  718. path("accounts/", include("django.contrib.auth.urls")),
  719. ]
  720. This will include the following URL patterns:
  721. .. code-block:: text
  722. accounts/login/ [name='login']
  723. accounts/logout/ [name='logout']
  724. accounts/password_change/ [name='password_change']
  725. accounts/password_change/done/ [name='password_change_done']
  726. accounts/password_reset/ [name='password_reset']
  727. accounts/password_reset/done/ [name='password_reset_done']
  728. accounts/reset/<uidb64>/<token>/ [name='password_reset_confirm']
  729. accounts/reset/done/ [name='password_reset_complete']
  730. The views provide a URL name for easier reference. See :doc:`the URL
  731. documentation </topics/http/urls>` for details on using named URL patterns.
  732. If you want more control over your URLs, you can reference a specific view in
  733. your URLconf::
  734. from django.contrib.auth import views as auth_views
  735. urlpatterns = [
  736. path("change-password/", auth_views.PasswordChangeView.as_view()),
  737. ]
  738. The views have optional arguments you can use to alter the behavior of the
  739. view. For example, if you want to change the template name a view uses, you can
  740. provide the ``template_name`` argument. A way to do this is to provide keyword
  741. arguments in the URLconf, these will be passed on to the view. For example::
  742. urlpatterns = [
  743. path(
  744. "change-password/",
  745. auth_views.PasswordChangeView.as_view(template_name="change-password.html"),
  746. ),
  747. ]
  748. All views are :doc:`class-based </topics/class-based-views/index>`, which allows
  749. you to easily customize them by subclassing.
  750. .. _all-authentication-views:
  751. All authentication views
  752. ~~~~~~~~~~~~~~~~~~~~~~~~
  753. This is a list with all the views ``django.contrib.auth`` provides. For
  754. implementation details see :ref:`using-the-views`.
  755. .. class:: LoginView
  756. **URL name:** ``login``
  757. See :doc:`the URL documentation </topics/http/urls>` for details on using
  758. named URL patterns.
  759. **Methods and Attributes**
  760. .. attribute:: template_name
  761. The name of a template to display for the view used to log the user in.
  762. Defaults to :file:`registration/login.html`.
  763. .. attribute:: next_page
  764. The URL to redirect to after login. Defaults to
  765. :setting:`LOGIN_REDIRECT_URL`.
  766. .. attribute:: redirect_field_name
  767. The name of a ``GET`` field containing the URL to redirect to after
  768. login. Defaults to ``next``. Overrides the
  769. :meth:`get_default_redirect_url` URL if the given ``GET`` parameter is
  770. passed.
  771. .. attribute:: authentication_form
  772. A callable (typically a form class) to use for authentication. Defaults
  773. to :class:`~django.contrib.auth.forms.AuthenticationForm`.
  774. .. attribute:: extra_context
  775. A dictionary of context data that will be added to the default context
  776. data passed to the template.
  777. .. attribute:: redirect_authenticated_user
  778. A boolean that controls whether or not authenticated users accessing
  779. the login page will be redirected as if they had just successfully
  780. logged in. Defaults to ``False``.
  781. .. warning::
  782. If you enable ``redirect_authenticated_user``, other websites will
  783. be able to determine if their visitors are authenticated on your
  784. site by requesting redirect URLs to image files on your website. To
  785. avoid this "`social media fingerprinting
  786. <https://robinlinus.github.io/socialmedia-leak/>`_" information
  787. leakage, host all images and your favicon on a separate domain.
  788. Enabling ``redirect_authenticated_user`` can also result in a
  789. redirect loop when using the :func:`.permission_required` decorator
  790. unless the ``raise_exception`` parameter is used.
  791. .. attribute:: success_url_allowed_hosts
  792. A :class:`set` of hosts, in addition to :meth:`request.get_host()
  793. <django.http.HttpRequest.get_host>`, that are safe for redirecting
  794. after login. Defaults to an empty :class:`set`.
  795. .. method:: get_default_redirect_url()
  796. Returns the URL to redirect to after login. The default implementation
  797. resolves and returns :attr:`next_page` if set, or
  798. :setting:`LOGIN_REDIRECT_URL` otherwise.
  799. Here's what ``LoginView`` does:
  800. * If called via ``GET``, it displays a login form that POSTs to the
  801. same URL. More on this in a bit.
  802. * If called via ``POST`` with user submitted credentials, it tries to log
  803. the user in. If login is successful, the view redirects to the URL
  804. specified in ``next``. If ``next`` isn't provided, it redirects to
  805. :setting:`settings.LOGIN_REDIRECT_URL <LOGIN_REDIRECT_URL>` (which
  806. defaults to ``/accounts/profile/``). If login isn't successful, it
  807. redisplays the login form.
  808. It's your responsibility to provide the html for the login template
  809. , called ``registration/login.html`` by default. This template gets passed
  810. four template context variables:
  811. * ``form``: A :class:`~django.forms.Form` object representing the
  812. :class:`~django.contrib.auth.forms.AuthenticationForm`.
  813. * ``next``: The URL to redirect to after successful login. This may
  814. contain a query string, too.
  815. * ``site``: The current :class:`~django.contrib.sites.models.Site`,
  816. according to the :setting:`SITE_ID` setting. If you don't have the
  817. site framework installed, this will be set to an instance of
  818. :class:`~django.contrib.sites.requests.RequestSite`, which derives the
  819. site name and domain from the current
  820. :class:`~django.http.HttpRequest`.
  821. * ``site_name``: An alias for ``site.name``. If you don't have the site
  822. framework installed, this will be set to the value of
  823. :attr:`request.META['SERVER_NAME'] <django.http.HttpRequest.META>`.
  824. For more on sites, see :doc:`/ref/contrib/sites`.
  825. If you'd prefer not to call the template :file:`registration/login.html`,
  826. you can pass the ``template_name`` parameter via the extra arguments to
  827. the ``as_view`` method in your URLconf. For example, this URLconf line would
  828. use :file:`myapp/login.html` instead::
  829. path("accounts/login/", auth_views.LoginView.as_view(template_name="myapp/login.html")),
  830. You can also specify the name of the ``GET`` field which contains the URL
  831. to redirect to after login using ``redirect_field_name``. By default, the
  832. field is called ``next``.
  833. Here's a sample :file:`registration/login.html` template you can use as a
  834. starting point. It assumes you have a :file:`base.html` template that
  835. defines a ``content`` block:
  836. .. code-block:: html+django
  837. {% extends "base.html" %}
  838. {% block content %}
  839. {% if form.errors %}
  840. <p>Your username and password didn't match. Please try again.</p>
  841. {% endif %}
  842. {% if next %}
  843. {% if user.is_authenticated %}
  844. <p>Your account doesn't have access to this page. To proceed,
  845. please login with an account that has access.</p>
  846. {% else %}
  847. <p>Please login to see this page.</p>
  848. {% endif %}
  849. {% endif %}
  850. <form method="post" action="{% url 'login' %}">
  851. {% csrf_token %}
  852. <table>
  853. <tr>
  854. <td>{{ form.username.label_tag }}</td>
  855. <td>{{ form.username }}</td>
  856. </tr>
  857. <tr>
  858. <td>{{ form.password.label_tag }}</td>
  859. <td>{{ form.password }}</td>
  860. </tr>
  861. </table>
  862. <input type="submit" value="login">
  863. <input type="hidden" name="next" value="{{ next }}">
  864. </form>
  865. {# Assumes you set up the password_reset view in your URLconf #}
  866. <p><a href="{% url 'password_reset' %}">Lost password?</a></p>
  867. {% endblock %}
  868. If you have customized authentication (see :doc:`Customizing Authentication
  869. </topics/auth/customizing>`) you can use a custom authentication form by
  870. setting the ``authentication_form`` attribute. This form must accept a
  871. ``request`` keyword argument in its ``__init__()`` method and provide a
  872. ``get_user()`` method which returns the authenticated user object (this
  873. method is only ever called after successful form validation).
  874. .. class:: LogoutView
  875. Logs a user out on ``POST`` requests.
  876. **URL name:** ``logout``
  877. **Attributes:**
  878. .. attribute:: next_page
  879. The URL to redirect to after logout. Defaults to
  880. :setting:`LOGOUT_REDIRECT_URL`.
  881. .. attribute:: template_name
  882. The full name of a template to display after logging the user out.
  883. Defaults to :file:`registration/logged_out.html`.
  884. .. attribute:: redirect_field_name
  885. The name of a ``GET`` field containing the URL to redirect to after log
  886. out. Defaults to ``'next'``. Overrides the
  887. :attr:`next_page` URL if the given ``GET`` parameter is
  888. passed.
  889. .. attribute:: extra_context
  890. A dictionary of context data that will be added to the default context
  891. data passed to the template.
  892. .. attribute:: success_url_allowed_hosts
  893. A :class:`set` of hosts, in addition to :meth:`request.get_host()
  894. <django.http.HttpRequest.get_host>`, that are safe for redirecting
  895. after logout. Defaults to an empty :class:`set`.
  896. **Template context:**
  897. * ``title``: The string "Logged out", localized.
  898. * ``site``: The current :class:`~django.contrib.sites.models.Site`,
  899. according to the :setting:`SITE_ID` setting. If you don't have the
  900. site framework installed, this will be set to an instance of
  901. :class:`~django.contrib.sites.requests.RequestSite`, which derives the
  902. site name and domain from the current
  903. :class:`~django.http.HttpRequest`.
  904. * ``site_name``: An alias for ``site.name``. If you don't have the site
  905. framework installed, this will be set to the value of
  906. :attr:`request.META['SERVER_NAME'] <django.http.HttpRequest.META>`.
  907. For more on sites, see :doc:`/ref/contrib/sites`.
  908. .. function:: logout_then_login(request, login_url=None)
  909. Logs a user out on ``POST`` requests, then redirects to the login page.
  910. **URL name:** No default URL provided
  911. **Optional arguments:**
  912. * ``login_url``: The URL of the login page to redirect to.
  913. Defaults to :setting:`settings.LOGIN_URL <LOGIN_URL>` if not supplied.
  914. .. class:: PasswordChangeView
  915. **URL name:** ``password_change``
  916. Allows a user to change their password.
  917. **Attributes:**
  918. .. attribute:: template_name
  919. The full name of a template to use for displaying the password change
  920. form. Defaults to :file:`registration/password_change_form.html` if not
  921. supplied.
  922. .. attribute:: success_url
  923. The URL to redirect to after a successful password change. Defaults to
  924. ``'password_change_done'``.
  925. .. attribute:: form_class
  926. A custom "change password" form which must accept a ``user`` keyword
  927. argument. The form is responsible for actually changing the user's
  928. password. Defaults to
  929. :class:`~django.contrib.auth.forms.PasswordChangeForm`.
  930. .. attribute:: extra_context
  931. A dictionary of context data that will be added to the default context
  932. data passed to the template.
  933. **Template context:**
  934. * ``form``: The password change form (see ``form_class`` above).
  935. .. class:: PasswordChangeDoneView
  936. **URL name:** ``password_change_done``
  937. The page shown after a user has changed their password.
  938. **Attributes:**
  939. .. attribute:: template_name
  940. The full name of a template to use. Defaults to
  941. :file:`registration/password_change_done.html` if not supplied.
  942. .. attribute:: extra_context
  943. A dictionary of context data that will be added to the default context
  944. data passed to the template.
  945. .. class:: PasswordResetView
  946. **URL name:** ``password_reset``
  947. Allows a user to reset their password by generating a one-time use link
  948. that can be used to reset the password, and sending that link to the
  949. user's registered email address.
  950. This view will send an email if the following conditions are met:
  951. * The email address provided exists in the system.
  952. * The requested user is active (``User.is_active`` is ``True``).
  953. * The requested user has a usable password. Users flagged with an unusable
  954. password (see
  955. :meth:`~django.contrib.auth.models.User.set_unusable_password`) aren't
  956. allowed to request a password reset to prevent misuse when using an
  957. external authentication source like LDAP.
  958. If any of these conditions are *not* met, no email will be sent, but the
  959. user won't receive any error message either. This prevents information
  960. leaking to potential attackers. If you want to provide an error message in
  961. this case, you can subclass
  962. :class:`~django.contrib.auth.forms.PasswordResetForm` and use the
  963. ``form_class`` attribute.
  964. .. note::
  965. Be aware that sending an email costs extra time, hence you may be
  966. vulnerable to an email address enumeration timing attack due to a
  967. difference between the duration of a reset request for an existing
  968. email address and the duration of a reset request for a nonexistent
  969. email address. To reduce the overhead, you can use a 3rd party package
  970. that allows to send emails asynchronously, e.g. :pypi:`django-mailer`.
  971. **Attributes:**
  972. .. attribute:: template_name
  973. The full name of a template to use for displaying the password reset
  974. form. Defaults to :file:`registration/password_reset_form.html` if not
  975. supplied.
  976. .. attribute:: form_class
  977. Form that will be used to get the email of the user to reset the
  978. password for. Defaults to
  979. :class:`~django.contrib.auth.forms.PasswordResetForm`.
  980. .. attribute:: email_template_name
  981. The full name of a template to use for generating the email with the
  982. reset password link. Defaults to
  983. :file:`registration/password_reset_email.html` if not supplied.
  984. .. attribute:: subject_template_name
  985. The full name of a template to use for the subject of the email with
  986. the reset password link. Defaults to
  987. :file:`registration/password_reset_subject.txt` if not supplied.
  988. .. attribute:: token_generator
  989. Instance of the class to check the one time link. This will default to
  990. ``default_token_generator``, it's an instance of
  991. ``django.contrib.auth.tokens.PasswordResetTokenGenerator``.
  992. .. attribute:: success_url
  993. The URL to redirect to after a successful password reset request.
  994. Defaults to ``'password_reset_done'``.
  995. .. attribute:: from_email
  996. A valid email address. By default Django uses the
  997. :setting:`DEFAULT_FROM_EMAIL`.
  998. .. attribute:: extra_context
  999. A dictionary of context data that will be added to the default context
  1000. data passed to the template.
  1001. .. attribute:: html_email_template_name
  1002. The full name of a template to use for generating a
  1003. :mimetype:`text/html` multipart email with the password reset link. By
  1004. default, HTML email is not sent.
  1005. .. attribute:: extra_email_context
  1006. A dictionary of context data that will be available in the email
  1007. template. It can be used to override default template context values
  1008. listed below e.g. ``domain``.
  1009. **Template context:**
  1010. * ``form``: The form (see ``form_class`` above) for resetting the user's
  1011. password.
  1012. **Email template context:**
  1013. * ``email``: An alias for ``user.email``
  1014. * ``user``: The current :class:`~django.contrib.auth.models.User`,
  1015. according to the ``email`` form field. Only active users are able to
  1016. reset their passwords (``User.is_active is True``).
  1017. * ``site_name``: An alias for ``site.name``. If you don't have the site
  1018. framework installed, this will be set to the value of
  1019. :attr:`request.META['SERVER_NAME'] <django.http.HttpRequest.META>`.
  1020. For more on sites, see :doc:`/ref/contrib/sites`.
  1021. * ``domain``: An alias for ``site.domain``. If you don't have the site
  1022. framework installed, this will be set to the value of
  1023. ``request.get_host()``.
  1024. * ``protocol``: http or https
  1025. * ``uid``: The user's primary key encoded in base 64.
  1026. * ``token``: Token to check that the reset link is valid.
  1027. Sample ``registration/password_reset_email.html`` (email body template):
  1028. .. code-block:: html+django
  1029. Someone asked for password reset for email {{ email }}. Follow the link below:
  1030. {{ protocol}}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %}
  1031. The same template context is used for subject template. Subject must be
  1032. single line plain text string.
  1033. .. class:: PasswordResetDoneView
  1034. **URL name:** ``password_reset_done``
  1035. The page shown after a user has been emailed a link to reset their
  1036. password. This view is called by default if the :class:`PasswordResetView`
  1037. doesn't have an explicit ``success_url`` URL set.
  1038. .. note::
  1039. If the email address provided does not exist in the system, the user is
  1040. inactive, or has an unusable password, the user will still be
  1041. redirected to this view but no email will be sent.
  1042. **Attributes:**
  1043. .. attribute:: template_name
  1044. The full name of a template to use. Defaults to
  1045. :file:`registration/password_reset_done.html` if not supplied.
  1046. .. attribute:: extra_context
  1047. A dictionary of context data that will be added to the default context
  1048. data passed to the template.
  1049. .. class:: PasswordResetConfirmView
  1050. **URL name:** ``password_reset_confirm``
  1051. Presents a form for entering a new password.
  1052. **Keyword arguments from the URL:**
  1053. * ``uidb64``: The user's id encoded in base 64.
  1054. * ``token``: Token to check that the password is valid.
  1055. **Attributes:**
  1056. .. attribute:: template_name
  1057. The full name of a template to display the confirm password view.
  1058. Default value is :file:`registration/password_reset_confirm.html`.
  1059. .. attribute:: token_generator
  1060. Instance of the class to check the password. This will default to
  1061. ``default_token_generator``, it's an instance of
  1062. ``django.contrib.auth.tokens.PasswordResetTokenGenerator``.
  1063. .. attribute:: post_reset_login
  1064. A boolean indicating if the user should be automatically authenticated
  1065. after a successful password reset. Defaults to ``False``.
  1066. .. attribute:: post_reset_login_backend
  1067. A dotted path to the authentication backend to use when authenticating
  1068. a user if ``post_reset_login`` is ``True``. Required only if you have
  1069. multiple :setting:`AUTHENTICATION_BACKENDS` configured. Defaults to
  1070. ``None``.
  1071. .. attribute:: form_class
  1072. Form that will be used to set the password. Defaults to
  1073. :class:`~django.contrib.auth.forms.SetPasswordForm`.
  1074. .. attribute:: success_url
  1075. URL to redirect after the password reset done. Defaults to
  1076. ``'password_reset_complete'``.
  1077. .. attribute:: extra_context
  1078. A dictionary of context data that will be added to the default context
  1079. data passed to the template.
  1080. .. attribute:: reset_url_token
  1081. Token parameter displayed as a component of password reset URLs.
  1082. Defaults to ``'set-password'``.
  1083. **Template context:**
  1084. * ``form``: The form (see ``form_class`` above) for setting the new user's
  1085. password.
  1086. * ``validlink``: Boolean, True if the link (combination of ``uidb64`` and
  1087. ``token``) is valid or unused yet.
  1088. .. class:: PasswordResetCompleteView
  1089. **URL name:** ``password_reset_complete``
  1090. Presents a view which informs the user that the password has been
  1091. successfully changed.
  1092. **Attributes:**
  1093. .. attribute:: template_name
  1094. The full name of a template to display the view. Defaults to
  1095. :file:`registration/password_reset_complete.html`.
  1096. .. attribute:: extra_context
  1097. A dictionary of context data that will be added to the default context
  1098. data passed to the template.
  1099. Helper functions
  1100. ----------------
  1101. .. currentmodule:: django.contrib.auth.views
  1102. .. function:: redirect_to_login(next, login_url=None, redirect_field_name='next')
  1103. Redirects to the login page, and then back to another URL after a
  1104. successful login.
  1105. **Required arguments:**
  1106. * ``next``: The URL to redirect to after a successful login.
  1107. **Optional arguments:**
  1108. * ``login_url``: The URL of the login page to redirect to.
  1109. Defaults to :setting:`settings.LOGIN_URL <LOGIN_URL>` if not supplied.
  1110. * ``redirect_field_name``: The name of a ``GET`` field containing the
  1111. URL to redirect to after login. Overrides ``next`` if the given
  1112. ``GET`` parameter is passed.
  1113. .. _built-in-auth-forms:
  1114. Built-in forms
  1115. --------------
  1116. .. module:: django.contrib.auth.forms
  1117. If you don't want to use the built-in views, but want the convenience of not
  1118. having to write forms for this functionality, the authentication system
  1119. provides several built-in forms located in :mod:`django.contrib.auth.forms`:
  1120. .. note::
  1121. The built-in authentication forms make certain assumptions about the user
  1122. model that they are working with. If you're using a :ref:`custom user model
  1123. <auth-custom-user>`, it may be necessary to define your own forms for the
  1124. authentication system. For more information, refer to the documentation
  1125. about :ref:`using the built-in authentication forms with custom user models
  1126. <custom-users-and-the-built-in-auth-forms>`.
  1127. .. class:: AdminPasswordChangeForm
  1128. A form used in the admin interface to change a user's password.
  1129. Takes the ``user`` as the first positional argument.
  1130. .. class:: AuthenticationForm
  1131. A form for logging a user in.
  1132. Takes ``request`` as its first positional argument, which is stored on the
  1133. form instance for use by sub-classes.
  1134. .. method:: confirm_login_allowed(user)
  1135. By default, ``AuthenticationForm`` rejects users whose ``is_active``
  1136. flag is set to ``False``. You may override this behavior with a custom
  1137. policy to determine which users can log in. Do this with a custom form
  1138. that subclasses ``AuthenticationForm`` and overrides the
  1139. ``confirm_login_allowed()`` method. This method should raise a
  1140. :exc:`~django.core.exceptions.ValidationError` if the given user may
  1141. not log in.
  1142. For example, to allow all users to log in regardless of "active"
  1143. status::
  1144. from django.contrib.auth.forms import AuthenticationForm
  1145. class AuthenticationFormWithInactiveUsersOkay(AuthenticationForm):
  1146. def confirm_login_allowed(self, user):
  1147. pass
  1148. (In this case, you'll also need to use an authentication backend that
  1149. allows inactive users, such as
  1150. :class:`~django.contrib.auth.backends.AllowAllUsersModelBackend`.)
  1151. Or to allow only some active users to log in::
  1152. class PickyAuthenticationForm(AuthenticationForm):
  1153. def confirm_login_allowed(self, user):
  1154. if not user.is_active:
  1155. raise ValidationError(
  1156. _("This account is inactive."),
  1157. code="inactive",
  1158. )
  1159. if user.username.startswith("b"):
  1160. raise ValidationError(
  1161. _("Sorry, accounts starting with 'b' aren't welcome here."),
  1162. code="no_b_users",
  1163. )
  1164. .. class:: PasswordChangeForm
  1165. A form for allowing a user to change their password.
  1166. .. class:: PasswordResetForm
  1167. A form for generating and emailing a one-time use link to reset a
  1168. user's password.
  1169. .. method:: send_mail(subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None)
  1170. Uses the arguments to send an ``EmailMultiAlternatives``.
  1171. Can be overridden to customize how the email is sent to the user. If
  1172. you choose to override this method, be mindful of handling potential
  1173. exceptions raised due to email sending failures.
  1174. :param subject_template_name: the template for the subject.
  1175. :param email_template_name: the template for the email body.
  1176. :param context: context passed to the ``subject_template``,
  1177. ``email_template``, and ``html_email_template`` (if it is not
  1178. ``None``).
  1179. :param from_email: the sender's email.
  1180. :param to_email: the email of the requester.
  1181. :param html_email_template_name: the template for the HTML body;
  1182. defaults to ``None``, in which case a plain text email is sent.
  1183. By default, ``save()`` populates the ``context`` with the
  1184. same variables that
  1185. :class:`~django.contrib.auth.views.PasswordResetView` passes to its
  1186. email context.
  1187. .. class:: SetPasswordForm
  1188. A form that lets a user change their password without entering the old
  1189. password.
  1190. .. class:: UserChangeForm
  1191. A form used in the admin interface to change a user's information and
  1192. permissions.
  1193. .. class:: BaseUserCreationForm
  1194. .. versionadded:: 4.2
  1195. A :class:`~django.forms.ModelForm` for creating a new user. This is the
  1196. recommended base class if you need to customize the user creation form.
  1197. It has three fields: ``username`` (from the user model), ``password1``,
  1198. and ``password2``. It verifies that ``password1`` and ``password2`` match,
  1199. validates the password using
  1200. :func:`~django.contrib.auth.password_validation.validate_password`, and
  1201. sets the user's password using
  1202. :meth:`~django.contrib.auth.models.User.set_password()`.
  1203. .. class:: UserCreationForm
  1204. Inherits from :class:`BaseUserCreationForm`. To help prevent confusion with
  1205. similar usernames, the form doesn't allow usernames that differ only in
  1206. case.
  1207. .. versionchanged:: 4.2
  1208. In older versions, :class:`UserCreationForm` didn't save many-to-many
  1209. form fields for a custom user model.
  1210. In older versions, usernames that differ only in case are allowed.
  1211. .. currentmodule:: django.contrib.auth
  1212. Authentication data in templates
  1213. --------------------------------
  1214. The currently logged-in user and their permissions are made available in the
  1215. :doc:`template context </ref/templates/api>` when you use
  1216. :class:`~django.template.RequestContext`.
  1217. .. admonition:: Technicality
  1218. Technically, these variables are only made available in the template
  1219. context if you use :class:`~django.template.RequestContext` and the
  1220. ``'django.contrib.auth.context_processors.auth'`` context processor is
  1221. enabled. It is in the default generated settings file. For more, see the
  1222. :ref:`RequestContext docs <subclassing-context-requestcontext>`.
  1223. Users
  1224. ~~~~~
  1225. When rendering a template :class:`~django.template.RequestContext`, the
  1226. currently logged-in user, either a :class:`~django.contrib.auth.models.User`
  1227. instance or an :class:`~django.contrib.auth.models.AnonymousUser` instance, is
  1228. stored in the template variable ``{{ user }}``:
  1229. .. code-block:: html+django
  1230. {% if user.is_authenticated %}
  1231. <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
  1232. {% else %}
  1233. <p>Welcome, new user. Please log in.</p>
  1234. {% endif %}
  1235. This template context variable is not available if a ``RequestContext`` is not
  1236. being used.
  1237. Permissions
  1238. ~~~~~~~~~~~
  1239. The currently logged-in user's permissions are stored in the template variable
  1240. ``{{ perms }}``. This is an instance of
  1241. ``django.contrib.auth.context_processors.PermWrapper``, which is a
  1242. template-friendly proxy of permissions.
  1243. Evaluating a single-attribute lookup of ``{{ perms }}`` as a boolean is a proxy
  1244. to :meth:`User.has_module_perms()
  1245. <django.contrib.auth.models.User.has_module_perms>`. For example, to check if
  1246. the logged-in user has any permissions in the ``foo`` app:
  1247. .. code-block:: html+django
  1248. {% if perms.foo %}
  1249. Evaluating a two-level-attribute lookup as a boolean is a proxy to
  1250. :meth:`User.has_perm() <django.contrib.auth.models.User.has_perm>`. For example,
  1251. to check if the logged-in user has the permission ``foo.add_vote``:
  1252. .. code-block:: html+django
  1253. {% if perms.foo.add_vote %}
  1254. Here's a more complete example of checking permissions in a template:
  1255. .. code-block:: html+django
  1256. {% if perms.foo %}
  1257. <p>You have permission to do something in the foo app.</p>
  1258. {% if perms.foo.add_vote %}
  1259. <p>You can vote!</p>
  1260. {% endif %}
  1261. {% if perms.foo.add_driving %}
  1262. <p>You can drive!</p>
  1263. {% endif %}
  1264. {% else %}
  1265. <p>You don't have permission to do anything in the foo app.</p>
  1266. {% endif %}
  1267. It is possible to also look permissions up by ``{% if in %}`` statements.
  1268. For example:
  1269. .. code-block:: html+django
  1270. {% if 'foo' in perms %}
  1271. {% if 'foo.add_vote' in perms %}
  1272. <p>In lookup works, too.</p>
  1273. {% endif %}
  1274. {% endif %}
  1275. .. _auth-admin:
  1276. Managing users in the admin
  1277. ===========================
  1278. When you have both ``django.contrib.admin`` and ``django.contrib.auth``
  1279. installed, the admin provides a convenient way to view and manage users,
  1280. groups, and permissions. Users can be created and deleted like any Django
  1281. model. Groups can be created, and permissions can be assigned to users or
  1282. groups. A log of user edits to models made within the admin is also stored and
  1283. displayed.
  1284. Creating users
  1285. --------------
  1286. You should see a link to "Users" in the "Auth"
  1287. section of the main admin index page. The "Add user" admin page is different
  1288. than standard admin pages in that it requires you to choose a username and
  1289. password before allowing you to edit the rest of the user's fields.
  1290. Also note: if you want a user account to be able to create users using the
  1291. Django admin site, you'll need to give them permission to add users *and*
  1292. change users (i.e., the "Add user" and "Change user" permissions). If an
  1293. account has permission to add users but not to change them, that account won't
  1294. be able to add users. Why? Because if you have permission to add users, you
  1295. have the power to create superusers, which can then, in turn, change other
  1296. users. So Django requires add *and* change permissions as a slight security
  1297. measure.
  1298. Be thoughtful about how you allow users to manage permissions. If you give a
  1299. non-superuser the ability to edit users, this is ultimately the same as giving
  1300. them superuser status because they will be able to elevate permissions of
  1301. users including themselves!
  1302. Changing passwords
  1303. ------------------
  1304. User passwords are not displayed in the admin (nor stored in the database), but
  1305. the :doc:`password storage details </topics/auth/passwords>` are displayed.
  1306. Included in the display of this information is a link to
  1307. a password change form that allows admins to change user passwords.