default.txt 53 KB

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