default.txt 63 KB

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