default.txt 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360
  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. .. versionadded:: 1.7
  82. Changing a user's password will log out all their sessions if the
  83. :class:`~django.contrib.auth.middleware.SessionAuthenticationMiddleware` is
  84. enabled. See :ref:`session-invalidation-on-password-change` for details.
  85. Authenticating Users
  86. --------------------
  87. .. function:: authenticate(\**credentials)
  88. To authenticate a given username and password, use
  89. :func:`~django.contrib.auth.authenticate()`. It takes credentials in the
  90. form of keyword arguments, for the default configuration this is
  91. ``username`` and ``password``, and it returns
  92. a :class:`~django.contrib.auth.models.User` object if the password is valid
  93. for the given username. If the password is invalid,
  94. :func:`~django.contrib.auth.authenticate()` returns ``None``. Example::
  95. from django.contrib.auth import authenticate
  96. user = authenticate(username='john', password='secret')
  97. if user is not None:
  98. # the password verified for the user
  99. if user.is_active:
  100. print("User is valid, active and authenticated")
  101. else:
  102. print("The password is valid, but the account has been disabled!")
  103. else:
  104. # the authentication system was unable to verify the username and password
  105. print("The username and password were incorrect.")
  106. .. note::
  107. This is a low level way to authenticate a set of credentials; for
  108. example, it's used by the
  109. :class:`~django.contrib.auth.middleware.RemoteUserMiddleware`. Unless
  110. you are writing your own authentication system, you probably won't use
  111. this. Rather if you are looking for a way to limit access to logged in
  112. users, see the :func:`~django.contrib.auth.decorators.login_required`
  113. decorator.
  114. .. _topic-authorization:
  115. Permissions and Authorization
  116. =============================
  117. Django comes with a simple permissions system. It provides a way to assign
  118. permissions to specific users and groups of users.
  119. It's used by the Django admin site, but you're welcome to use it in your own
  120. code.
  121. The Django admin site uses permissions as follows:
  122. * Access to view the "add" form and add an object is limited to users with
  123. the "add" permission for that type of object.
  124. * Access to view the change list, view the "change" form and change an
  125. object is limited to users with the "change" permission for that type of
  126. object.
  127. * Access to delete an object is limited to users with the "delete"
  128. permission for that type of object.
  129. Permissions can be set not only per type of object, but also per specific
  130. object instance. By using the
  131. :meth:`~django.contrib.admin.ModelAdmin.has_add_permission`,
  132. :meth:`~django.contrib.admin.ModelAdmin.has_change_permission` and
  133. :meth:`~django.contrib.admin.ModelAdmin.has_delete_permission` methods provided
  134. by the :class:`~django.contrib.admin.ModelAdmin` class, it is possible to
  135. customize permissions for different object instances of the same type.
  136. :class:`~django.contrib.auth.models.User` objects have two many-to-many
  137. fields: ``groups`` and ``user_permissions``.
  138. :class:`~django.contrib.auth.models.User` objects can access their related
  139. objects in the same way as any other :doc:`Django model
  140. </topics/db/models>`::
  141. myuser.groups = [group_list]
  142. myuser.groups.add(group, group, ...)
  143. myuser.groups.remove(group, group, ...)
  144. myuser.groups.clear()
  145. myuser.user_permissions = [permission_list]
  146. myuser.user_permissions.add(permission, permission, ...)
  147. myuser.user_permissions.remove(permission, permission, ...)
  148. myuser.user_permissions.clear()
  149. Default permissions
  150. -------------------
  151. When ``django.contrib.auth`` is listed in your :setting:`INSTALLED_APPS`
  152. setting, it will ensure that three default permissions -- add, change and
  153. delete -- are created for each Django model defined in one of your installed
  154. applications.
  155. These permissions will be created when you run :djadmin:`manage.py migrate
  156. <migrate>`; the first time you run ``migrate`` after adding
  157. ``django.contrib.auth`` to :setting:`INSTALLED_APPS`, the default permissions
  158. will be created for all previously-installed models, as well as for any new
  159. models being installed at that time. Afterward, it will create default
  160. permissions for new models each time you run :djadmin:`manage.py migrate
  161. <migrate>`.
  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 Group, 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. else:
  239. # Do something for anonymous users.
  240. .. _how-to-log-a-user-in:
  241. How to log a user in
  242. --------------------
  243. If you have an authenticated user you want to attach to the current session
  244. - this is done with a :func:`~django.contrib.auth.login` function.
  245. .. function:: login()
  246. To log a user in, from a view, use :func:`~django.contrib.auth.login()`. It
  247. takes an :class:`~django.http.HttpRequest` object and a
  248. :class:`~django.contrib.auth.models.User` object.
  249. :func:`~django.contrib.auth.login()` saves the user's ID in the session,
  250. using Django's session framework.
  251. Note that any data set during the anonymous session is retained in the
  252. session after a user logs in.
  253. This example shows how you might use both
  254. :func:`~django.contrib.auth.authenticate()` and
  255. :func:`~django.contrib.auth.login()`::
  256. from django.contrib.auth import authenticate, login
  257. def my_view(request):
  258. username = request.POST['username']
  259. password = request.POST['password']
  260. user = authenticate(username=username, password=password)
  261. if user is not None:
  262. if user.is_active:
  263. login(request, user)
  264. # Redirect to a success page.
  265. else:
  266. # Return a 'disabled account' error message
  267. else:
  268. # Return an 'invalid login' error message.
  269. .. admonition:: Calling ``authenticate()`` first
  270. When you're manually logging a user in, you *must* call
  271. :func:`~django.contrib.auth.authenticate()` before you call
  272. :func:`~django.contrib.auth.login()`.
  273. :func:`~django.contrib.auth.authenticate()`
  274. sets an attribute on the :class:`~django.contrib.auth.models.User` noting
  275. which authentication backend successfully authenticated that user (see the
  276. :ref:`backends documentation <authentication-backends>` for details), and
  277. this information is needed later during the login process. An error will be
  278. raised if you try to login a user object retrieved from the database
  279. directly.
  280. How to log a user out
  281. ---------------------
  282. .. function:: logout()
  283. To log out a user who has been logged in via
  284. :func:`django.contrib.auth.login()`, use
  285. :func:`django.contrib.auth.logout()` within your view. It takes an
  286. :class:`~django.http.HttpRequest` object and has no return value.
  287. Example::
  288. from django.contrib.auth import logout
  289. def logout_view(request):
  290. logout(request)
  291. # Redirect to a success page.
  292. Note that :func:`~django.contrib.auth.logout()` doesn't throw any errors if
  293. the user wasn't logged in.
  294. When you call :func:`~django.contrib.auth.logout()`, the session data for
  295. the current request is completely cleaned out. All existing data is
  296. removed. This is to prevent another person from using the same Web browser
  297. to log in and have access to the previous user's session data. If you want
  298. to put anything into the session that will be available to the user
  299. immediately after logging out, do that *after* calling
  300. :func:`django.contrib.auth.logout()`.
  301. Limiting access to logged-in users
  302. ----------------------------------
  303. The raw way
  304. ~~~~~~~~~~~
  305. The simple, raw way to limit access to pages is to check
  306. :meth:`request.user.is_authenticated()
  307. <django.contrib.auth.models.User.is_authenticated()>` and either redirect to a
  308. login page::
  309. from django.shortcuts import redirect
  310. def my_view(request):
  311. if not request.user.is_authenticated():
  312. return redirect('/login/?next=%s' % request.path)
  313. # ...
  314. ...or display an error message::
  315. from django.shortcuts import render
  316. def my_view(request):
  317. if not request.user.is_authenticated():
  318. return render(request, 'myapp/login_error.html')
  319. # ...
  320. .. currentmodule:: django.contrib.auth.decorators
  321. The login_required decorator
  322. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  323. .. function:: login_required([redirect_field_name=REDIRECT_FIELD_NAME, login_url=None])
  324. As a shortcut, you can use the convenient
  325. :func:`~django.contrib.auth.decorators.login_required` decorator::
  326. from django.contrib.auth.decorators import login_required
  327. @login_required
  328. def my_view(request):
  329. ...
  330. :func:`~django.contrib.auth.decorators.login_required` does the following:
  331. * If the user isn't logged in, redirect to
  332. :setting:`settings.LOGIN_URL <LOGIN_URL>`, passing the current absolute
  333. path in the query string. Example: ``/accounts/login/?next=/polls/3/``.
  334. * If the user is logged in, execute the view normally. The view code is
  335. free to assume the user is logged in.
  336. By default, the path that the user should be redirected to upon
  337. successful authentication is stored in a query string parameter called
  338. ``"next"``. If you would prefer to use a different name for this parameter,
  339. :func:`~django.contrib.auth.decorators.login_required` takes an
  340. optional ``redirect_field_name`` parameter::
  341. from django.contrib.auth.decorators import login_required
  342. @login_required(redirect_field_name='my_redirect_field')
  343. def my_view(request):
  344. ...
  345. Note that if you provide a value to ``redirect_field_name``, you will most
  346. likely need to customize your login template as well, since the template
  347. context variable which stores the redirect path will use the value of
  348. ``redirect_field_name`` as its key rather than ``"next"`` (the default).
  349. :func:`~django.contrib.auth.decorators.login_required` also takes an
  350. optional ``login_url`` parameter. Example::
  351. from django.contrib.auth.decorators import login_required
  352. @login_required(login_url='/accounts/login/')
  353. def my_view(request):
  354. ...
  355. Note that if you don't specify the ``login_url`` parameter, you'll need to
  356. ensure that the :setting:`settings.LOGIN_URL <LOGIN_URL>` and your login
  357. view are properly associated. For example, using the defaults, add the
  358. following lines to your URLconf::
  359. from django.contrib.auth import views as auth_views
  360. url(r'^accounts/login/$', auth_views.login),
  361. The :setting:`settings.LOGIN_URL <LOGIN_URL>` also accepts view function
  362. names and :ref:`named URL patterns <naming-url-patterns>`. This allows you
  363. to freely remap your login view within your URLconf without having to
  364. update the setting.
  365. .. note::
  366. The login_required decorator does NOT check the is_active flag on a user.
  367. Limiting access to logged-in users that pass a test
  368. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  369. To limit access based on certain permissions or some other test, you'd do
  370. essentially the same thing as described in the previous section.
  371. The simple way is to run your test on :attr:`request.user
  372. <django.http.HttpRequest.user>` in the view directly. For example, this view
  373. checks to make sure the user has an email in the desired domain::
  374. def my_view(request):
  375. if not '@example.com' in request.user.email:
  376. return HttpResponse("You can't vote in this poll.")
  377. # ...
  378. .. function:: user_passes_test(func, [login_url=None, redirect_field_name=REDIRECT_FIELD_NAME])
  379. As a shortcut, you can use the convenient ``user_passes_test`` decorator::
  380. from django.contrib.auth.decorators import user_passes_test
  381. def email_check(user):
  382. return '@example.com' in user.email
  383. @user_passes_test(email_check)
  384. def my_view(request):
  385. ...
  386. :func:`~django.contrib.auth.decorators.user_passes_test` takes a required
  387. argument: a callable that takes a
  388. :class:`~django.contrib.auth.models.User` object and returns ``True`` if
  389. the user is allowed to view the page. Note that
  390. :func:`~django.contrib.auth.decorators.user_passes_test` does not
  391. automatically check that the :class:`~django.contrib.auth.models.User` is
  392. not anonymous.
  393. :func:`~django.contrib.auth.decorators.user_passes_test` takes two
  394. optional arguments:
  395. ``login_url``
  396. Lets you specify the URL that users who don't pass the test will be
  397. redirected to. It may be a login page and defaults to
  398. :setting:`settings.LOGIN_URL <LOGIN_URL>` if you don't specify one.
  399. ``redirect_field_name``
  400. Same as for :func:`~django.contrib.auth.decorators.login_required`.
  401. Setting it to ``None`` removes it from the URL, which you may want to do
  402. if you are redirecting users that don't pass the test to a non-login
  403. page where there's no "next page".
  404. For example::
  405. @user_passes_test(email_check, login_url='/login/')
  406. def my_view(request):
  407. ...
  408. The permission_required decorator
  409. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  410. .. function:: permission_required(perm, [login_url=None, raise_exception=False])
  411. It's a relatively common task to check whether a user has a particular
  412. permission. For that reason, Django provides a shortcut for that case: the
  413. :func:`~django.contrib.auth.decorators.permission_required()` decorator.::
  414. from django.contrib.auth.decorators import permission_required
  415. @permission_required('polls.can_vote')
  416. def my_view(request):
  417. ...
  418. As for the :meth:`~django.contrib.auth.models.User.has_perm` method,
  419. permission names take the form ``"<app label>.<permission codename>"``
  420. (i.e. ``polls.can_vote`` for a permission on a model in the ``polls``
  421. application).
  422. Note that :func:`~django.contrib.auth.decorators.permission_required()`
  423. also takes an optional ``login_url`` parameter. Example::
  424. from django.contrib.auth.decorators import permission_required
  425. @permission_required('polls.can_vote', login_url='/loginpage/')
  426. def my_view(request):
  427. ...
  428. As in the :func:`~django.contrib.auth.decorators.login_required` decorator,
  429. ``login_url`` defaults to :setting:`settings.LOGIN_URL <LOGIN_URL>`.
  430. If the ``raise_exception`` parameter is given, the decorator will raise
  431. :exc:`~django.core.exceptions.PermissionDenied`, prompting :ref:`the 403
  432. (HTTP Forbidden) view<http_forbidden_view>` instead of redirecting to the
  433. login page.
  434. .. versionchanged:: 1.7
  435. The :func:`~django.contrib.auth.decorators.permission_required`
  436. decorator can take a list of permissions as well as a single permission.
  437. .. _applying-permissions-to-generic-views:
  438. Applying permissions to generic views
  439. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  440. To apply a permission to a :doc:`class-based generic view
  441. </ref/class-based-views/index>`, decorate the :meth:`View.dispatch
  442. <django.views.generic.base.View.dispatch>` method on the class. See
  443. :ref:`decorating-class-based-views` for details. Another approach is to
  444. :ref:`write a mixin that wraps as_view() <mixins_that_wrap_as_view>`.
  445. .. _session-invalidation-on-password-change:
  446. Session invalidation on password change
  447. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  448. .. versionadded:: 1.7
  449. .. warning::
  450. This protection only applies if
  451. :class:`~django.contrib.auth.middleware.SessionAuthenticationMiddleware`
  452. is enabled in :setting:`MIDDLEWARE_CLASSES`. It's included if
  453. ``settings.py`` was generated by :djadmin:`startproject` on Django ≥ 1.7.
  454. If your :setting:`AUTH_USER_MODEL` inherits from
  455. :class:`~django.contrib.auth.models.AbstractBaseUser` or implements its own
  456. :meth:`~django.contrib.auth.models.AbstractBaseUser.get_session_auth_hash()`
  457. method, authenticated sessions will include the hash returned by this function.
  458. In the :class:`~django.contrib.auth.models.AbstractBaseUser` case, this is an
  459. HMAC of the password field. If the
  460. :class:`~django.contrib.auth.middleware.SessionAuthenticationMiddleware` is
  461. enabled, Django verifies that the hash sent along with each request matches
  462. the one that's computed server-side. This allows a user to log out all of their
  463. sessions by changing their password.
  464. The default password change views included with Django,
  465. :func:`django.contrib.auth.views.password_change` and the
  466. ``user_change_password`` view in the :mod:`django.contrib.auth` admin, update
  467. the session with the new password hash so that a user changing their own
  468. password won't log themselves out. If you have a custom password change view
  469. and wish to have similar behavior, use this function:
  470. .. function:: update_session_auth_hash(request, user)
  471. This function takes the current request and the updated user object from
  472. which the new session hash will be derived and updates the session hash
  473. appropriately. Example usage::
  474. from django.contrib.auth import update_session_auth_hash
  475. def password_change(request):
  476. if request.method == 'POST':
  477. form = PasswordChangeForm(user=request.user, data=request.POST)
  478. if form.is_valid():
  479. form.save()
  480. update_session_auth_hash(request, form.user)
  481. else:
  482. ...
  483. If you are upgrading an existing site and wish to enable this middleware without
  484. requiring all your users to re-login afterward, you should first upgrade to
  485. Django 1.7 and run it for a while so that as sessions are naturally recreated
  486. as users login, they include the session hash as described above. Once you
  487. start running your site with
  488. :class:`~django.contrib.auth.middleware.SessionAuthenticationMiddleware`, any
  489. users who have not logged in and had their session updated with the verification
  490. hash will have their existing session invalidated and be required to login.
  491. .. note::
  492. Since
  493. :meth:`~django.contrib.auth.models.AbstractBaseUser.get_session_auth_hash()`
  494. is based on :setting:`SECRET_KEY`, updating your site to use a new secret
  495. will invalidate all existing sessions.
  496. .. _built-in-auth-views:
  497. Authentication Views
  498. --------------------
  499. .. module:: django.contrib.auth.views
  500. Django provides several views that you can use for handling login, logout, and
  501. password management. These make use of the :ref:`stock auth forms
  502. <built-in-auth-forms>` but you can pass in your own forms as well.
  503. Django provides no default template for the authentication views - however the
  504. template context is documented for each view below.
  505. The built-in views all return
  506. a :class:`~django.template.response.TemplateResponse` instance, which allows
  507. you to easily customize the response data before rendering. For more details,
  508. see the :doc:`TemplateResponse documentation </ref/template-response>`.
  509. Most built-in authentication views provide a URL name for easier reference. See
  510. :doc:`the URL documentation </topics/http/urls>` for details on using named URL
  511. patterns.
  512. .. function:: login(request, [template_name, redirect_field_name, authentication_form, current_app, extra_context])
  513. **URL name:** ``login``
  514. See :doc:`the URL documentation </topics/http/urls>` for details on using
  515. named URL patterns.
  516. **Optional arguments:**
  517. * ``template_name``: The name of a template to display for the view used to
  518. log the user in. Defaults to :file:`registration/login.html`.
  519. * ``redirect_field_name``: The name of a ``GET`` field containing the
  520. URL to redirect to after login. Defaults to ``next``.
  521. * ``authentication_form``: A callable (typically just a form class) to
  522. use for authentication. Defaults to
  523. :class:`~django.contrib.auth.forms.AuthenticationForm`.
  524. * ``current_app``: A hint indicating which application contains the current
  525. view. See the :ref:`namespaced URL resolution strategy
  526. <topics-http-reversing-url-namespaces>` for more information.
  527. * ``extra_context``: A dictionary of context data that will be added to the
  528. default context data passed to the template.
  529. Here's what ``django.contrib.auth.views.login`` does:
  530. * If called via ``GET``, it displays a login form that POSTs to the
  531. same URL. More on this in a bit.
  532. * If called via ``POST`` with user submitted credentials, it tries to log
  533. the user in. If login is successful, the view redirects to the URL
  534. specified in ``next``. If ``next`` isn't provided, it redirects to
  535. :setting:`settings.LOGIN_REDIRECT_URL <LOGIN_REDIRECT_URL>` (which
  536. defaults to ``/accounts/profile/``). If login isn't successful, it
  537. redisplays the login form.
  538. It's your responsibility to provide the html for the login template
  539. , called ``registration/login.html`` by default. This template gets passed
  540. four template context variables:
  541. * ``form``: A :class:`~django.forms.Form` object representing the
  542. :class:`~django.contrib.auth.forms.AuthenticationForm`.
  543. * ``next``: The URL to redirect to after successful login. This may
  544. contain a query string, too.
  545. * ``site``: The current :class:`~django.contrib.sites.models.Site`,
  546. according to the :setting:`SITE_ID` setting. If you don't have the
  547. site framework installed, this will be set to an instance of
  548. :class:`~django.contrib.sites.requests.RequestSite`, which derives the
  549. site name and domain from the current
  550. :class:`~django.http.HttpRequest`.
  551. * ``site_name``: An alias for ``site.name``. If you don't have the site
  552. framework installed, this will be set to the value of
  553. :attr:`request.META['SERVER_NAME'] <django.http.HttpRequest.META>`.
  554. For more on sites, see :doc:`/ref/contrib/sites`.
  555. If you'd prefer not to call the template :file:`registration/login.html`,
  556. you can pass the ``template_name`` parameter via the extra arguments to
  557. the view in your URLconf. For example, this URLconf line would use
  558. :file:`myapp/login.html` instead::
  559. url(r'^accounts/login/$', auth_views.login, {'template_name': 'myapp/login.html'}),
  560. You can also specify the name of the ``GET`` field which contains the URL
  561. to redirect to after login by passing ``redirect_field_name`` to the view.
  562. By default, the field is called ``next``.
  563. Here's a sample :file:`registration/login.html` template you can use as a
  564. starting point. It assumes you have a :file:`base.html` template that
  565. defines a ``content`` block:
  566. .. code-block:: html+django
  567. {% extends "base.html" %}
  568. {% block content %}
  569. {% if form.errors %}
  570. <p>Your username and password didn't match. Please try again.</p>
  571. {% endif %}
  572. <form method="post" action="{% url 'django.contrib.auth.views.login' %}">
  573. {% csrf_token %}
  574. <table>
  575. <tr>
  576. <td>{{ form.username.label_tag }}</td>
  577. <td>{{ form.username }}</td>
  578. </tr>
  579. <tr>
  580. <td>{{ form.password.label_tag }}</td>
  581. <td>{{ form.password }}</td>
  582. </tr>
  583. </table>
  584. <input type="submit" value="login" />
  585. <input type="hidden" name="next" value="{{ next }}" />
  586. </form>
  587. {% endblock %}
  588. If you have customized authentication (see
  589. :doc:`Customizing Authentication </topics/auth/customizing>`) you can pass a custom authentication form
  590. to the login view via the ``authentication_form`` parameter. This form must
  591. accept a ``request`` keyword argument in its ``__init__`` method, and
  592. provide a ``get_user`` method which returns the authenticated user object
  593. (this method is only ever called after successful form validation).
  594. .. _forms documentation: ../forms/
  595. .. _site framework docs: ../sites/
  596. .. function:: logout(request, [next_page, template_name, redirect_field_name, current_app, extra_context])
  597. Logs a user out.
  598. **URL name:** ``logout``
  599. **Optional arguments:**
  600. * ``next_page``: The URL to redirect to after logout.
  601. * ``template_name``: The full name of a template to display after
  602. logging the user out. Defaults to
  603. :file:`registration/logged_out.html` if no argument is supplied.
  604. * ``redirect_field_name``: The name of a ``GET`` field containing the
  605. URL to redirect to after log out. Defaults to ``next``. Overrides the
  606. ``next_page`` URL if the given ``GET`` parameter is passed.
  607. * ``current_app``: A hint indicating which application contains the current
  608. view. See the :ref:`namespaced URL resolution strategy
  609. <topics-http-reversing-url-namespaces>` for more information.
  610. * ``extra_context``: A dictionary of context data that will be added to the
  611. default context data passed to the template.
  612. **Template context:**
  613. * ``title``: The string "Logged out", localized.
  614. * ``site``: The current :class:`~django.contrib.sites.models.Site`,
  615. according to the :setting:`SITE_ID` setting. If you don't have the
  616. site framework installed, this will be set to an instance of
  617. :class:`~django.contrib.sites.requests.RequestSite`, which derives the
  618. site name and domain from the current
  619. :class:`~django.http.HttpRequest`.
  620. * ``site_name``: An alias for ``site.name``. If you don't have the site
  621. framework installed, this will be set to the value of
  622. :attr:`request.META['SERVER_NAME'] <django.http.HttpRequest.META>`.
  623. For more on sites, see :doc:`/ref/contrib/sites`.
  624. * ``current_app``: A hint indicating which application contains the current
  625. view. See the :ref:`namespaced URL resolution strategy
  626. <topics-http-reversing-url-namespaces>` for more information.
  627. * ``extra_context``: A dictionary of context data that will be added to the
  628. default context data passed to the template.
  629. .. function:: logout_then_login(request[, login_url, current_app, extra_context])
  630. Logs a user out, then redirects to the login page.
  631. **URL name:** No default URL provided
  632. **Optional arguments:**
  633. * ``login_url``: The URL of the login page to redirect to.
  634. Defaults to :setting:`settings.LOGIN_URL <LOGIN_URL>` if not supplied.
  635. * ``current_app``: A hint indicating which application contains the current
  636. view. See the :ref:`namespaced URL resolution strategy
  637. <topics-http-reversing-url-namespaces>` for more information.
  638. * ``extra_context``: A dictionary of context data that will be added to the
  639. default context data passed to the template.
  640. .. function:: password_change(request[, template_name, post_change_redirect, password_change_form, current_app, extra_context])
  641. Allows a user to change their password.
  642. **URL name:** ``password_change``
  643. **Optional arguments:**
  644. * ``template_name``: The full name of a template to use for
  645. displaying the password change form. Defaults to
  646. :file:`registration/password_change_form.html` if not supplied.
  647. * ``post_change_redirect``: The URL to redirect to after a successful
  648. password change.
  649. * ``password_change_form``: A custom "change password" form which must
  650. accept a ``user`` keyword argument. The form is responsible for
  651. actually changing the user's password. Defaults to
  652. :class:`~django.contrib.auth.forms.PasswordChangeForm`.
  653. * ``current_app``: A hint indicating which application contains the current
  654. view. See the :ref:`namespaced URL resolution strategy
  655. <topics-http-reversing-url-namespaces>` for more information.
  656. * ``extra_context``: A dictionary of context data that will be added to the
  657. default context data passed to the template.
  658. **Template context:**
  659. * ``form``: The password change form (see ``password_change_form`` above).
  660. .. function:: password_change_done(request[, template_name, current_app, extra_context])
  661. The page shown after a user has changed their password.
  662. **URL name:** ``password_change_done``
  663. **Optional arguments:**
  664. * ``template_name``: The full name of a template to use.
  665. Defaults to :file:`registration/password_change_done.html` if not
  666. supplied.
  667. * ``current_app``: A hint indicating which application contains the current
  668. view. See the :ref:`namespaced URL resolution strategy
  669. <topics-http-reversing-url-namespaces>` for more information.
  670. * ``extra_context``: A dictionary of context data that will be added to the
  671. default context data passed to the template.
  672. .. function:: password_reset(request[, is_admin_site, template_name, email_template_name, password_reset_form, token_generator, post_reset_redirect, from_email, current_app, extra_context, html_email_template_name])
  673. Allows a user to reset their password by generating a one-time use link
  674. that can be used to reset the password, and sending that link to the
  675. user's registered email address.
  676. If the email address provided does not exist in the system, this view
  677. won't send an email, but the user won't receive any error message either.
  678. This prevents information leaking to potential attackers. If you want to
  679. provide an error message in this case, you can subclass
  680. :class:`~django.contrib.auth.forms.PasswordResetForm` and use the
  681. ``password_reset_form`` argument.
  682. Users flagged with an unusable password (see
  683. :meth:`~django.contrib.auth.models.User.set_unusable_password()` aren't
  684. allowed to request a password reset to prevent misuse when using an
  685. external authentication source like LDAP. Note that they won't receive any
  686. error message since this would expose their account's existence but no
  687. mail will be sent either.
  688. **URL name:** ``password_reset``
  689. **Optional arguments:**
  690. * ``template_name``: The full name of a template to use for
  691. displaying the password reset form. Defaults to
  692. :file:`registration/password_reset_form.html` if not supplied.
  693. * ``email_template_name``: The full name of a template to use for
  694. generating the email with the reset password link. Defaults to
  695. :file:`registration/password_reset_email.html` if not supplied.
  696. * ``subject_template_name``: The full name of a template to use for
  697. the subject of the email with the reset password link. Defaults
  698. to :file:`registration/password_reset_subject.txt` if not supplied.
  699. * ``password_reset_form``: Form that will be used to get the email of
  700. the user to reset the password for. Defaults to
  701. :class:`~django.contrib.auth.forms.PasswordResetForm`.
  702. * ``token_generator``: Instance of the class to check the one time link.
  703. This will default to ``default_token_generator``, it's an instance of
  704. ``django.contrib.auth.tokens.PasswordResetTokenGenerator``.
  705. * ``post_reset_redirect``: The URL to redirect to after a successful
  706. password reset request.
  707. * ``from_email``: A valid email address. By default Django uses
  708. the :setting:`DEFAULT_FROM_EMAIL`.
  709. * ``current_app``: A hint indicating which application contains the current
  710. view. See the :ref:`namespaced URL resolution strategy
  711. <topics-http-reversing-url-namespaces>` for more information.
  712. * ``extra_context``: A dictionary of context data that will be added to the
  713. default context data passed to the template.
  714. * ``html_email_template_name``: The full name of a template to use
  715. for generating a ``text/html`` multipart email with the password reset
  716. link. By default, HTML email is not sent.
  717. .. versionadded:: 1.7
  718. ``html_email_template_name`` was added.
  719. **Template context:**
  720. * ``form``: The form (see ``password_reset_form`` above) for resetting
  721. the user's password.
  722. **Email template context:**
  723. * ``email``: An alias for ``user.email``
  724. * ``user``: The current :class:`~django.contrib.auth.models.User`,
  725. according to the ``email`` form field. Only active users are able to
  726. reset their passwords (``User.is_active is True``).
  727. * ``site_name``: An alias for ``site.name``. If you don't have the site
  728. framework installed, this will be set to the value of
  729. :attr:`request.META['SERVER_NAME'] <django.http.HttpRequest.META>`.
  730. For more on sites, see :doc:`/ref/contrib/sites`.
  731. * ``domain``: An alias for ``site.domain``. If you don't have the site
  732. framework installed, this will be set to the value of
  733. ``request.get_host()``.
  734. * ``protocol``: http or https
  735. * ``uid``: The user's primary key encoded in base 64.
  736. * ``token``: Token to check that the reset link is valid.
  737. Sample ``registration/password_reset_email.html`` (email body template):
  738. .. code-block:: html+django
  739. Someone asked for password reset for email {{ email }}. Follow the link below:
  740. {{ protocol}}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %}
  741. The same template context is used for subject template. Subject must be
  742. single line plain text string.
  743. .. function:: password_reset_done(request[, template_name, current_app, extra_context])
  744. The page shown after a user has been emailed a link to reset their
  745. password. This view is called by default if the :func:`password_reset` view
  746. doesn't have an explicit ``post_reset_redirect`` URL set.
  747. **URL name:** ``password_reset_done``
  748. **Optional arguments:**
  749. * ``template_name``: The full name of a template to use.
  750. Defaults to :file:`registration/password_reset_done.html` if not
  751. supplied.
  752. * ``current_app``: A hint indicating which application contains the current
  753. view. See the :ref:`namespaced URL resolution strategy
  754. <topics-http-reversing-url-namespaces>` for more information.
  755. * ``extra_context``: A dictionary of context data that will be added to the
  756. default context data passed to the template.
  757. .. function:: password_reset_confirm(request[, uidb64, token, template_name, token_generator, set_password_form, post_reset_redirect, current_app, extra_context])
  758. Presents a form for entering a new password.
  759. **URL name:** ``password_reset_confirm``
  760. **Optional arguments:**
  761. * ``uidb64``: The user's id encoded in base 64. Defaults to ``None``.
  762. * ``token``: Token to check that the password is valid. Defaults to
  763. ``None``.
  764. * ``template_name``: The full name of a template to display the confirm
  765. password view. Default value is :file:`registration/password_reset_confirm.html`.
  766. * ``token_generator``: Instance of the class to check the password. This
  767. will default to ``default_token_generator``, it's an instance of
  768. ``django.contrib.auth.tokens.PasswordResetTokenGenerator``.
  769. * ``set_password_form``: Form that will be used to set the password.
  770. Defaults to :class:`~django.contrib.auth.forms.SetPasswordForm`
  771. * ``post_reset_redirect``: URL to redirect after the password reset
  772. done. Defaults to ``None``.
  773. * ``current_app``: A hint indicating which application contains the current
  774. view. See the :ref:`namespaced URL resolution strategy
  775. <topics-http-reversing-url-namespaces>` for more information.
  776. * ``extra_context``: A dictionary of context data that will be added to the
  777. default context data passed to the template.
  778. **Template context:**
  779. * ``form``: The form (see ``set_password_form`` above) for setting the
  780. new user's password.
  781. * ``validlink``: Boolean, True if the link (combination of ``uidb64`` and
  782. ``token``) is valid or unused yet.
  783. .. function:: password_reset_complete(request[,template_name, current_app, extra_context])
  784. Presents a view which informs the user that the password has been
  785. successfully changed.
  786. **URL name:** ``password_reset_complete``
  787. **Optional arguments:**
  788. * ``template_name``: The full name of a template to display the view.
  789. Defaults to :file:`registration/password_reset_complete.html`.
  790. * ``current_app``: A hint indicating which application contains the current
  791. view. See the :ref:`namespaced URL resolution strategy
  792. <topics-http-reversing-url-namespaces>` for more information.
  793. * ``extra_context``: A dictionary of context data that will be added to the
  794. default context data passed to the template.
  795. Helper functions
  796. ----------------
  797. .. currentmodule:: django.contrib.auth.views
  798. .. function:: redirect_to_login(next[, login_url, redirect_field_name])
  799. Redirects to the login page, and then back to another URL after a
  800. successful login.
  801. **Required arguments:**
  802. * ``next``: The URL to redirect to after a successful login.
  803. **Optional arguments:**
  804. * ``login_url``: The URL of the login page to redirect to.
  805. Defaults to :setting:`settings.LOGIN_URL <LOGIN_URL>` if not supplied.
  806. * ``redirect_field_name``: The name of a ``GET`` field containing the
  807. URL to redirect to after log out. Overrides ``next`` if the given
  808. ``GET`` parameter is passed.
  809. .. _built-in-auth-forms:
  810. Built-in forms
  811. --------------
  812. .. module:: django.contrib.auth.forms
  813. If you don't want to use the built-in views, but want the convenience of not
  814. having to write forms for this functionality, the authentication system
  815. provides several built-in forms located in :mod:`django.contrib.auth.forms`:
  816. .. note::
  817. The built-in authentication forms make certain assumptions about the user
  818. model that they are working with. If you're using a :ref:`custom User model
  819. <auth-custom-user>`, it may be necessary to define your own forms for the
  820. authentication system. For more information, refer to the documentation
  821. about :ref:`using the built-in authentication forms with custom user models
  822. <custom-users-and-the-built-in-auth-forms>`.
  823. .. class:: AdminPasswordChangeForm
  824. A form used in the admin interface to change a user's password.
  825. Takes the ``user`` as the first positional argument.
  826. .. class:: AuthenticationForm
  827. A form for logging a user in.
  828. Takes ``request`` as its first positional argument, which is stored on the
  829. form instance for use by sub-classes.
  830. .. method:: confirm_login_allowed(user)
  831. .. versionadded:: 1.7
  832. By default, ``AuthenticationForm`` rejects users whose ``is_active`` flag
  833. is set to ``False``. You may override this behavior with a custom policy to
  834. determine which users can log in. Do this with a custom form that subclasses
  835. ``AuthenticationForm`` and overrides the ``confirm_login_allowed`` method.
  836. This method should raise a :exc:`~django.core.exceptions.ValidationError`
  837. if the given user may not log in.
  838. For example, to allow all users to log in, regardless of "active" status::
  839. from django.contrib.auth.forms import AuthenticationForm
  840. class AuthenticationFormWithInactiveUsersOkay(AuthenticationForm):
  841. def confirm_login_allowed(self, user):
  842. pass
  843. Or to allow only some active users to log in::
  844. class PickyAuthenticationForm(AuthenticationForm):
  845. def confirm_login_allowed(self, user):
  846. if not user.is_active:
  847. raise forms.ValidationError(
  848. _("This account is inactive."),
  849. code='inactive',
  850. )
  851. if user.username.startswith('b'):
  852. raise forms.ValidationError(
  853. _("Sorry, accounts starting with 'b' aren't welcome here."),
  854. code='no_b_users',
  855. )
  856. .. class:: PasswordChangeForm
  857. A form for allowing a user to change their password.
  858. .. class:: PasswordResetForm
  859. A form for generating and emailing a one-time use link to reset a
  860. user's password.
  861. .. method:: send_email(subject_template_name, email_template_name, context, from_email, to_email, [html_email_template_name=None])
  862. .. versionadded:: 1.8
  863. Uses the arguments to send an ``EmailMultiAlternatives``.
  864. Can be overridden to customize how the email is sent to the user.
  865. :param subject_template_name: the template for the subject.
  866. :param email_template_name: the template for the email body.
  867. :param context: context passed to the ``subject_template``, ``email_template``,
  868. and ``html_email_template`` (if it is not ``None``).
  869. :param from_email: the sender's email.
  870. :param to_email: the email of the requester.
  871. :param html_email_template_name: the template for the HTML body;
  872. defaults to ``None``, in which case a plain text email is sent.
  873. By default, ``save()`` populates the ``context`` with the
  874. same variables that :func:`~django.contrib.auth.views.password_reset`
  875. passes to its email context.
  876. .. class:: SetPasswordForm
  877. A form that lets a user change their password without entering the old
  878. password.
  879. .. class:: UserChangeForm
  880. A form used in the admin interface to change a user's information and
  881. permissions.
  882. .. class:: UserCreationForm
  883. A form for creating a new user.
  884. .. currentmodule:: django.contrib.auth
  885. Authentication data in templates
  886. --------------------------------
  887. The currently logged-in user and their permissions are made available in the
  888. :doc:`template context </ref/templates/api>` when you use
  889. :class:`~django.template.RequestContext`.
  890. .. admonition:: Technicality
  891. Technically, these variables are only made available in the template context
  892. if you use :class:`~django.template.RequestContext` *and* your
  893. :setting:`TEMPLATE_CONTEXT_PROCESSORS` setting contains
  894. ``"django.contrib.auth.context_processors.auth"``, which is default. For
  895. more, see the :ref:`RequestContext docs <subclassing-context-requestcontext>`.
  896. Users
  897. ~~~~~
  898. When rendering a template :class:`~django.template.RequestContext`, the
  899. currently logged-in user, either a :class:`~django.contrib.auth.models.User`
  900. instance or an :class:`~django.contrib.auth.models.AnonymousUser` instance, is
  901. stored in the template variable ``{{ user }}``:
  902. .. code-block:: html+django
  903. {% if user.is_authenticated %}
  904. <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
  905. {% else %}
  906. <p>Welcome, new user. Please log in.</p>
  907. {% endif %}
  908. This template context variable is not available if a ``RequestContext`` is not
  909. being used.
  910. Permissions
  911. ~~~~~~~~~~~
  912. The currently logged-in user's permissions are stored in the template variable
  913. ``{{ perms }}``. This is an instance of
  914. ``django.contrib.auth.context_processors.PermWrapper``, which is a
  915. template-friendly proxy of permissions.
  916. In the ``{{ perms }}`` object, single-attribute lookup is a proxy to
  917. :meth:`User.has_module_perms <django.contrib.auth.models.User.has_module_perms>`.
  918. This example would display ``True`` if the logged-in user had any permissions
  919. in the ``foo`` app::
  920. {{ perms.foo }}
  921. Two-level-attribute lookup is a proxy to
  922. :meth:`User.has_perm <django.contrib.auth.models.User.has_perm>`. This example
  923. would display ``True`` if the logged-in user had the permission
  924. ``foo.can_vote``::
  925. {{ perms.foo.can_vote }}
  926. Thus, you can check permissions in template ``{% if %}`` statements:
  927. .. code-block:: html+django
  928. {% if perms.foo %}
  929. <p>You have permission to do something in the foo app.</p>
  930. {% if perms.foo.can_vote %}
  931. <p>You can vote!</p>
  932. {% endif %}
  933. {% if perms.foo.can_drive %}
  934. <p>You can drive!</p>
  935. {% endif %}
  936. {% else %}
  937. <p>You don't have permission to do anything in the foo app.</p>
  938. {% endif %}
  939. It is possible to also look permissions up by ``{% if in %}`` statements.
  940. For example:
  941. .. code-block:: html+django
  942. {% if 'foo' in perms %}
  943. {% if 'foo.can_vote' in perms %}
  944. <p>In lookup works, too.</p>
  945. {% endif %}
  946. {% endif %}
  947. .. _auth-admin:
  948. Managing users in the admin
  949. ===========================
  950. When you have both ``django.contrib.admin`` and ``django.contrib.auth``
  951. installed, the admin provides a convenient way to view and manage users,
  952. groups, and permissions. Users can be created and deleted like any Django
  953. model. Groups can be created, and permissions can be assigned to users or
  954. groups. A log of user edits to models made within the admin is also stored and
  955. displayed.
  956. Creating Users
  957. --------------
  958. You should see a link to "Users" in the "Auth"
  959. section of the main admin index page. The "Add user" admin page is different
  960. than standard admin pages in that it requires you to choose a username and
  961. password before allowing you to edit the rest of the user's fields.
  962. Also note: if you want a user account to be able to create users using the
  963. Django admin site, you'll need to give them permission to add users *and*
  964. change users (i.e., the "Add user" and "Change user" permissions). If an
  965. account has permission to add users but not to change them, that account won't
  966. be able to add users. Why? Because if you have permission to add users, you
  967. have the power to create superusers, which can then, in turn, change other
  968. users. So Django requires add *and* change permissions as a slight security
  969. measure.
  970. Changing Passwords
  971. ------------------
  972. User passwords are not displayed in the admin (nor stored in the database), but
  973. the :doc:`password storage details </topics/auth/passwords>` are displayed.
  974. Included in the display of this information is a link to
  975. a password change form that allows admins to change user passwords.