default.txt 67 KB

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