default.txt 66 KB

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