default.txt 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879
  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. ...
  414. :func:`~django.contrib.auth.decorators.login_required` does the following:
  415. * If the user isn't logged in, redirect to
  416. :setting:`settings.LOGIN_URL <LOGIN_URL>`, passing the current absolute
  417. path in the query string. Example: ``/accounts/login/?next=/polls/3/``.
  418. * If the user is logged in, execute the view normally. The view code is
  419. free to assume the user is logged in.
  420. By default, the path that the user should be redirected to upon
  421. successful authentication is stored in a query string parameter called
  422. ``"next"``. If you would prefer to use a different name for this parameter,
  423. :func:`~django.contrib.auth.decorators.login_required` takes an
  424. optional ``redirect_field_name`` parameter::
  425. from django.contrib.auth.decorators import login_required
  426. @login_required(redirect_field_name="my_redirect_field")
  427. def my_view(request):
  428. ...
  429. Note that if you provide a value to ``redirect_field_name``, you will most
  430. likely need to customize your login template as well, since the template
  431. context variable which stores the redirect path will use the value of
  432. ``redirect_field_name`` as its key rather than ``"next"`` (the default).
  433. :func:`~django.contrib.auth.decorators.login_required` also takes an
  434. optional ``login_url`` parameter. Example::
  435. from django.contrib.auth.decorators import login_required
  436. @login_required(login_url="/accounts/login/")
  437. def my_view(request):
  438. ...
  439. Note that if you don't specify the ``login_url`` parameter, you'll need to
  440. ensure that the :setting:`settings.LOGIN_URL <LOGIN_URL>` and your login
  441. view are properly associated. For example, using the defaults, add the
  442. following lines to your URLconf::
  443. from django.contrib.auth import views as auth_views
  444. path("accounts/login/", auth_views.LoginView.as_view()),
  445. The :setting:`settings.LOGIN_URL <LOGIN_URL>` also accepts view function
  446. names and :ref:`named URL patterns <naming-url-patterns>`. This allows you
  447. to freely remap your login view within your URLconf without having to
  448. update the setting.
  449. .. note::
  450. The ``login_required`` decorator does NOT check the ``is_active`` flag on a
  451. user, but the default :setting:`AUTHENTICATION_BACKENDS` reject inactive
  452. users.
  453. .. seealso::
  454. If you are writing custom views for Django's admin (or need the same
  455. authorization check that the built-in views use), you may find the
  456. :func:`django.contrib.admin.views.decorators.staff_member_required`
  457. decorator a useful alternative to ``login_required()``.
  458. .. currentmodule:: django.contrib.auth.mixins
  459. The ``LoginRequiredMixin`` mixin
  460. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  461. When using :doc:`class-based views </topics/class-based-views/index>`, you can
  462. achieve the same behavior as with ``login_required`` by using the
  463. ``LoginRequiredMixin``. This mixin should be at the leftmost position in the
  464. inheritance list.
  465. .. class:: LoginRequiredMixin
  466. If a view is using this mixin, all requests by non-authenticated users will
  467. be redirected to the login page or shown an HTTP 403 Forbidden error,
  468. depending on the
  469. :attr:`~django.contrib.auth.mixins.AccessMixin.raise_exception` parameter.
  470. You can set any of the parameters of
  471. :class:`~django.contrib.auth.mixins.AccessMixin` to customize the handling
  472. of unauthorized users::
  473. from django.contrib.auth.mixins import LoginRequiredMixin
  474. class MyView(LoginRequiredMixin, View):
  475. login_url = "/login/"
  476. redirect_field_name = "redirect_to"
  477. .. note::
  478. Just as the ``login_required`` decorator, this mixin does NOT check the
  479. ``is_active`` flag on a user, but the default
  480. :setting:`AUTHENTICATION_BACKENDS` reject inactive users.
  481. .. currentmodule:: django.contrib.auth.decorators
  482. Limiting access to logged-in users that pass a test
  483. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  484. To limit access based on certain permissions or some other test, you'd do
  485. essentially the same thing as described in the previous section.
  486. You can run your test on :attr:`request.user <django.http.HttpRequest.user>` in
  487. the view directly. For example, this view checks to make sure the user has an
  488. email in the desired domain and if not, redirects to the login page::
  489. from django.shortcuts import redirect
  490. def my_view(request):
  491. if not request.user.email.endswith("@example.com"):
  492. return redirect("/login/?next=%s" % request.path)
  493. # ...
  494. .. function:: user_passes_test(test_func, login_url=None, redirect_field_name='next')
  495. As a shortcut, you can use the convenient ``user_passes_test`` decorator
  496. which performs a redirect when the callable returns ``False``::
  497. from django.contrib.auth.decorators import user_passes_test
  498. def email_check(user):
  499. return user.email.endswith("@example.com")
  500. @user_passes_test(email_check)
  501. def my_view(request):
  502. ...
  503. :func:`~django.contrib.auth.decorators.user_passes_test` takes a required
  504. argument: a callable that takes a
  505. :class:`~django.contrib.auth.models.User` object and returns ``True`` if
  506. the user is allowed to view the page. Note that
  507. :func:`~django.contrib.auth.decorators.user_passes_test` does not
  508. automatically check that the :class:`~django.contrib.auth.models.User` is
  509. not anonymous.
  510. :func:`~django.contrib.auth.decorators.user_passes_test` takes two
  511. optional arguments:
  512. ``login_url``
  513. Lets you specify the URL that users who don't pass the test will be
  514. redirected to. It may be a login page and defaults to
  515. :setting:`settings.LOGIN_URL <LOGIN_URL>` if you don't specify one.
  516. ``redirect_field_name``
  517. Same as for :func:`~django.contrib.auth.decorators.login_required`.
  518. Setting it to ``None`` removes it from the URL, which you may want to do
  519. if you are redirecting users that don't pass the test to a non-login
  520. page where there's no "next page".
  521. For example::
  522. @user_passes_test(email_check, login_url="/login/")
  523. def my_view(request):
  524. ...
  525. .. currentmodule:: django.contrib.auth.mixins
  526. .. class:: UserPassesTestMixin
  527. When using :doc:`class-based views </topics/class-based-views/index>`, you
  528. can use the ``UserPassesTestMixin`` to do this.
  529. .. method:: test_func()
  530. You have to override the ``test_func()`` method of the class to
  531. provide the test that is performed. Furthermore, you can set any of the
  532. parameters of :class:`~django.contrib.auth.mixins.AccessMixin` to
  533. customize the handling of unauthorized users::
  534. from django.contrib.auth.mixins import UserPassesTestMixin
  535. class MyView(UserPassesTestMixin, View):
  536. def test_func(self):
  537. return self.request.user.email.endswith("@example.com")
  538. .. method:: get_test_func()
  539. You can also override the ``get_test_func()`` method to have the mixin
  540. use a differently named function for its checks (instead of
  541. :meth:`test_func`).
  542. .. admonition:: Stacking ``UserPassesTestMixin``
  543. Due to the way ``UserPassesTestMixin`` is implemented, you cannot stack
  544. them in your inheritance list. The following does NOT work::
  545. class TestMixin1(UserPassesTestMixin):
  546. def test_func(self):
  547. return self.request.user.email.endswith("@example.com")
  548. class TestMixin2(UserPassesTestMixin):
  549. def test_func(self):
  550. return self.request.user.username.startswith("django")
  551. class MyView(TestMixin1, TestMixin2, View):
  552. ...
  553. If ``TestMixin1`` would call ``super()`` and take that result into
  554. account, ``TestMixin1`` wouldn't work standalone anymore.
  555. .. currentmodule:: django.contrib.auth.decorators
  556. The ``permission_required`` decorator
  557. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  558. .. function:: permission_required(perm, login_url=None, raise_exception=False)
  559. It's a relatively common task to check whether a user has a particular
  560. permission. For that reason, Django provides a shortcut for that case: the
  561. :func:`~django.contrib.auth.decorators.permission_required()` decorator.::
  562. from django.contrib.auth.decorators import permission_required
  563. @permission_required("polls.add_choice")
  564. def my_view(request):
  565. ...
  566. Just like the :meth:`~django.contrib.auth.models.User.has_perm` method,
  567. permission names take the form ``"<app label>.<permission codename>"``
  568. (i.e. ``polls.add_choice`` for a permission on a model in the ``polls``
  569. application).
  570. The decorator may also take an iterable of permissions, in which case the
  571. user must have all of the permissions in order to access the view.
  572. Note that :func:`~django.contrib.auth.decorators.permission_required()`
  573. also takes an optional ``login_url`` parameter::
  574. from django.contrib.auth.decorators import permission_required
  575. @permission_required("polls.add_choice", login_url="/loginpage/")
  576. def my_view(request):
  577. ...
  578. As in the :func:`~django.contrib.auth.decorators.login_required` decorator,
  579. ``login_url`` defaults to :setting:`settings.LOGIN_URL <LOGIN_URL>`.
  580. If the ``raise_exception`` parameter is given, the decorator will raise
  581. :exc:`~django.core.exceptions.PermissionDenied`, prompting :ref:`the 403
  582. (HTTP Forbidden) view<http_forbidden_view>` instead of redirecting to the
  583. login page.
  584. If you want to use ``raise_exception`` but also give your users a chance to
  585. login first, you can add the
  586. :func:`~django.contrib.auth.decorators.login_required` decorator::
  587. from django.contrib.auth.decorators import login_required, permission_required
  588. @login_required
  589. @permission_required("polls.add_choice", raise_exception=True)
  590. def my_view(request):
  591. ...
  592. This also avoids a redirect loop when :class:`.LoginView`'s
  593. ``redirect_authenticated_user=True`` and the logged-in user doesn't have
  594. all of the required permissions.
  595. .. currentmodule:: django.contrib.auth.mixins
  596. The ``PermissionRequiredMixin`` mixin
  597. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  598. To apply permission checks to :doc:`class-based views
  599. </ref/class-based-views/index>`, you can use the ``PermissionRequiredMixin``:
  600. .. class:: PermissionRequiredMixin
  601. This mixin, just like the ``permission_required``
  602. decorator, checks whether the user accessing a view has all given
  603. permissions. You should specify the permission (or an iterable of
  604. permissions) using the ``permission_required`` parameter::
  605. from django.contrib.auth.mixins import PermissionRequiredMixin
  606. class MyView(PermissionRequiredMixin, View):
  607. permission_required = "polls.add_choice"
  608. # Or multiple of permissions:
  609. permission_required = ["polls.view_choice", "polls.change_choice"]
  610. You can set any of the parameters of
  611. :class:`~django.contrib.auth.mixins.AccessMixin` to customize the handling
  612. of unauthorized users.
  613. You may also override these methods:
  614. .. method:: get_permission_required()
  615. Returns an iterable of permission names used by the mixin. Defaults to
  616. the ``permission_required`` attribute, converted to a tuple if
  617. necessary.
  618. .. method:: has_permission()
  619. Returns a boolean denoting whether the current user has permission to
  620. execute the decorated view. By default, this returns the result of
  621. calling :meth:`~django.contrib.auth.models.User.has_perms()` with the
  622. list of permissions returned by :meth:`get_permission_required()`.
  623. Redirecting unauthorized requests in class-based views
  624. ------------------------------------------------------
  625. To ease the handling of access restrictions in :doc:`class-based views
  626. </ref/class-based-views/index>`, the ``AccessMixin`` can be used to configure
  627. the behavior of a view when access is denied. Authenticated users are denied
  628. access with an HTTP 403 Forbidden response. Anonymous users are redirected to
  629. the login page or shown an HTTP 403 Forbidden response, depending on the
  630. :attr:`~django.contrib.auth.mixins.AccessMixin.raise_exception` attribute.
  631. .. class:: AccessMixin
  632. .. attribute:: login_url
  633. Default return value for :meth:`get_login_url`. Defaults to ``None``
  634. in which case :meth:`get_login_url` falls back to
  635. :setting:`settings.LOGIN_URL <LOGIN_URL>`.
  636. .. attribute:: permission_denied_message
  637. Default return value for :meth:`get_permission_denied_message`.
  638. Defaults to an empty string.
  639. .. attribute:: redirect_field_name
  640. Default return value for :meth:`get_redirect_field_name`. Defaults to
  641. ``"next"``.
  642. .. attribute:: raise_exception
  643. If this attribute is set to ``True``, a
  644. :class:`~django.core.exceptions.PermissionDenied` exception is raised
  645. when the conditions are not met. When ``False`` (the default),
  646. anonymous users are redirected to the login page.
  647. .. method:: get_login_url()
  648. Returns the URL that users who don't pass the test will be redirected
  649. to. Returns :attr:`login_url` if set, or :setting:`settings.LOGIN_URL
  650. <LOGIN_URL>` otherwise.
  651. .. method:: get_permission_denied_message()
  652. When :attr:`raise_exception` is ``True``, this method can be used to
  653. control the error message passed to the error handler for display to
  654. the user. Returns the :attr:`permission_denied_message` attribute by
  655. default.
  656. .. method:: get_redirect_field_name()
  657. Returns the name of the query parameter that will contain the URL the
  658. user should be redirected to after a successful login. If you set this
  659. to ``None``, a query parameter won't be added. Returns the
  660. :attr:`redirect_field_name` attribute by default.
  661. .. method:: handle_no_permission()
  662. Depending on the value of ``raise_exception``, the method either raises
  663. a :exc:`~django.core.exceptions.PermissionDenied` exception or
  664. redirects the user to the ``login_url``, optionally including the
  665. ``redirect_field_name`` if it is set.
  666. .. currentmodule:: django.contrib.auth
  667. .. _session-invalidation-on-password-change:
  668. Session invalidation on password change
  669. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  670. If your :setting:`AUTH_USER_MODEL` inherits from
  671. :class:`~django.contrib.auth.models.AbstractBaseUser` or implements its own
  672. :meth:`~django.contrib.auth.models.AbstractBaseUser.get_session_auth_hash()`
  673. method, authenticated sessions will include the hash returned by this function.
  674. In the :class:`~django.contrib.auth.models.AbstractBaseUser` case, this is an
  675. HMAC of the password field. Django verifies that the hash in the session for
  676. each request matches the one that's computed during the request. This allows a
  677. user to log out all of their sessions by changing their password.
  678. The default password change views included with Django,
  679. :class:`~django.contrib.auth.views.PasswordChangeView` and the
  680. ``user_change_password`` view in the :mod:`django.contrib.auth` admin, update
  681. the session with the new password hash so that a user changing their own
  682. password won't log themselves out. If you have a custom password change view
  683. and wish to have similar behavior, use the :func:`update_session_auth_hash`
  684. function.
  685. .. function:: update_session_auth_hash(request, user)
  686. .. function:: aupdate_session_auth_hash(request, user)
  687. *Asynchronous version*: ``aupdate_session_auth_hash()``
  688. This function takes the current request and the updated user object from
  689. which the new session hash will be derived and updates the session hash
  690. appropriately. It also rotates the session key so that a stolen session
  691. cookie will be invalidated.
  692. Example usage::
  693. from django.contrib.auth import update_session_auth_hash
  694. def password_change(request):
  695. if request.method == "POST":
  696. form = PasswordChangeForm(user=request.user, data=request.POST)
  697. if form.is_valid():
  698. form.save()
  699. update_session_auth_hash(request, form.user)
  700. else:
  701. ...
  702. .. versionchanged:: 5.0
  703. ``aupdate_session_auth_hash()`` function was added.
  704. .. note::
  705. Since
  706. :meth:`~django.contrib.auth.models.AbstractBaseUser.get_session_auth_hash()`
  707. is based on :setting:`SECRET_KEY`, secret key values must be
  708. rotated to avoid invalidating existing sessions when updating your site to
  709. use a new secret. See :setting:`SECRET_KEY_FALLBACKS` for details.
  710. .. _built-in-auth-views:
  711. Authentication Views
  712. --------------------
  713. .. module:: django.contrib.auth.views
  714. Django provides several views that you can use for handling login, logout, and
  715. password management. These make use of the :ref:`stock auth forms
  716. <built-in-auth-forms>` but you can pass in your own forms as well.
  717. Django provides no default template for the authentication views. You should
  718. create your own templates for the views you want to use. The template context
  719. is documented in each view, see :ref:`all-authentication-views`.
  720. .. _using-the-views:
  721. Using the views
  722. ~~~~~~~~~~~~~~~
  723. There are different methods to implement these views in your project. The
  724. easiest way is to include the provided URLconf in ``django.contrib.auth.urls``
  725. in your own URLconf, for example::
  726. urlpatterns = [
  727. path("accounts/", include("django.contrib.auth.urls")),
  728. ]
  729. This will include the following URL patterns:
  730. .. code-block:: text
  731. accounts/login/ [name='login']
  732. accounts/logout/ [name='logout']
  733. accounts/password_change/ [name='password_change']
  734. accounts/password_change/done/ [name='password_change_done']
  735. accounts/password_reset/ [name='password_reset']
  736. accounts/password_reset/done/ [name='password_reset_done']
  737. accounts/reset/<uidb64>/<token>/ [name='password_reset_confirm']
  738. accounts/reset/done/ [name='password_reset_complete']
  739. The views provide a URL name for easier reference. See :doc:`the URL
  740. documentation </topics/http/urls>` for details on using named URL patterns.
  741. If you want more control over your URLs, you can reference a specific view in
  742. your URLconf::
  743. from django.contrib.auth import views as auth_views
  744. urlpatterns = [
  745. path("change-password/", auth_views.PasswordChangeView.as_view()),
  746. ]
  747. The views have optional arguments you can use to alter the behavior of the
  748. view. For example, if you want to change the template name a view uses, you can
  749. provide the ``template_name`` argument. A way to do this is to provide keyword
  750. arguments in the URLconf, these will be passed on to the view. For example::
  751. urlpatterns = [
  752. path(
  753. "change-password/",
  754. auth_views.PasswordChangeView.as_view(template_name="change-password.html"),
  755. ),
  756. ]
  757. All views are :doc:`class-based </topics/class-based-views/index>`, which allows
  758. you to easily customize them by subclassing.
  759. .. _all-authentication-views:
  760. All authentication views
  761. ~~~~~~~~~~~~~~~~~~~~~~~~
  762. This is a list with all the views ``django.contrib.auth`` provides. For
  763. implementation details see :ref:`using-the-views`.
  764. .. class:: LoginView
  765. **URL name:** ``login``
  766. See :doc:`the URL documentation </topics/http/urls>` for details on using
  767. named URL patterns.
  768. **Methods and Attributes**
  769. .. attribute:: template_name
  770. The name of a template to display for the view used to log the user in.
  771. Defaults to :file:`registration/login.html`.
  772. .. attribute:: next_page
  773. The URL to redirect to after login. Defaults to
  774. :setting:`LOGIN_REDIRECT_URL`.
  775. .. attribute:: redirect_field_name
  776. The name of a ``GET`` field containing the URL to redirect to after
  777. login. Defaults to ``next``. Overrides the
  778. :meth:`get_default_redirect_url` URL if the given ``GET`` parameter is
  779. passed.
  780. .. attribute:: authentication_form
  781. A callable (typically a form class) to use for authentication. Defaults
  782. to :class:`~django.contrib.auth.forms.AuthenticationForm`.
  783. .. attribute:: extra_context
  784. A dictionary of context data that will be added to the default context
  785. data passed to the template.
  786. .. attribute:: redirect_authenticated_user
  787. A boolean that controls whether or not authenticated users accessing
  788. the login page will be redirected as if they had just successfully
  789. logged in. Defaults to ``False``.
  790. .. warning::
  791. If you enable ``redirect_authenticated_user``, other websites will
  792. be able to determine if their visitors are authenticated on your
  793. site by requesting redirect URLs to image files on your website. To
  794. avoid this "`social media fingerprinting
  795. <https://robinlinus.github.io/socialmedia-leak/>`_" information
  796. leakage, host all images and your favicon on a separate domain.
  797. Enabling ``redirect_authenticated_user`` can also result in a
  798. redirect loop when using the :func:`.permission_required` decorator
  799. unless the ``raise_exception`` parameter is used.
  800. .. attribute:: success_url_allowed_hosts
  801. A :class:`set` of hosts, in addition to :meth:`request.get_host()
  802. <django.http.HttpRequest.get_host>`, that are safe for redirecting
  803. after login. Defaults to an empty :class:`set`.
  804. .. method:: get_default_redirect_url()
  805. Returns the URL to redirect to after login. The default implementation
  806. resolves and returns :attr:`next_page` if set, or
  807. :setting:`LOGIN_REDIRECT_URL` otherwise.
  808. Here's what ``LoginView`` does:
  809. * If called via ``GET``, it displays a login form that POSTs to the
  810. same URL. More on this in a bit.
  811. * If called via ``POST`` with user submitted credentials, it tries to log
  812. the user in. If login is successful, the view redirects to the URL
  813. specified in ``next``. If ``next`` isn't provided, it redirects to
  814. :setting:`settings.LOGIN_REDIRECT_URL <LOGIN_REDIRECT_URL>` (which
  815. defaults to ``/accounts/profile/``). If login isn't successful, it
  816. redisplays the login form.
  817. It's your responsibility to provide the html for the login template
  818. , called ``registration/login.html`` by default. This template gets passed
  819. four template context variables:
  820. * ``form``: A :class:`~django.forms.Form` object representing the
  821. :class:`~django.contrib.auth.forms.AuthenticationForm`.
  822. * ``next``: The URL to redirect to after successful login. This may
  823. contain a query string, too.
  824. * ``site``: The current :class:`~django.contrib.sites.models.Site`,
  825. according to the :setting:`SITE_ID` setting. If you don't have the
  826. site framework installed, this will be set to an instance of
  827. :class:`~django.contrib.sites.requests.RequestSite`, which derives the
  828. site name and domain from the current
  829. :class:`~django.http.HttpRequest`.
  830. * ``site_name``: An alias for ``site.name``. If you don't have the site
  831. framework installed, this will be set to the value of
  832. :attr:`request.META['SERVER_NAME'] <django.http.HttpRequest.META>`.
  833. For more on sites, see :doc:`/ref/contrib/sites`.
  834. If you'd prefer not to call the template :file:`registration/login.html`,
  835. you can pass the ``template_name`` parameter via the extra arguments to
  836. the ``as_view`` method in your URLconf. For example, this URLconf line would
  837. use :file:`myapp/login.html` instead::
  838. path("accounts/login/", auth_views.LoginView.as_view(template_name="myapp/login.html")),
  839. You can also specify the name of the ``GET`` field which contains the URL
  840. to redirect to after login using ``redirect_field_name``. By default, the
  841. field is called ``next``.
  842. Here's a sample :file:`registration/login.html` template you can use as a
  843. starting point. It assumes you have a :file:`base.html` template that
  844. defines a ``content`` block:
  845. .. code-block:: html+django
  846. {% extends "base.html" %}
  847. {% block content %}
  848. {% if form.errors %}
  849. <p>Your username and password didn't match. Please try again.</p>
  850. {% endif %}
  851. {% if next %}
  852. {% if user.is_authenticated %}
  853. <p>Your account doesn't have access to this page. To proceed,
  854. please login with an account that has access.</p>
  855. {% else %}
  856. <p>Please login to see this page.</p>
  857. {% endif %}
  858. {% endif %}
  859. <form method="post" action="{% url 'login' %}">
  860. {% csrf_token %}
  861. <table>
  862. <tr>
  863. <td>{{ form.username.label_tag }}</td>
  864. <td>{{ form.username }}</td>
  865. </tr>
  866. <tr>
  867. <td>{{ form.password.label_tag }}</td>
  868. <td>{{ form.password }}</td>
  869. </tr>
  870. </table>
  871. <input type="submit" value="login">
  872. <input type="hidden" name="next" value="{{ next }}">
  873. </form>
  874. {# Assumes you set up the password_reset view in your URLconf #}
  875. <p><a href="{% url 'password_reset' %}">Lost password?</a></p>
  876. {% endblock %}
  877. If you have customized authentication (see :doc:`Customizing Authentication
  878. </topics/auth/customizing>`) you can use a custom authentication form by
  879. setting the ``authentication_form`` attribute. This form must accept a
  880. ``request`` keyword argument in its ``__init__()`` method and provide a
  881. ``get_user()`` method which returns the authenticated user object (this
  882. method is only ever called after successful form validation).
  883. .. class:: LogoutView
  884. Logs a user out on ``POST`` requests.
  885. **URL name:** ``logout``
  886. **Attributes:**
  887. .. attribute:: next_page
  888. The URL to redirect to after logout. Defaults to
  889. :setting:`LOGOUT_REDIRECT_URL`.
  890. .. attribute:: template_name
  891. The full name of a template to display after logging the user out.
  892. Defaults to :file:`registration/logged_out.html`.
  893. .. attribute:: redirect_field_name
  894. The name of a ``GET`` field containing the URL to redirect to after log
  895. out. Defaults to ``'next'``. Overrides the
  896. :attr:`next_page` URL if the given ``GET`` parameter is
  897. passed.
  898. .. attribute:: extra_context
  899. A dictionary of context data that will be added to the default context
  900. data passed to the template.
  901. .. attribute:: success_url_allowed_hosts
  902. A :class:`set` of hosts, in addition to :meth:`request.get_host()
  903. <django.http.HttpRequest.get_host>`, that are safe for redirecting
  904. after logout. Defaults to an empty :class:`set`.
  905. **Template context:**
  906. * ``title``: The string "Logged out", localized.
  907. * ``site``: The current :class:`~django.contrib.sites.models.Site`,
  908. according to the :setting:`SITE_ID` setting. If you don't have the
  909. site framework installed, this will be set to an instance of
  910. :class:`~django.contrib.sites.requests.RequestSite`, which derives the
  911. site name and domain from the current
  912. :class:`~django.http.HttpRequest`.
  913. * ``site_name``: An alias for ``site.name``. If you don't have the site
  914. framework installed, this will be set to the value of
  915. :attr:`request.META['SERVER_NAME'] <django.http.HttpRequest.META>`.
  916. For more on sites, see :doc:`/ref/contrib/sites`.
  917. .. function:: logout_then_login(request, login_url=None)
  918. Logs a user out on ``POST`` requests, then redirects to the login page.
  919. **URL name:** No default URL provided
  920. **Optional arguments:**
  921. * ``login_url``: The URL of the login page to redirect to.
  922. Defaults to :setting:`settings.LOGIN_URL <LOGIN_URL>` if not supplied.
  923. .. class:: PasswordChangeView
  924. **URL name:** ``password_change``
  925. Allows a user to change their password.
  926. **Attributes:**
  927. .. attribute:: template_name
  928. The full name of a template to use for displaying the password change
  929. form. Defaults to :file:`registration/password_change_form.html` if not
  930. supplied.
  931. .. attribute:: success_url
  932. The URL to redirect to after a successful password change. Defaults to
  933. ``'password_change_done'``.
  934. .. attribute:: form_class
  935. A custom "change password" form which must accept a ``user`` keyword
  936. argument. The form is responsible for actually changing the user's
  937. password. Defaults to
  938. :class:`~django.contrib.auth.forms.PasswordChangeForm`.
  939. .. attribute:: extra_context
  940. A dictionary of context data that will be added to the default context
  941. data passed to the template.
  942. **Template context:**
  943. * ``form``: The password change form (see ``form_class`` above).
  944. .. class:: PasswordChangeDoneView
  945. **URL name:** ``password_change_done``
  946. The page shown after a user has changed their password.
  947. **Attributes:**
  948. .. attribute:: template_name
  949. The full name of a template to use. Defaults to
  950. :file:`registration/password_change_done.html` if not supplied.
  951. .. attribute:: extra_context
  952. A dictionary of context data that will be added to the default context
  953. data passed to the template.
  954. .. class:: PasswordResetView
  955. **URL name:** ``password_reset``
  956. Allows a user to reset their password by generating a one-time use link
  957. that can be used to reset the password, and sending that link to the
  958. user's registered email address.
  959. This view will send an email if the following conditions are met:
  960. * The email address provided exists in the system.
  961. * The requested user is active (``User.is_active`` is ``True``).
  962. * The requested user has a usable password. Users flagged with an unusable
  963. password (see
  964. :meth:`~django.contrib.auth.models.User.set_unusable_password`) aren't
  965. allowed to request a password reset to prevent misuse when using an
  966. external authentication source like LDAP.
  967. If any of these conditions are *not* met, no email will be sent, but the
  968. user won't receive any error message either. This prevents information
  969. leaking to potential attackers. If you want to provide an error message in
  970. this case, you can subclass
  971. :class:`~django.contrib.auth.forms.PasswordResetForm` and use the
  972. ``form_class`` attribute.
  973. .. note::
  974. Be aware that sending an email costs extra time, hence you may be
  975. vulnerable to an email address enumeration timing attack due to a
  976. difference between the duration of a reset request for an existing
  977. email address and the duration of a reset request for a nonexistent
  978. email address. To reduce the overhead, you can use a 3rd party package
  979. that allows to send emails asynchronously, e.g. :pypi:`django-mailer`.
  980. **Attributes:**
  981. .. attribute:: template_name
  982. The full name of a template to use for displaying the password reset
  983. form. Defaults to :file:`registration/password_reset_form.html` if not
  984. supplied.
  985. .. attribute:: form_class
  986. Form that will be used to get the email of the user to reset the
  987. password for. Defaults to
  988. :class:`~django.contrib.auth.forms.PasswordResetForm`.
  989. .. attribute:: email_template_name
  990. The full name of a template to use for generating the email with the
  991. reset password link. Defaults to
  992. :file:`registration/password_reset_email.html` if not supplied.
  993. .. attribute:: subject_template_name
  994. The full name of a template to use for the subject of the email with
  995. the reset password link. Defaults to
  996. :file:`registration/password_reset_subject.txt` if not supplied.
  997. .. attribute:: token_generator
  998. Instance of the class to check the one time link. This will default to
  999. ``default_token_generator``, it's an instance of
  1000. ``django.contrib.auth.tokens.PasswordResetTokenGenerator``.
  1001. .. attribute:: success_url
  1002. The URL to redirect to after a successful password reset request.
  1003. Defaults to ``'password_reset_done'``.
  1004. .. attribute:: from_email
  1005. A valid email address. By default Django uses the
  1006. :setting:`DEFAULT_FROM_EMAIL`.
  1007. .. attribute:: extra_context
  1008. A dictionary of context data that will be added to the default context
  1009. data passed to the template.
  1010. .. attribute:: html_email_template_name
  1011. The full name of a template to use for generating a
  1012. :mimetype:`text/html` multipart email with the password reset link. By
  1013. default, HTML email is not sent.
  1014. .. attribute:: extra_email_context
  1015. A dictionary of context data that will be available in the email
  1016. template. It can be used to override default template context values
  1017. listed below e.g. ``domain``.
  1018. **Template context:**
  1019. * ``form``: The form (see ``form_class`` above) for resetting the user's
  1020. password.
  1021. **Email template context:**
  1022. * ``email``: An alias for ``user.email``
  1023. * ``user``: The current :class:`~django.contrib.auth.models.User`,
  1024. according to the ``email`` form field. Only active users are able to
  1025. reset their passwords (``User.is_active is True``).
  1026. * ``site_name``: An alias for ``site.name``. If you don't have the site
  1027. framework installed, this will be set to the value of
  1028. :attr:`request.META['SERVER_NAME'] <django.http.HttpRequest.META>`.
  1029. For more on sites, see :doc:`/ref/contrib/sites`.
  1030. * ``domain``: An alias for ``site.domain``. If you don't have the site
  1031. framework installed, this will be set to the value of
  1032. ``request.get_host()``.
  1033. * ``protocol``: http or https
  1034. * ``uid``: The user's primary key encoded in base 64.
  1035. * ``token``: Token to check that the reset link is valid.
  1036. Sample ``registration/password_reset_email.html`` (email body template):
  1037. .. code-block:: html+django
  1038. Someone asked for password reset for email {{ email }}. Follow the link below:
  1039. {{ protocol}}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %}
  1040. The same template context is used for subject template. Subject must be
  1041. single line plain text string.
  1042. .. class:: PasswordResetDoneView
  1043. **URL name:** ``password_reset_done``
  1044. The page shown after a user has been emailed a link to reset their
  1045. password. This view is called by default if the :class:`PasswordResetView`
  1046. doesn't have an explicit ``success_url`` URL set.
  1047. .. note::
  1048. If the email address provided does not exist in the system, the user is
  1049. inactive, or has an unusable password, the user will still be
  1050. redirected to this view but no email will be sent.
  1051. **Attributes:**
  1052. .. attribute:: template_name
  1053. The full name of a template to use. Defaults to
  1054. :file:`registration/password_reset_done.html` if not supplied.
  1055. .. attribute:: extra_context
  1056. A dictionary of context data that will be added to the default context
  1057. data passed to the template.
  1058. .. class:: PasswordResetConfirmView
  1059. **URL name:** ``password_reset_confirm``
  1060. Presents a form for entering a new password.
  1061. **Keyword arguments from the URL:**
  1062. * ``uidb64``: The user's id encoded in base 64.
  1063. * ``token``: Token to check that the password is valid.
  1064. **Attributes:**
  1065. .. attribute:: template_name
  1066. The full name of a template to display the confirm password view.
  1067. Default value is :file:`registration/password_reset_confirm.html`.
  1068. .. attribute:: token_generator
  1069. Instance of the class to check the password. This will default to
  1070. ``default_token_generator``, it's an instance of
  1071. ``django.contrib.auth.tokens.PasswordResetTokenGenerator``.
  1072. .. attribute:: post_reset_login
  1073. A boolean indicating if the user should be automatically authenticated
  1074. after a successful password reset. Defaults to ``False``.
  1075. .. attribute:: post_reset_login_backend
  1076. A dotted path to the authentication backend to use when authenticating
  1077. a user if ``post_reset_login`` is ``True``. Required only if you have
  1078. multiple :setting:`AUTHENTICATION_BACKENDS` configured. Defaults to
  1079. ``None``.
  1080. .. attribute:: form_class
  1081. Form that will be used to set the password. Defaults to
  1082. :class:`~django.contrib.auth.forms.SetPasswordForm`.
  1083. .. attribute:: success_url
  1084. URL to redirect after the password reset done. Defaults to
  1085. ``'password_reset_complete'``.
  1086. .. attribute:: extra_context
  1087. A dictionary of context data that will be added to the default context
  1088. data passed to the template.
  1089. .. attribute:: reset_url_token
  1090. Token parameter displayed as a component of password reset URLs.
  1091. Defaults to ``'set-password'``.
  1092. **Template context:**
  1093. * ``form``: The form (see ``form_class`` above) for setting the new user's
  1094. password.
  1095. * ``validlink``: Boolean, True if the link (combination of ``uidb64`` and
  1096. ``token``) is valid or unused yet.
  1097. .. class:: PasswordResetCompleteView
  1098. **URL name:** ``password_reset_complete``
  1099. Presents a view which informs the user that the password has been
  1100. successfully changed.
  1101. **Attributes:**
  1102. .. attribute:: template_name
  1103. The full name of a template to display the view. Defaults to
  1104. :file:`registration/password_reset_complete.html`.
  1105. .. attribute:: extra_context
  1106. A dictionary of context data that will be added to the default context
  1107. data passed to the template.
  1108. Helper functions
  1109. ----------------
  1110. .. currentmodule:: django.contrib.auth.views
  1111. .. function:: redirect_to_login(next, login_url=None, redirect_field_name='next')
  1112. Redirects to the login page, and then back to another URL after a
  1113. successful login.
  1114. **Required arguments:**
  1115. * ``next``: The URL to redirect to after a successful login.
  1116. **Optional arguments:**
  1117. * ``login_url``: The URL of the login page to redirect to.
  1118. Defaults to :setting:`settings.LOGIN_URL <LOGIN_URL>` if not supplied.
  1119. * ``redirect_field_name``: The name of a ``GET`` field containing the
  1120. URL to redirect to after log out. Overrides ``next`` if the given
  1121. ``GET`` parameter is passed.
  1122. .. _built-in-auth-forms:
  1123. Built-in forms
  1124. --------------
  1125. .. module:: django.contrib.auth.forms
  1126. If you don't want to use the built-in views, but want the convenience of not
  1127. having to write forms for this functionality, the authentication system
  1128. provides several built-in forms located in :mod:`django.contrib.auth.forms`:
  1129. .. note::
  1130. The built-in authentication forms make certain assumptions about the user
  1131. model that they are working with. If you're using a :ref:`custom user model
  1132. <auth-custom-user>`, it may be necessary to define your own forms for the
  1133. authentication system. For more information, refer to the documentation
  1134. about :ref:`using the built-in authentication forms with custom user models
  1135. <custom-users-and-the-built-in-auth-forms>`.
  1136. .. class:: AdminPasswordChangeForm
  1137. A form used in the admin interface to change a user's password.
  1138. Takes the ``user`` as the first positional argument.
  1139. .. class:: AuthenticationForm
  1140. A form for logging a user in.
  1141. Takes ``request`` as its first positional argument, which is stored on the
  1142. form instance for use by sub-classes.
  1143. .. method:: confirm_login_allowed(user)
  1144. By default, ``AuthenticationForm`` rejects users whose ``is_active``
  1145. flag is set to ``False``. You may override this behavior with a custom
  1146. policy to determine which users can log in. Do this with a custom form
  1147. that subclasses ``AuthenticationForm`` and overrides the
  1148. ``confirm_login_allowed()`` method. This method should raise a
  1149. :exc:`~django.core.exceptions.ValidationError` if the given user may
  1150. not log in.
  1151. For example, to allow all users to log in regardless of "active"
  1152. status::
  1153. from django.contrib.auth.forms import AuthenticationForm
  1154. class AuthenticationFormWithInactiveUsersOkay(AuthenticationForm):
  1155. def confirm_login_allowed(self, user):
  1156. pass
  1157. (In this case, you'll also need to use an authentication backend that
  1158. allows inactive users, such as
  1159. :class:`~django.contrib.auth.backends.AllowAllUsersModelBackend`.)
  1160. Or to allow only some active users to log in::
  1161. class PickyAuthenticationForm(AuthenticationForm):
  1162. def confirm_login_allowed(self, user):
  1163. if not user.is_active:
  1164. raise ValidationError(
  1165. _("This account is inactive."),
  1166. code="inactive",
  1167. )
  1168. if user.username.startswith("b"):
  1169. raise ValidationError(
  1170. _("Sorry, accounts starting with 'b' aren't welcome here."),
  1171. code="no_b_users",
  1172. )
  1173. .. class:: PasswordChangeForm
  1174. A form for allowing a user to change their password.
  1175. .. class:: PasswordResetForm
  1176. A form for generating and emailing a one-time use link to reset a
  1177. user's password.
  1178. .. method:: send_mail(subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None)
  1179. Uses the arguments to send an ``EmailMultiAlternatives``.
  1180. Can be overridden to customize how the email is sent to the user.
  1181. :param subject_template_name: the template for the subject.
  1182. :param email_template_name: the template for the email body.
  1183. :param context: context passed to the ``subject_template``,
  1184. ``email_template``, and ``html_email_template`` (if it is not
  1185. ``None``).
  1186. :param from_email: the sender's email.
  1187. :param to_email: the email of the requester.
  1188. :param html_email_template_name: the template for the HTML body;
  1189. defaults to ``None``, in which case a plain text email is sent.
  1190. By default, ``save()`` populates the ``context`` with the
  1191. same variables that
  1192. :class:`~django.contrib.auth.views.PasswordResetView` passes to its
  1193. email context.
  1194. .. class:: SetPasswordForm
  1195. A form that lets a user change their password without entering the old
  1196. password.
  1197. .. class:: UserChangeForm
  1198. A form used in the admin interface to change a user's information and
  1199. permissions.
  1200. .. class:: BaseUserCreationForm
  1201. .. versionadded:: 4.2
  1202. A :class:`~django.forms.ModelForm` for creating a new user. This is the
  1203. recommended base class if you need to customize the user creation form.
  1204. It has three fields: ``username`` (from the user model), ``password1``,
  1205. and ``password2``. It verifies that ``password1`` and ``password2`` match,
  1206. validates the password using
  1207. :func:`~django.contrib.auth.password_validation.validate_password`, and
  1208. sets the user's password using
  1209. :meth:`~django.contrib.auth.models.User.set_password()`.
  1210. .. class:: UserCreationForm
  1211. Inherits from :class:`BaseUserCreationForm`. To help prevent confusion with
  1212. similar usernames, the form doesn't allow usernames that differ only in
  1213. case.
  1214. .. versionchanged:: 4.2
  1215. In older versions, :class:`UserCreationForm` didn't save many-to-many
  1216. form fields for a custom user model.
  1217. In older versions, usernames that differ only in case are allowed.
  1218. .. currentmodule:: django.contrib.auth
  1219. Authentication data in templates
  1220. --------------------------------
  1221. The currently logged-in user and their permissions are made available in the
  1222. :doc:`template context </ref/templates/api>` when you use
  1223. :class:`~django.template.RequestContext`.
  1224. .. admonition:: Technicality
  1225. Technically, these variables are only made available in the template
  1226. context if you use :class:`~django.template.RequestContext` and the
  1227. ``'django.contrib.auth.context_processors.auth'`` context processor is
  1228. enabled. It is in the default generated settings file. For more, see the
  1229. :ref:`RequestContext docs <subclassing-context-requestcontext>`.
  1230. Users
  1231. ~~~~~
  1232. When rendering a template :class:`~django.template.RequestContext`, the
  1233. currently logged-in user, either a :class:`~django.contrib.auth.models.User`
  1234. instance or an :class:`~django.contrib.auth.models.AnonymousUser` instance, is
  1235. stored in the template variable ``{{ user }}``:
  1236. .. code-block:: html+django
  1237. {% if user.is_authenticated %}
  1238. <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
  1239. {% else %}
  1240. <p>Welcome, new user. Please log in.</p>
  1241. {% endif %}
  1242. This template context variable is not available if a ``RequestContext`` is not
  1243. being used.
  1244. Permissions
  1245. ~~~~~~~~~~~
  1246. The currently logged-in user's permissions are stored in the template variable
  1247. ``{{ perms }}``. This is an instance of
  1248. ``django.contrib.auth.context_processors.PermWrapper``, which is a
  1249. template-friendly proxy of permissions.
  1250. Evaluating a single-attribute lookup of ``{{ perms }}`` as a boolean is a proxy
  1251. to :meth:`User.has_module_perms()
  1252. <django.contrib.auth.models.User.has_module_perms>`. For example, to check if
  1253. the logged-in user has any permissions in the ``foo`` app:
  1254. .. code-block:: html+django
  1255. {% if perms.foo %}
  1256. Evaluating a two-level-attribute lookup as a boolean is a proxy to
  1257. :meth:`User.has_perm() <django.contrib.auth.models.User.has_perm>`. For example,
  1258. to check if the logged-in user has the permission ``foo.add_vote``:
  1259. .. code-block:: html+django
  1260. {% if perms.foo.add_vote %}
  1261. Here's a more complete example of checking permissions in a template:
  1262. .. code-block:: html+django
  1263. {% if perms.foo %}
  1264. <p>You have permission to do something in the foo app.</p>
  1265. {% if perms.foo.add_vote %}
  1266. <p>You can vote!</p>
  1267. {% endif %}
  1268. {% if perms.foo.add_driving %}
  1269. <p>You can drive!</p>
  1270. {% endif %}
  1271. {% else %}
  1272. <p>You don't have permission to do anything in the foo app.</p>
  1273. {% endif %}
  1274. It is possible to also look permissions up by ``{% if in %}`` statements.
  1275. For example:
  1276. .. code-block:: html+django
  1277. {% if 'foo' in perms %}
  1278. {% if 'foo.add_vote' in perms %}
  1279. <p>In lookup works, too.</p>
  1280. {% endif %}
  1281. {% endif %}
  1282. .. _auth-admin:
  1283. Managing users in the admin
  1284. ===========================
  1285. When you have both ``django.contrib.admin`` and ``django.contrib.auth``
  1286. installed, the admin provides a convenient way to view and manage users,
  1287. groups, and permissions. Users can be created and deleted like any Django
  1288. model. Groups can be created, and permissions can be assigned to users or
  1289. groups. A log of user edits to models made within the admin is also stored and
  1290. displayed.
  1291. Creating users
  1292. --------------
  1293. You should see a link to "Users" in the "Auth"
  1294. section of the main admin index page. The "Add user" admin page is different
  1295. than standard admin pages in that it requires you to choose a username and
  1296. password before allowing you to edit the rest of the user's fields.
  1297. Also note: if you want a user account to be able to create users using the
  1298. Django admin site, you'll need to give them permission to add users *and*
  1299. change users (i.e., the "Add user" and "Change user" permissions). If an
  1300. account has permission to add users but not to change them, that account won't
  1301. be able to add users. Why? Because if you have permission to add users, you
  1302. have the power to create superusers, which can then, in turn, change other
  1303. users. So Django requires add *and* change permissions as a slight security
  1304. measure.
  1305. Be thoughtful about how you allow users to manage permissions. If you give a
  1306. non-superuser the ability to edit users, this is ultimately the same as giving
  1307. them superuser status because they will be able to elevate permissions of
  1308. users including themselves!
  1309. Changing passwords
  1310. ------------------
  1311. User passwords are not displayed in the admin (nor stored in the database), but
  1312. the :doc:`password storage details </topics/auth/passwords>` are displayed.
  1313. Included in the display of this information is a link to
  1314. a password change form that allows admins to change user passwords.