default.txt 63 KB

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