default.txt 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457
  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 Group, 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. Limiting access to logged-in users that pass a test
  378. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  379. To limit access based on certain permissions or some other test, you'd do
  380. essentially the same thing as described in the previous section.
  381. The simple way is to run your test on :attr:`request.user
  382. <django.http.HttpRequest.user>` in the view directly. For example, this view
  383. checks to make sure the user has an email in the desired domain and if not,
  384. redirects to the login page::
  385. from django.shortcuts import redirect
  386. def my_view(request):
  387. if not request.user.email.endswith('@example.com'):
  388. return redirect('/login/?next=%s' % request.path)
  389. # ...
  390. .. function:: user_passes_test(func, [login_url=None, redirect_field_name=REDIRECT_FIELD_NAME])
  391. As a shortcut, you can use the convenient ``user_passes_test`` decorator
  392. which performs a redirect when the callable returns ``False``::
  393. from django.contrib.auth.decorators import user_passes_test
  394. def email_check(user):
  395. return user.email.endswith('@example.com')
  396. @user_passes_test(email_check)
  397. def my_view(request):
  398. ...
  399. :func:`~django.contrib.auth.decorators.user_passes_test` takes a required
  400. argument: a callable that takes a
  401. :class:`~django.contrib.auth.models.User` object and returns ``True`` if
  402. the user is allowed to view the page. Note that
  403. :func:`~django.contrib.auth.decorators.user_passes_test` does not
  404. automatically check that the :class:`~django.contrib.auth.models.User` is
  405. not anonymous.
  406. :func:`~django.contrib.auth.decorators.user_passes_test` takes two
  407. optional arguments:
  408. ``login_url``
  409. Lets you specify the URL that users who don't pass the test will be
  410. redirected to. It may be a login page and defaults to
  411. :setting:`settings.LOGIN_URL <LOGIN_URL>` if you don't specify one.
  412. ``redirect_field_name``
  413. Same as for :func:`~django.contrib.auth.decorators.login_required`.
  414. Setting it to ``None`` removes it from the URL, which you may want to do
  415. if you are redirecting users that don't pass the test to a non-login
  416. page where there's no "next page".
  417. For example::
  418. @user_passes_test(email_check, login_url='/login/')
  419. def my_view(request):
  420. ...
  421. The permission_required decorator
  422. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  423. .. function:: permission_required(perm, [login_url=None, raise_exception=False])
  424. It's a relatively common task to check whether a user has a particular
  425. permission. For that reason, Django provides a shortcut for that case: the
  426. :func:`~django.contrib.auth.decorators.permission_required()` decorator.::
  427. from django.contrib.auth.decorators import permission_required
  428. @permission_required('polls.can_vote')
  429. def my_view(request):
  430. ...
  431. Just like the :meth:`~django.contrib.auth.models.User.has_perm` method,
  432. permission names take the form ``"<app label>.<permission codename>"``
  433. (i.e. ``polls.can_vote`` for a permission on a model in the ``polls``
  434. application).
  435. The decorator may also take a list of permissions.
  436. Note that :func:`~django.contrib.auth.decorators.permission_required()`
  437. also takes an optional ``login_url`` parameter. Example::
  438. from django.contrib.auth.decorators import permission_required
  439. @permission_required('polls.can_vote', login_url='/loginpage/')
  440. def my_view(request):
  441. ...
  442. As in the :func:`~django.contrib.auth.decorators.login_required` decorator,
  443. ``login_url`` defaults to :setting:`settings.LOGIN_URL <LOGIN_URL>`.
  444. If the ``raise_exception`` parameter is given, the decorator will raise
  445. :exc:`~django.core.exceptions.PermissionDenied`, prompting :ref:`the 403
  446. (HTTP Forbidden) view<http_forbidden_view>` instead of redirecting to the
  447. login page.
  448. .. _applying-permissions-to-generic-views:
  449. Applying permissions to generic views
  450. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  451. To apply a permission to a :doc:`class-based generic view
  452. </ref/class-based-views/index>`, decorate the :meth:`View.dispatch
  453. <django.views.generic.base.View.dispatch>` method on the class. See
  454. :ref:`decorating-class-based-views` for details. Another approach is to
  455. :ref:`write a mixin that wraps as_view() <mixins_that_wrap_as_view>`.
  456. .. _session-invalidation-on-password-change:
  457. Session invalidation on password change
  458. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  459. .. warning::
  460. This protection only applies if
  461. :class:`~django.contrib.auth.middleware.SessionAuthenticationMiddleware`
  462. is enabled in :setting:`MIDDLEWARE_CLASSES`. It's included if
  463. ``settings.py`` was generated by :djadmin:`startproject` on Django ≥ 1.7.
  464. Session verification will become mandatory in Django 2.0 regardless of
  465. whether or not ``SessionAuthenticationMiddleware`` is enabled. If you have
  466. a pre-1.7 project or one generated using a template that doesn't include
  467. ``SessionAuthenticationMiddleware``, consider enabling it before then after
  468. reading the upgrade considerations below.
  469. If your :setting:`AUTH_USER_MODEL` inherits from
  470. :class:`~django.contrib.auth.models.AbstractBaseUser` or implements its own
  471. :meth:`~django.contrib.auth.models.AbstractBaseUser.get_session_auth_hash()`
  472. method, authenticated sessions will include the hash returned by this function.
  473. In the :class:`~django.contrib.auth.models.AbstractBaseUser` case, this is an
  474. HMAC of the password field. If the
  475. :class:`~django.contrib.auth.middleware.SessionAuthenticationMiddleware` is
  476. enabled, Django verifies that the hash sent along with each request matches
  477. the one that's computed server-side. This allows a user to log out all of their
  478. sessions by changing their password.
  479. The default password change views included with Django,
  480. :func:`django.contrib.auth.views.password_change` and the
  481. ``user_change_password`` view in the :mod:`django.contrib.auth` admin, update
  482. the session with the new password hash so that a user changing their own
  483. password won't log themselves out. If you have a custom password change view
  484. and wish to have similar behavior, use this function:
  485. .. function:: update_session_auth_hash(request, user)
  486. This function takes the current request and the updated user object from
  487. which the new session hash will be derived and updates the session hash
  488. appropriately. Example usage::
  489. from django.contrib.auth import update_session_auth_hash
  490. def password_change(request):
  491. if request.method == 'POST':
  492. form = PasswordChangeForm(user=request.user, data=request.POST)
  493. if form.is_valid():
  494. form.save()
  495. update_session_auth_hash(request, form.user)
  496. else:
  497. ...
  498. If you are upgrading an existing site and wish to enable this middleware without
  499. requiring all your users to re-login afterward, you should first upgrade to
  500. Django 1.7 and run it for a while so that as sessions are naturally recreated
  501. as users login, they include the session hash as described above. Once you
  502. start running your site with
  503. :class:`~django.contrib.auth.middleware.SessionAuthenticationMiddleware`, any
  504. users who have not logged in and had their session updated with the verification
  505. hash will have their existing session invalidated and be required to login.
  506. .. note::
  507. Since
  508. :meth:`~django.contrib.auth.models.AbstractBaseUser.get_session_auth_hash()`
  509. is based on :setting:`SECRET_KEY`, updating your site to use a new secret
  510. will invalidate all existing sessions.
  511. .. _built-in-auth-views:
  512. Authentication Views
  513. --------------------
  514. .. module:: django.contrib.auth.views
  515. Django provides several views that you can use for handling login, logout, and
  516. password management. These make use of the :ref:`stock auth forms
  517. <built-in-auth-forms>` but you can pass in your own forms as well.
  518. Django provides no default template for the authentication views. You should
  519. create your own templates for the views you want to use. The template context
  520. is documented in each view, see :ref:`all-authentication-views`.
  521. .. _using-the-views:
  522. Using the views
  523. ~~~~~~~~~~~~~~~
  524. There are different methods to implement these views in your project. The
  525. easiest way is to include the provided URLconf in ``django.contrib.auth.urls``
  526. in your own URLconf, for example::
  527. urlpatterns = [
  528. url('^', include('django.contrib.auth.urls'))
  529. ]
  530. This will include the following URL patterns::
  531. ^login/$ [name='login']
  532. ^logout/$ [name='logout']
  533. ^password_change/$ [name='password_change']
  534. ^password_change/done/$ [name='password_change_done']
  535. ^password_reset/$ [name='password_reset']
  536. ^password_reset/done/$ [name='password_reset_done']
  537. ^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']
  538. ^reset/done/$ [name='password_reset_complete']
  539. The views provide a URL name for easier reference. See :doc:`the URL
  540. documentation </topics/http/urls>` for details on using named URL patterns.
  541. If you want more control over your URLs, you can reference a specific view in
  542. your URLconf::
  543. urlpatterns = [
  544. url('^change-password/', 'django.contrib.auth.views.password_change')
  545. ]
  546. The views have optional arguments you can use to alter the behavior of the
  547. view. For example, if you want to change the template name a view uses, you can
  548. provide the ``template_name`` argument. A way to do this is to provide keyword
  549. arguments in the URLconf, these will be passed on to the view. For example::
  550. urlpatterns = [
  551. url(
  552. '^change-password/',
  553. 'django.contrib.auth.views.password_change',
  554. {'template_name': 'change-password.html'}
  555. )
  556. ]
  557. All views return a :class:`~django.template.response.TemplateResponse`
  558. instance, which allows you to easily customize the response data before
  559. rendering. A way to do this is to wrap a view in your own view::
  560. from django.contrib.auth import views
  561. def change_password(request):
  562. template_response = views.password_change(request)
  563. # Do something with `template_response`
  564. return template_response
  565. For more details, see the :doc:`TemplateResponse documentation
  566. </ref/template-response>`.
  567. .. _all-authentication-views:
  568. All authentication views
  569. ~~~~~~~~~~~~~~~~~~~~~~~~
  570. This is a list with all the views ``django.contrib.auth`` provides. For
  571. implementation details see :ref:`using-the-views`.
  572. .. function:: login(request, [template_name, redirect_field_name, authentication_form, current_app, extra_context])
  573. **URL name:** ``login``
  574. See :doc:`the URL documentation </topics/http/urls>` for details on using
  575. named URL patterns.
  576. **Optional arguments:**
  577. * ``template_name``: The name of a template to display for the view used to
  578. log the user in. Defaults to :file:`registration/login.html`.
  579. * ``redirect_field_name``: The name of a ``GET`` field containing the
  580. URL to redirect to after login. Defaults to ``next``.
  581. * ``authentication_form``: A callable (typically just a form class) to
  582. use for authentication. Defaults to
  583. :class:`~django.contrib.auth.forms.AuthenticationForm`.
  584. * ``current_app``: A hint indicating which application contains the current
  585. view. See the :ref:`namespaced URL resolution strategy
  586. <topics-http-reversing-url-namespaces>` for more information.
  587. * ``extra_context``: A dictionary of context data that will be added to the
  588. default context data passed to the template.
  589. Here's what ``django.contrib.auth.views.login`` does:
  590. * If called via ``GET``, it displays a login form that POSTs to the
  591. same URL. More on this in a bit.
  592. * If called via ``POST`` with user submitted credentials, it tries to log
  593. the user in. If login is successful, the view redirects to the URL
  594. specified in ``next``. If ``next`` isn't provided, it redirects to
  595. :setting:`settings.LOGIN_REDIRECT_URL <LOGIN_REDIRECT_URL>` (which
  596. defaults to ``/accounts/profile/``). If login isn't successful, it
  597. redisplays the login form.
  598. It's your responsibility to provide the html for the login template
  599. , called ``registration/login.html`` by default. This template gets passed
  600. four template context variables:
  601. * ``form``: A :class:`~django.forms.Form` object representing the
  602. :class:`~django.contrib.auth.forms.AuthenticationForm`.
  603. * ``next``: The URL to redirect to after successful login. This may
  604. contain a query string, too.
  605. * ``site``: The current :class:`~django.contrib.sites.models.Site`,
  606. according to the :setting:`SITE_ID` setting. If you don't have the
  607. site framework installed, this will be set to an instance of
  608. :class:`~django.contrib.sites.requests.RequestSite`, which derives the
  609. site name and domain from the current
  610. :class:`~django.http.HttpRequest`.
  611. * ``site_name``: An alias for ``site.name``. If you don't have the site
  612. framework installed, this will be set to the value of
  613. :attr:`request.META['SERVER_NAME'] <django.http.HttpRequest.META>`.
  614. For more on sites, see :doc:`/ref/contrib/sites`.
  615. If you'd prefer not to call the template :file:`registration/login.html`,
  616. you can pass the ``template_name`` parameter via the extra arguments to
  617. the view in your URLconf. For example, this URLconf line would use
  618. :file:`myapp/login.html` instead::
  619. url(r'^accounts/login/$', auth_views.login, {'template_name': 'myapp/login.html'}),
  620. You can also specify the name of the ``GET`` field which contains the URL
  621. to redirect to after login by passing ``redirect_field_name`` to the view.
  622. By default, the field is called ``next``.
  623. Here's a sample :file:`registration/login.html` template you can use as a
  624. starting point. It assumes you have a :file:`base.html` template that
  625. defines a ``content`` block:
  626. .. code-block:: html+django
  627. {% extends "base.html" %}
  628. {% block content %}
  629. {% if form.errors %}
  630. <p>Your username and password didn't match. Please try again.</p>
  631. {% endif %}
  632. {% if next %}
  633. {% if user.is_authenticated %}
  634. <p>Your account doesn't have access to this page. To proceed,
  635. please login with an account that has access.</p>
  636. {% else %}
  637. <p>Please login to see this page.</p>
  638. {% endif %}
  639. {% endif %}
  640. <form method="post" action="{% url 'django.contrib.auth.views.login' %}">
  641. {% csrf_token %}
  642. <table>
  643. <tr>
  644. <td>{{ form.username.label_tag }}</td>
  645. <td>{{ form.username }}</td>
  646. </tr>
  647. <tr>
  648. <td>{{ form.password.label_tag }}</td>
  649. <td>{{ form.password }}</td>
  650. </tr>
  651. </table>
  652. <input type="submit" value="login" />
  653. <input type="hidden" name="next" value="{{ next }}" />
  654. </form>
  655. {# Assumes you setup the password_reset view in your URLconf #}
  656. <p><a href="{% url 'password_reset' %}">Lost password?</a></p>
  657. {% endblock %}
  658. If you have customized authentication (see
  659. :doc:`Customizing Authentication </topics/auth/customizing>`) you can pass a custom authentication form
  660. to the login view via the ``authentication_form`` parameter. This form must
  661. accept a ``request`` keyword argument in its ``__init__`` method, and
  662. provide a ``get_user`` method which returns the authenticated user object
  663. (this method is only ever called after successful form validation).
  664. .. _forms documentation: ../forms/
  665. .. _site framework docs: ../sites/
  666. .. function:: logout(request, [next_page, template_name, redirect_field_name, current_app, extra_context])
  667. Logs a user out.
  668. **URL name:** ``logout``
  669. **Optional arguments:**
  670. * ``next_page``: The URL to redirect to after logout.
  671. * ``template_name``: The full name of a template to display after
  672. logging the user out. Defaults to
  673. :file:`registration/logged_out.html` if no argument is supplied.
  674. * ``redirect_field_name``: The name of a ``GET`` field containing the
  675. URL to redirect to after log out. Defaults to ``next``. Overrides the
  676. ``next_page`` URL if the given ``GET`` parameter is passed.
  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. **Template context:**
  683. * ``title``: The string "Logged out", localized.
  684. * ``site``: The current :class:`~django.contrib.sites.models.Site`,
  685. according to the :setting:`SITE_ID` setting. If you don't have the
  686. site framework installed, this will be set to an instance of
  687. :class:`~django.contrib.sites.requests.RequestSite`, which derives the
  688. site name and domain from the current
  689. :class:`~django.http.HttpRequest`.
  690. * ``site_name``: An alias for ``site.name``. If you don't have the site
  691. framework installed, this will be set to the value of
  692. :attr:`request.META['SERVER_NAME'] <django.http.HttpRequest.META>`.
  693. For more on sites, see :doc:`/ref/contrib/sites`.
  694. * ``current_app``: A hint indicating which application contains the current
  695. view. See the :ref:`namespaced URL resolution strategy
  696. <topics-http-reversing-url-namespaces>` for more information.
  697. * ``extra_context``: A dictionary of context data that will be added to the
  698. default context data passed to the template.
  699. .. function:: logout_then_login(request[, login_url, current_app, extra_context])
  700. Logs a user out, then redirects to the login page.
  701. **URL name:** No default URL provided
  702. **Optional arguments:**
  703. * ``login_url``: The URL of the login page to redirect to.
  704. Defaults to :setting:`settings.LOGIN_URL <LOGIN_URL>` if not supplied.
  705. * ``current_app``: A hint indicating which application contains the current
  706. view. See the :ref:`namespaced URL resolution strategy
  707. <topics-http-reversing-url-namespaces>` for more information.
  708. * ``extra_context``: A dictionary of context data that will be added to the
  709. default context data passed to the template.
  710. .. function:: password_change(request[, template_name, post_change_redirect, password_change_form, current_app, extra_context])
  711. Allows a user to change their password.
  712. **URL name:** ``password_change``
  713. **Optional arguments:**
  714. * ``template_name``: The full name of a template to use for
  715. displaying the password change form. Defaults to
  716. :file:`registration/password_change_form.html` if not supplied.
  717. * ``post_change_redirect``: The URL to redirect to after a successful
  718. password change.
  719. * ``password_change_form``: A custom "change password" form which must
  720. accept a ``user`` keyword argument. The form is responsible for
  721. actually changing the user's password. Defaults to
  722. :class:`~django.contrib.auth.forms.PasswordChangeForm`.
  723. * ``current_app``: A hint indicating which application contains the current
  724. view. See the :ref:`namespaced URL resolution strategy
  725. <topics-http-reversing-url-namespaces>` for more information.
  726. * ``extra_context``: A dictionary of context data that will be added to the
  727. default context data passed to the template.
  728. **Template context:**
  729. * ``form``: The password change form (see ``password_change_form`` above).
  730. .. function:: password_change_done(request[, template_name, current_app, extra_context])
  731. The page shown after a user has changed their password.
  732. **URL name:** ``password_change_done``
  733. **Optional arguments:**
  734. * ``template_name``: The full name of a template to use.
  735. Defaults to :file:`registration/password_change_done.html` if not
  736. supplied.
  737. * ``current_app``: A hint indicating which application contains the current
  738. view. See the :ref:`namespaced URL resolution strategy
  739. <topics-http-reversing-url-namespaces>` for more information.
  740. * ``extra_context``: A dictionary of context data that will be added to the
  741. default context data passed to the template.
  742. .. 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])
  743. Allows a user to reset their password by generating a one-time use link
  744. that can be used to reset the password, and sending that link to the
  745. user's registered email address.
  746. If the email address provided does not exist in the system, this view
  747. won't send an email, but the user won't receive any error message either.
  748. This prevents information leaking to potential attackers. If you want to
  749. provide an error message in this case, you can subclass
  750. :class:`~django.contrib.auth.forms.PasswordResetForm` and use the
  751. ``password_reset_form`` argument.
  752. Users flagged with an unusable password (see
  753. :meth:`~django.contrib.auth.models.User.set_unusable_password()` aren't
  754. allowed to request a password reset to prevent misuse when using an
  755. external authentication source like LDAP. Note that they won't receive any
  756. error message since this would expose their account's existence but no
  757. mail will be sent either.
  758. **URL name:** ``password_reset``
  759. **Optional arguments:**
  760. * ``template_name``: The full name of a template to use for
  761. displaying the password reset form. Defaults to
  762. :file:`registration/password_reset_form.html` if not supplied.
  763. * ``email_template_name``: The full name of a template to use for
  764. generating the email with the reset password link. Defaults to
  765. :file:`registration/password_reset_email.html` if not supplied.
  766. * ``subject_template_name``: The full name of a template to use for
  767. the subject of the email with the reset password link. Defaults
  768. to :file:`registration/password_reset_subject.txt` if not supplied.
  769. * ``password_reset_form``: Form that will be used to get the email of
  770. the user to reset the password for. Defaults to
  771. :class:`~django.contrib.auth.forms.PasswordResetForm`.
  772. * ``token_generator``: Instance of the class to check the one time link.
  773. This will default to ``default_token_generator``, it's an instance of
  774. ``django.contrib.auth.tokens.PasswordResetTokenGenerator``.
  775. * ``post_reset_redirect``: The URL to redirect to after a successful
  776. password reset request.
  777. * ``from_email``: A valid email address. By default Django uses
  778. the :setting:`DEFAULT_FROM_EMAIL`.
  779. * ``current_app``: A hint indicating which application contains the current
  780. view. See the :ref:`namespaced URL resolution strategy
  781. <topics-http-reversing-url-namespaces>` for more information.
  782. * ``extra_context``: A dictionary of context data that will be added to the
  783. default context data passed to the template.
  784. * ``html_email_template_name``: The full name of a template to use
  785. for generating a ``text/html`` multipart email with the password reset
  786. link. By default, HTML email is not sent.
  787. .. deprecated:: 1.8
  788. The ``is_admin_site`` argument is deprecated and will be removed in
  789. Django 2.0.
  790. **Template context:**
  791. * ``form``: The form (see ``password_reset_form`` above) for resetting
  792. the user's password.
  793. **Email template context:**
  794. * ``email``: An alias for ``user.email``
  795. * ``user``: The current :class:`~django.contrib.auth.models.User`,
  796. according to the ``email`` form field. Only active users are able to
  797. reset their passwords (``User.is_active is True``).
  798. * ``site_name``: An alias for ``site.name``. If you don't have the site
  799. framework installed, this will be set to the value of
  800. :attr:`request.META['SERVER_NAME'] <django.http.HttpRequest.META>`.
  801. For more on sites, see :doc:`/ref/contrib/sites`.
  802. * ``domain``: An alias for ``site.domain``. If you don't have the site
  803. framework installed, this will be set to the value of
  804. ``request.get_host()``.
  805. * ``protocol``: http or https
  806. * ``uid``: The user's primary key encoded in base 64.
  807. * ``token``: Token to check that the reset link is valid.
  808. Sample ``registration/password_reset_email.html`` (email body template):
  809. .. code-block:: html+django
  810. Someone asked for password reset for email {{ email }}. Follow the link below:
  811. {{ protocol}}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %}
  812. The same template context is used for subject template. Subject must be
  813. single line plain text string.
  814. .. function:: password_reset_done(request[, template_name, current_app, extra_context])
  815. The page shown after a user has been emailed a link to reset their
  816. password. This view is called by default if the :func:`password_reset` view
  817. doesn't have an explicit ``post_reset_redirect`` URL set.
  818. **URL name:** ``password_reset_done``
  819. .. note::
  820. If the email address provided does not exist in the system, the user is inactive, or has an unusable password,
  821. the user will still be redirected to this view but no email will be sent.
  822. **Optional arguments:**
  823. * ``template_name``: The full name of a template to use.
  824. Defaults to :file:`registration/password_reset_done.html` if not
  825. supplied.
  826. * ``current_app``: A hint indicating which application contains the current
  827. view. See the :ref:`namespaced URL resolution strategy
  828. <topics-http-reversing-url-namespaces>` for more information.
  829. * ``extra_context``: A dictionary of context data that will be added to the
  830. default context data passed to the template.
  831. .. function:: password_reset_confirm(request[, uidb64, token, template_name, token_generator, set_password_form, post_reset_redirect, current_app, extra_context])
  832. Presents a form for entering a new password.
  833. **URL name:** ``password_reset_confirm``
  834. **Optional arguments:**
  835. * ``uidb64``: The user's id encoded in base 64. Defaults to ``None``.
  836. * ``token``: Token to check that the password is valid. Defaults to
  837. ``None``.
  838. * ``template_name``: The full name of a template to display the confirm
  839. password view. Default value is :file:`registration/password_reset_confirm.html`.
  840. * ``token_generator``: Instance of the class to check the password. This
  841. will default to ``default_token_generator``, it's an instance of
  842. ``django.contrib.auth.tokens.PasswordResetTokenGenerator``.
  843. * ``set_password_form``: Form that will be used to set the password.
  844. Defaults to :class:`~django.contrib.auth.forms.SetPasswordForm`
  845. * ``post_reset_redirect``: URL to redirect after the password reset
  846. done. Defaults to ``None``.
  847. * ``current_app``: A hint indicating which application contains the current
  848. view. See the :ref:`namespaced URL resolution strategy
  849. <topics-http-reversing-url-namespaces>` for more information.
  850. * ``extra_context``: A dictionary of context data that will be added to the
  851. default context data passed to the template.
  852. **Template context:**
  853. * ``form``: The form (see ``set_password_form`` above) for setting the
  854. new user's password.
  855. * ``validlink``: Boolean, True if the link (combination of ``uidb64`` and
  856. ``token``) is valid or unused yet.
  857. .. function:: password_reset_complete(request[,template_name, current_app, extra_context])
  858. Presents a view which informs the user that the password has been
  859. successfully changed.
  860. **URL name:** ``password_reset_complete``
  861. **Optional arguments:**
  862. * ``template_name``: The full name of a template to display the view.
  863. Defaults to :file:`registration/password_reset_complete.html`.
  864. * ``current_app``: A hint indicating which application contains the current
  865. view. See the :ref:`namespaced URL resolution strategy
  866. <topics-http-reversing-url-namespaces>` for more information.
  867. * ``extra_context``: A dictionary of context data that will be added to the
  868. default context data passed to the template.
  869. Helper functions
  870. ----------------
  871. .. currentmodule:: django.contrib.auth.views
  872. .. function:: redirect_to_login(next[, login_url, redirect_field_name])
  873. Redirects to the login page, and then back to another URL after a
  874. successful login.
  875. **Required arguments:**
  876. * ``next``: The URL to redirect to after a successful login.
  877. **Optional arguments:**
  878. * ``login_url``: The URL of the login page to redirect to.
  879. Defaults to :setting:`settings.LOGIN_URL <LOGIN_URL>` if not supplied.
  880. * ``redirect_field_name``: The name of a ``GET`` field containing the
  881. URL to redirect to after log out. Overrides ``next`` if the given
  882. ``GET`` parameter is passed.
  883. .. _built-in-auth-forms:
  884. Built-in forms
  885. --------------
  886. .. module:: django.contrib.auth.forms
  887. If you don't want to use the built-in views, but want the convenience of not
  888. having to write forms for this functionality, the authentication system
  889. provides several built-in forms located in :mod:`django.contrib.auth.forms`:
  890. .. note::
  891. The built-in authentication forms make certain assumptions about the user
  892. model that they are working with. If you're using a :ref:`custom User model
  893. <auth-custom-user>`, it may be necessary to define your own forms for the
  894. authentication system. For more information, refer to the documentation
  895. about :ref:`using the built-in authentication forms with custom user models
  896. <custom-users-and-the-built-in-auth-forms>`.
  897. .. class:: AdminPasswordChangeForm
  898. A form used in the admin interface to change a user's password.
  899. Takes the ``user`` as the first positional argument.
  900. .. class:: AuthenticationForm
  901. A form for logging a user in.
  902. Takes ``request`` as its first positional argument, which is stored on the
  903. form instance for use by sub-classes.
  904. .. method:: confirm_login_allowed(user)
  905. By default, ``AuthenticationForm`` rejects users whose ``is_active`` flag
  906. is set to ``False``. You may override this behavior with a custom policy to
  907. determine which users can log in. Do this with a custom form that subclasses
  908. ``AuthenticationForm`` and overrides the ``confirm_login_allowed`` method.
  909. This method should raise a :exc:`~django.core.exceptions.ValidationError`
  910. if the given user may not log in.
  911. For example, to allow all users to log in, regardless of "active" status::
  912. from django.contrib.auth.forms import AuthenticationForm
  913. class AuthenticationFormWithInactiveUsersOkay(AuthenticationForm):
  914. def confirm_login_allowed(self, user):
  915. pass
  916. Or to allow only some active users to log in::
  917. class PickyAuthenticationForm(AuthenticationForm):
  918. def confirm_login_allowed(self, user):
  919. if not user.is_active:
  920. raise forms.ValidationError(
  921. _("This account is inactive."),
  922. code='inactive',
  923. )
  924. if user.username.startswith('b'):
  925. raise forms.ValidationError(
  926. _("Sorry, accounts starting with 'b' aren't welcome here."),
  927. code='no_b_users',
  928. )
  929. .. class:: PasswordChangeForm
  930. A form for allowing a user to change their password.
  931. .. class:: PasswordResetForm
  932. A form for generating and emailing a one-time use link to reset a
  933. user's password.
  934. .. method:: send_email(subject_template_name, email_template_name, context, from_email, to_email, [html_email_template_name=None])
  935. .. versionadded:: 1.8
  936. Uses the arguments to send an ``EmailMultiAlternatives``.
  937. Can be overridden to customize how the email is sent to the user.
  938. :param subject_template_name: the template for the subject.
  939. :param email_template_name: the template for the email body.
  940. :param context: context passed to the ``subject_template``, ``email_template``,
  941. and ``html_email_template`` (if it is not ``None``).
  942. :param from_email: the sender's email.
  943. :param to_email: the email of the requester.
  944. :param html_email_template_name: the template for the HTML body;
  945. defaults to ``None``, in which case a plain text email is sent.
  946. By default, ``save()`` populates the ``context`` with the
  947. same variables that :func:`~django.contrib.auth.views.password_reset`
  948. passes to its email context.
  949. .. class:: SetPasswordForm
  950. A form that lets a user change their password without entering the old
  951. password.
  952. .. class:: UserChangeForm
  953. A form used in the admin interface to change a user's information and
  954. permissions.
  955. .. class:: UserCreationForm
  956. A form for creating a new user.
  957. .. currentmodule:: django.contrib.auth
  958. Authentication data in templates
  959. --------------------------------
  960. The currently logged-in user and their permissions are made available in the
  961. :doc:`template context </ref/templates/api>` when you use
  962. :class:`~django.template.RequestContext`.
  963. .. admonition:: Technicality
  964. Technically, these variables are only made available in the template
  965. context if you use :class:`~django.template.RequestContext` and the
  966. ``'django.contrib.auth.context_processors.auth'`` context processor is
  967. enabled. It is in the default generated settings file. For more, see the
  968. :ref:`RequestContext docs <subclassing-context-requestcontext>`.
  969. Users
  970. ~~~~~
  971. When rendering a template :class:`~django.template.RequestContext`, the
  972. currently logged-in user, either a :class:`~django.contrib.auth.models.User`
  973. instance or an :class:`~django.contrib.auth.models.AnonymousUser` instance, is
  974. stored in the template variable ``{{ user }}``:
  975. .. code-block:: html+django
  976. {% if user.is_authenticated %}
  977. <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
  978. {% else %}
  979. <p>Welcome, new user. Please log in.</p>
  980. {% endif %}
  981. This template context variable is not available if a ``RequestContext`` is not
  982. being used.
  983. Permissions
  984. ~~~~~~~~~~~
  985. The currently logged-in user's permissions are stored in the template variable
  986. ``{{ perms }}``. This is an instance of
  987. ``django.contrib.auth.context_processors.PermWrapper``, which is a
  988. template-friendly proxy of permissions.
  989. In the ``{{ perms }}`` object, single-attribute lookup is a proxy to
  990. :meth:`User.has_module_perms <django.contrib.auth.models.User.has_module_perms>`.
  991. This example would display ``True`` if the logged-in user had any permissions
  992. in the ``foo`` app::
  993. {{ perms.foo }}
  994. Two-level-attribute lookup is a proxy to
  995. :meth:`User.has_perm <django.contrib.auth.models.User.has_perm>`. This example
  996. would display ``True`` if the logged-in user had the permission
  997. ``foo.can_vote``::
  998. {{ perms.foo.can_vote }}
  999. Thus, you can check permissions in template ``{% if %}`` statements:
  1000. .. code-block:: html+django
  1001. {% if perms.foo %}
  1002. <p>You have permission to do something in the foo app.</p>
  1003. {% if perms.foo.can_vote %}
  1004. <p>You can vote!</p>
  1005. {% endif %}
  1006. {% if perms.foo.can_drive %}
  1007. <p>You can drive!</p>
  1008. {% endif %}
  1009. {% else %}
  1010. <p>You don't have permission to do anything in the foo app.</p>
  1011. {% endif %}
  1012. It is possible to also look permissions up by ``{% if in %}`` statements.
  1013. For example:
  1014. .. code-block:: html+django
  1015. {% if 'foo' in perms %}
  1016. {% if 'foo.can_vote' in perms %}
  1017. <p>In lookup works, too.</p>
  1018. {% endif %}
  1019. {% endif %}
  1020. .. _auth-admin:
  1021. Managing users in the admin
  1022. ===========================
  1023. When you have both ``django.contrib.admin`` and ``django.contrib.auth``
  1024. installed, the admin provides a convenient way to view and manage users,
  1025. groups, and permissions. Users can be created and deleted like any Django
  1026. model. Groups can be created, and permissions can be assigned to users or
  1027. groups. A log of user edits to models made within the admin is also stored and
  1028. displayed.
  1029. Creating Users
  1030. --------------
  1031. You should see a link to "Users" in the "Auth"
  1032. section of the main admin index page. The "Add user" admin page is different
  1033. than standard admin pages in that it requires you to choose a username and
  1034. password before allowing you to edit the rest of the user's fields.
  1035. Also note: if you want a user account to be able to create users using the
  1036. Django admin site, you'll need to give them permission to add users *and*
  1037. change users (i.e., the "Add user" and "Change user" permissions). If an
  1038. account has permission to add users but not to change them, that account won't
  1039. be able to add users. Why? Because if you have permission to add users, you
  1040. have the power to create superusers, which can then, in turn, change other
  1041. users. So Django requires add *and* change permissions as a slight security
  1042. measure.
  1043. Be thoughtful about how you allow users to manage permissions. If you give a
  1044. non-superuser the ability to edit users, this is ultimately the same as giving
  1045. them superuser status because they will be able to elevate permissions of
  1046. users including themselves!
  1047. Changing Passwords
  1048. ------------------
  1049. User passwords are not displayed in the admin (nor stored in the database), but
  1050. the :doc:`password storage details </topics/auth/passwords>` are displayed.
  1051. Included in the display of this information is a link to
  1052. a password change form that allows admins to change user passwords.