2
0

default.txt 67 KB

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