default.txt 62 KB

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