default.txt 64 KB

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