default.txt 66 KB

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