default.txt 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686
  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. See
  82. :ref:`session-invalidation-on-password-change` for details.
  83. Authenticating Users
  84. --------------------
  85. .. function:: authenticate(\**credentials)
  86. To authenticate a given username and password, use
  87. :func:`~django.contrib.auth.authenticate()`. It takes credentials in the
  88. form of keyword arguments, for the default configuration this is
  89. ``username`` and ``password``, and it returns
  90. a :class:`~django.contrib.auth.models.User` object if the password is valid
  91. for the given username. If the password is invalid,
  92. :func:`~django.contrib.auth.authenticate()` returns ``None``. Example::
  93. from django.contrib.auth import authenticate
  94. user = authenticate(username='john', password='secret')
  95. if user is not None:
  96. # the password verified for the user
  97. if user.is_active:
  98. print("User is valid, active and authenticated")
  99. else:
  100. print("The password is valid, but the account has been disabled!")
  101. else:
  102. # the authentication system was unable to verify the username and password
  103. print("The username and password were incorrect.")
  104. .. note::
  105. This is a low level way to authenticate a set of credentials; for
  106. example, it's used by the
  107. :class:`~django.contrib.auth.middleware.RemoteUserMiddleware`. Unless
  108. you are writing your own authentication system, you probably won't use
  109. this. Rather if you are looking for a way to limit access to logged in
  110. users, see the :func:`~django.contrib.auth.decorators.login_required`
  111. decorator.
  112. .. _topic-authorization:
  113. Permissions and Authorization
  114. =============================
  115. Django comes with a simple permissions system. It provides a way to assign
  116. permissions to specific users and groups of users.
  117. It's used by the Django admin site, but you're welcome to use it in your own
  118. code.
  119. The Django admin site uses permissions as follows:
  120. * Access to view the "add" form and add an object is limited to users with
  121. the "add" permission for that type of object.
  122. * Access to view the change list, view the "change" form and change an
  123. object is limited to users with the "change" permission for that type of
  124. object.
  125. * Access to delete an object is limited to users with the "delete"
  126. permission for that type of object.
  127. Permissions can be set not only per type of object, but also per specific
  128. object instance. By using the
  129. :meth:`~django.contrib.admin.ModelAdmin.has_add_permission`,
  130. :meth:`~django.contrib.admin.ModelAdmin.has_change_permission` and
  131. :meth:`~django.contrib.admin.ModelAdmin.has_delete_permission` methods provided
  132. by the :class:`~django.contrib.admin.ModelAdmin` class, it is possible to
  133. customize permissions for different object instances of the same type.
  134. :class:`~django.contrib.auth.models.User` objects have two many-to-many
  135. fields: ``groups`` and ``user_permissions``.
  136. :class:`~django.contrib.auth.models.User` objects can access their related
  137. objects in the same way as any other :doc:`Django model
  138. </topics/db/models>`::
  139. myuser.groups.set([group_list])
  140. myuser.groups.add(group, group, ...)
  141. myuser.groups.remove(group, group, ...)
  142. myuser.groups.clear()
  143. myuser.user_permissions.set([permission_list])
  144. myuser.user_permissions.add(permission, permission, ...)
  145. myuser.user_permissions.remove(permission, permission, ...)
  146. myuser.user_permissions.clear()
  147. Default permissions
  148. -------------------
  149. When ``django.contrib.auth`` is listed in your :setting:`INSTALLED_APPS`
  150. setting, it will ensure that three default permissions -- add, change and
  151. delete -- are created for each Django model defined in one of your installed
  152. applications.
  153. These permissions will be created when you run :djadmin:`manage.py migrate
  154. <migrate>`; the first time you run ``migrate`` after adding
  155. ``django.contrib.auth`` to :setting:`INSTALLED_APPS`, the default permissions
  156. will be created for all previously-installed models, as well as for any new
  157. models being installed at that time. Afterward, it will create default
  158. permissions for new models each time you run :djadmin:`manage.py migrate
  159. <migrate>` (the function that creates permissions is connected to the
  160. :data:`~django.db.models.signals.post_migrate` signal).
  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(request, user)
  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(request)
  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='next', 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='next')
  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. .. method:: test_func()
  451. You have to override the ``test_func()`` method of the class to
  452. provide the test that is performed. Furthermore, you can set any of the
  453. parameters of :class:`~django.contrib.auth.mixins.AccessMixin` to
  454. customize the handling of unauthorized users::
  455. from django.contrib.auth.mixins import UserPassesTestMixin
  456. class MyView(UserPassesTestMixin, View):
  457. def test_func(self):
  458. return self.request.user.email.endswith('@example.com')
  459. .. method:: get_test_func()
  460. You can also override the ``get_test_func()`` method to have the mixin
  461. use a differently named function for its checks (instead of
  462. :meth:`test_func`).
  463. .. admonition:: Stacking ``UserPassesTestMixin``
  464. Due to the way ``UserPassesTestMixin`` is implemented, you cannot stack
  465. them in your inheritance list. The following does NOT work::
  466. class TestMixin1(UserPassesTestMixin):
  467. def test_func(self):
  468. return self.request.user.email.endswith('@example.com')
  469. class TestMixin2(UserPassesTestMixin):
  470. def test_func(self):
  471. return self.request.user.username.startswith('django')
  472. class MyView(TestMixin1, TestMixin2, View):
  473. ...
  474. If ``TestMixin1`` would call ``super()`` and take that result into
  475. account, ``TestMixin1`` wouldn't work standalone anymore.
  476. .. currentmodule:: django.contrib.auth.decorators
  477. The ``permission_required`` decorator
  478. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  479. .. function:: permission_required(perm, login_url=None, raise_exception=False)
  480. It's a relatively common task to check whether a user has a particular
  481. permission. For that reason, Django provides a shortcut for that case: the
  482. :func:`~django.contrib.auth.decorators.permission_required()` decorator.::
  483. from django.contrib.auth.decorators import permission_required
  484. @permission_required('polls.can_vote')
  485. def my_view(request):
  486. ...
  487. Just like the :meth:`~django.contrib.auth.models.User.has_perm` method,
  488. permission names take the form ``"<app label>.<permission codename>"``
  489. (i.e. ``polls.can_vote`` for a permission on a model in the ``polls``
  490. application).
  491. The decorator may also take an iterable of permissions, in which case the
  492. user must have all of the permissions in order to access the view.
  493. Note that :func:`~django.contrib.auth.decorators.permission_required()`
  494. also takes an optional ``login_url`` parameter::
  495. from django.contrib.auth.decorators import permission_required
  496. @permission_required('polls.can_vote', login_url='/loginpage/')
  497. def my_view(request):
  498. ...
  499. As in the :func:`~django.contrib.auth.decorators.login_required` decorator,
  500. ``login_url`` defaults to :setting:`settings.LOGIN_URL <LOGIN_URL>`.
  501. If the ``raise_exception`` parameter is given, the decorator will raise
  502. :exc:`~django.core.exceptions.PermissionDenied`, prompting :ref:`the 403
  503. (HTTP Forbidden) view<http_forbidden_view>` instead of redirecting to the
  504. login page.
  505. If you want to use ``raise_exception`` but also give your users a chance to
  506. login first, you can add the
  507. :func:`~django.contrib.auth.decorators.login_required` decorator::
  508. from django.contrib.auth.decorators import login_required, permission_required
  509. @permission_required('polls.can_vote', raise_exception=True)
  510. @login_required
  511. def my_view(request):
  512. ...
  513. .. versionchanged:: 1.9
  514. In older versions, the ``permission`` parameter only worked with
  515. strings, lists, and tuples instead of strings and any iterable.
  516. .. currentmodule:: django.contrib.auth.mixins
  517. The ``PermissionRequiredMixin`` mixin
  518. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  519. To apply permission checks to :doc:`class-based views
  520. </ref/class-based-views/index>`, you can use the ``PermissionRequiredMixin``:
  521. .. class:: PermissionRequiredMixin
  522. .. versionadded:: 1.9
  523. This mixin, just like the ``permission_required``
  524. decorator, checks whether the user accessing a view has all given
  525. permissions. You should specify the permission (or an iterable of
  526. permissions) using the ``permission_required`` parameter::
  527. from django.contrib.auth.mixins import PermissionRequiredMixin
  528. class MyView(PermissionRequiredMixin, View):
  529. permission_required = 'polls.can_vote'
  530. # Or multiple of permissions:
  531. permission_required = ('polls.can_open', 'polls.can_edit')
  532. You can set any of the parameters of
  533. :class:`~django.contrib.auth.mixins.AccessMixin` to customize the handling
  534. of unauthorized users.
  535. You may also override these methods:
  536. .. method:: get_permission_required()
  537. Returns an iterable of permission names used by the mixin. Defaults to
  538. the ``permission_required`` attribute, converted to a tuple if
  539. necessary.
  540. .. method:: has_permission()
  541. Returns a boolean denoting whether the current user has permission to
  542. execute the decorated view. By default, this returns the result of
  543. calling :meth:`~django.contrib.auth.models.User.has_perms()` with the
  544. list of permissions returned by :meth:`get_permission_required()`.
  545. Redirecting unauthorized requests in class-based views
  546. ------------------------------------------------------
  547. To ease the handling of access restrictions in :doc:`class-based views
  548. </ref/class-based-views/index>`, the ``AccessMixin`` can be used to redirect a
  549. user to the login page or issue an HTTP 403 Forbidden response.
  550. .. class:: AccessMixin
  551. .. versionadded:: 1.9
  552. .. attribute:: login_url
  553. Default return value for :meth:`get_login_url`. Defaults to ``None``
  554. in which case :meth:`get_login_url` falls back to
  555. :setting:`settings.LOGIN_URL <LOGIN_URL>`.
  556. .. attribute:: permission_denied_message
  557. Default return value for :meth:`get_permission_denied_message`.
  558. Defaults to an empty string.
  559. .. attribute:: redirect_field_name
  560. Default return value for :meth:`get_redirect_field_name`. Defaults to
  561. ``"next"``.
  562. .. attribute:: raise_exception
  563. If this attribute is set to ``True``, a
  564. :class:`~django.core.exceptions.PermissionDenied` exception will be
  565. raised instead of the redirect. Defaults to ``False``.
  566. .. method:: get_login_url()
  567. Returns the URL that users who don't pass the test will be redirected
  568. to. Returns :attr:`login_url` if set, or :setting:`settings.LOGIN_URL
  569. <LOGIN_URL>` otherwise.
  570. .. method:: get_permission_denied_message()
  571. When :attr:`raise_exception` is ``True``, this method can be used to
  572. control the error message passed to the error handler for display to
  573. the user. Returns the :attr:`permission_denied_message` attribute by
  574. default.
  575. .. method:: get_redirect_field_name()
  576. Returns the name of the query parameter that will contain the URL the
  577. user should be redirected to after a successful login. If you set this
  578. to ``None``, a query parameter won't be added. Returns the
  579. :attr:`redirect_field_name` attribute by default.
  580. .. method:: handle_no_permission()
  581. Depending on the value of ``raise_exception``, the method either raises
  582. a :exc:`~django.core.exceptions.PermissionDenied` exception or
  583. redirects the user to the ``login_url``, optionally including the
  584. ``redirect_field_name`` if it is set.
  585. .. _session-invalidation-on-password-change:
  586. Session invalidation on password change
  587. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  588. .. versionchanged:: 1.10
  589. Session verification is enabled and mandatory in Django 1.10 (there's no
  590. way to disable it) regardless of whether or not
  591. ``SessionAuthenticationMiddleware`` is enabled. In older
  592. versions, this protection only applies if
  593. ``django.contrib.auth.middleware.SessionAuthenticationMiddleware``
  594. is enabled in :setting:`MIDDLEWARE_CLASSES`.
  595. If your :setting:`AUTH_USER_MODEL` inherits from
  596. :class:`~django.contrib.auth.models.AbstractBaseUser` or implements its own
  597. :meth:`~django.contrib.auth.models.AbstractBaseUser.get_session_auth_hash()`
  598. method, authenticated sessions will include the hash returned by this function.
  599. In the :class:`~django.contrib.auth.models.AbstractBaseUser` case, this is an
  600. HMAC of the password field. Django verifies that the hash sent along with each
  601. request matches the one that's computed server-side. This allows a user to log
  602. out all of their sessions by changing their password.
  603. The default password change views included with Django,
  604. :func:`django.contrib.auth.views.password_change` and the
  605. ``user_change_password`` view in the :mod:`django.contrib.auth` admin, update
  606. the session with the new password hash so that a user changing their own
  607. password won't log themselves out. If you have a custom password change view
  608. and wish to have similar behavior, use this function:
  609. .. function:: update_session_auth_hash(request, user)
  610. This function takes the current request and the updated user object from
  611. which the new session hash will be derived and updates the session hash
  612. appropriately. Example usage::
  613. from django.contrib.auth import update_session_auth_hash
  614. def password_change(request):
  615. if request.method == 'POST':
  616. form = PasswordChangeForm(user=request.user, data=request.POST)
  617. if form.is_valid():
  618. form.save()
  619. update_session_auth_hash(request, form.user)
  620. else:
  621. ...
  622. .. note::
  623. Since
  624. :meth:`~django.contrib.auth.models.AbstractBaseUser.get_session_auth_hash()`
  625. is based on :setting:`SECRET_KEY`, updating your site to use a new secret
  626. will invalidate all existing sessions.
  627. .. _built-in-auth-views:
  628. Authentication Views
  629. --------------------
  630. .. module:: django.contrib.auth.views
  631. Django provides several views that you can use for handling login, logout, and
  632. password management. These make use of the :ref:`stock auth forms
  633. <built-in-auth-forms>` but you can pass in your own forms as well.
  634. Django provides no default template for the authentication views. You should
  635. create your own templates for the views you want to use. The template context
  636. is documented in each view, see :ref:`all-authentication-views`.
  637. .. _using-the-views:
  638. Using the views
  639. ~~~~~~~~~~~~~~~
  640. There are different methods to implement these views in your project. The
  641. easiest way is to include the provided URLconf in ``django.contrib.auth.urls``
  642. in your own URLconf, for example::
  643. urlpatterns = [
  644. url('^', include('django.contrib.auth.urls'))
  645. ]
  646. This will include the following URL patterns::
  647. ^login/$ [name='login']
  648. ^logout/$ [name='logout']
  649. ^password_change/$ [name='password_change']
  650. ^password_change/done/$ [name='password_change_done']
  651. ^password_reset/$ [name='password_reset']
  652. ^password_reset/done/$ [name='password_reset_done']
  653. ^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']
  654. ^reset/done/$ [name='password_reset_complete']
  655. The views provide a URL name for easier reference. See :doc:`the URL
  656. documentation </topics/http/urls>` for details on using named URL patterns.
  657. If you want more control over your URLs, you can reference a specific view in
  658. your URLconf::
  659. from django.contrib.auth import views as auth_views
  660. urlpatterns = [
  661. url('^change-password/', auth_views.password_change)
  662. ]
  663. The views have optional arguments you can use to alter the behavior of the
  664. view. For example, if you want to change the template name a view uses, you can
  665. provide the ``template_name`` argument. A way to do this is to provide keyword
  666. arguments in the URLconf, these will be passed on to the view. For example::
  667. urlpatterns = [
  668. url(
  669. '^change-password/',
  670. auth_views.password_change,
  671. {'template_name': 'change-password.html'}
  672. )
  673. ]
  674. All views return a :class:`~django.template.response.TemplateResponse`
  675. instance, which allows you to easily customize the response data before
  676. rendering. A way to do this is to wrap a view in your own view::
  677. from django.contrib.auth import views
  678. def change_password(request):
  679. template_response = views.password_change(request)
  680. # Do something with `template_response`
  681. return template_response
  682. For more details, see the :doc:`TemplateResponse documentation
  683. </ref/template-response>`.
  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=, authentication_form, current_app, extra_context)
  690. **URL name:** ``login``
  691. See :doc:`the URL documentation </topics/http/urls>` for details on using
  692. named URL patterns.
  693. **Optional arguments:**
  694. * ``template_name``: The name of a template to display for the view used to
  695. log the user in. Defaults to :file:`registration/login.html`.
  696. * ``redirect_field_name``: The name of a ``GET`` field containing the
  697. URL to redirect to after login. Defaults to ``next``.
  698. * ``authentication_form``: A callable (typically just a form class) to
  699. use for authentication. Defaults to
  700. :class:`~django.contrib.auth.forms.AuthenticationForm`.
  701. * ``current_app``: A hint indicating which application contains the current
  702. view. See the :ref:`namespaced URL resolution strategy
  703. <topics-http-reversing-url-namespaces>` for more information.
  704. * ``extra_context``: A dictionary of context data that will be added to the
  705. default context data passed to the template.
  706. .. deprecated:: 1.9
  707. The ``current_app`` parameter is deprecated and will be removed in
  708. Django 2.0. Callers should set ``request.current_app`` instead.
  709. Here's what ``django.contrib.auth.views.login`` does:
  710. * If called via ``GET``, it displays a login form that POSTs to the
  711. same URL. More on this in a bit.
  712. * If called via ``POST`` with user submitted credentials, it tries to log
  713. the user in. If login is successful, the view redirects to the URL
  714. specified in ``next``. If ``next`` isn't provided, it redirects to
  715. :setting:`settings.LOGIN_REDIRECT_URL <LOGIN_REDIRECT_URL>` (which
  716. defaults to ``/accounts/profile/``). If login isn't successful, it
  717. redisplays the login form.
  718. It's your responsibility to provide the html for the login template
  719. , called ``registration/login.html`` by default. This template gets passed
  720. four template context variables:
  721. * ``form``: A :class:`~django.forms.Form` object representing the
  722. :class:`~django.contrib.auth.forms.AuthenticationForm`.
  723. * ``next``: The URL to redirect to after successful login. This may
  724. contain a query string, too.
  725. * ``site``: The current :class:`~django.contrib.sites.models.Site`,
  726. according to the :setting:`SITE_ID` setting. If you don't have the
  727. site framework installed, this will be set to an instance of
  728. :class:`~django.contrib.sites.requests.RequestSite`, which derives the
  729. site name and domain from the current
  730. :class:`~django.http.HttpRequest`.
  731. * ``site_name``: An alias for ``site.name``. If you don't have the site
  732. framework installed, this will be set to the value of
  733. :attr:`request.META['SERVER_NAME'] <django.http.HttpRequest.META>`.
  734. For more on sites, see :doc:`/ref/contrib/sites`.
  735. If you'd prefer not to call the template :file:`registration/login.html`,
  736. you can pass the ``template_name`` parameter via the extra arguments to
  737. the view in your URLconf. For example, this URLconf line would use
  738. :file:`myapp/login.html` instead::
  739. url(r'^accounts/login/$', auth_views.login, {'template_name': 'myapp/login.html'}),
  740. You can also specify the name of the ``GET`` field which contains the URL
  741. to redirect to after login by passing ``redirect_field_name`` to the view.
  742. By default, the field is called ``next``.
  743. Here's a sample :file:`registration/login.html` template you can use as a
  744. starting point. It assumes you have a :file:`base.html` template that
  745. defines a ``content`` block:
  746. .. code-block:: html+django
  747. {% extends "base.html" %}
  748. {% block content %}
  749. {% if form.errors %}
  750. <p>Your username and password didn't match. Please try again.</p>
  751. {% endif %}
  752. {% if next %}
  753. {% if user.is_authenticated %}
  754. <p>Your account doesn't have access to this page. To proceed,
  755. please login with an account that has access.</p>
  756. {% else %}
  757. <p>Please login to see this page.</p>
  758. {% endif %}
  759. {% endif %}
  760. <form method="post" action="{% url 'django.contrib.auth.views.login' %}">
  761. {% csrf_token %}
  762. <table>
  763. <tr>
  764. <td>{{ form.username.label_tag }}</td>
  765. <td>{{ form.username }}</td>
  766. </tr>
  767. <tr>
  768. <td>{{ form.password.label_tag }}</td>
  769. <td>{{ form.password }}</td>
  770. </tr>
  771. </table>
  772. <input type="submit" value="login" />
  773. <input type="hidden" name="next" value="{{ next }}" />
  774. </form>
  775. {# Assumes you setup the password_reset view in your URLconf #}
  776. <p><a href="{% url 'password_reset' %}">Lost password?</a></p>
  777. {% endblock %}
  778. If you have customized authentication (see
  779. :doc:`Customizing Authentication </topics/auth/customizing>`) you can pass
  780. a custom authentication form to the login view via the
  781. ``authentication_form`` parameter. This form must accept a ``request``
  782. keyword argument in its ``__init__`` method, and provide a ``get_user()``
  783. method which returns the authenticated user object (this method is only
  784. ever called after successful form validation).
  785. .. _forms documentation: ../forms/
  786. .. _site framework docs: ../sites/
  787. .. function:: logout(request, next_page=None, template_name='registration/logged_out.html', redirect_field_name='next', current_app=None, extra_context=None)
  788. Logs a user out.
  789. **URL name:** ``logout``
  790. **Optional arguments:**
  791. * ``next_page``: The URL to redirect to after logout.
  792. * ``template_name``: The full name of a template to display after
  793. logging the user out. Defaults to
  794. :file:`registration/logged_out.html` if no argument is supplied.
  795. * ``redirect_field_name``: The name of a ``GET`` field containing the
  796. URL to redirect to after log out. Defaults to ``next``. Overrides the
  797. ``next_page`` URL if the given ``GET`` parameter is passed.
  798. * ``current_app``: A hint indicating which application contains the current
  799. view. See the :ref:`namespaced URL resolution strategy
  800. <topics-http-reversing-url-namespaces>` for more information.
  801. * ``extra_context``: A dictionary of context data that will be added to the
  802. default context data passed to the template.
  803. .. deprecated:: 1.9
  804. The ``current_app`` parameter is deprecated and will be removed in
  805. Django 2.0. Callers should set ``request.current_app`` instead.
  806. **Template context:**
  807. * ``title``: The string "Logged out", localized.
  808. * ``site``: The current :class:`~django.contrib.sites.models.Site`,
  809. according to the :setting:`SITE_ID` setting. If you don't have the
  810. site framework installed, this will be set to an instance of
  811. :class:`~django.contrib.sites.requests.RequestSite`, which derives the
  812. site name and domain from the current
  813. :class:`~django.http.HttpRequest`.
  814. * ``site_name``: An alias for ``site.name``. If you don't have the site
  815. framework installed, this will be set to the value of
  816. :attr:`request.META['SERVER_NAME'] <django.http.HttpRequest.META>`.
  817. For more on sites, see :doc:`/ref/contrib/sites`.
  818. * ``current_app``: A hint indicating which application contains the current
  819. view. See the :ref:`namespaced URL resolution strategy
  820. <topics-http-reversing-url-namespaces>` for more information.
  821. * ``extra_context``: A dictionary of context data that will be added to the
  822. default context data passed to the template.
  823. .. function:: logout_then_login(request, login_url=None, current_app=None, extra_context=None)
  824. Logs a user out, then redirects to the login page.
  825. **URL name:** No default URL provided
  826. **Optional arguments:**
  827. * ``login_url``: The URL of the login page to redirect to.
  828. Defaults to :setting:`settings.LOGIN_URL <LOGIN_URL>` if not supplied.
  829. * ``current_app``: A hint indicating which application contains the current
  830. view. See the :ref:`namespaced URL resolution strategy
  831. <topics-http-reversing-url-namespaces>` for more information.
  832. * ``extra_context``: A dictionary of context data that will be added to the
  833. default context data passed to the template.
  834. .. deprecated:: 1.9
  835. The ``current_app`` parameter is deprecated and will be removed in
  836. Django 2.0. Callers should set ``request.current_app`` instead.
  837. .. function:: password_change(request, template_name='registration/password_change_form.html', post_change_redirect=None, password_change_form=PasswordChangeForm, current_app=None, extra_context=None)
  838. Allows a user to change their password.
  839. **URL name:** ``password_change``
  840. **Optional arguments:**
  841. * ``template_name``: The full name of a template to use for
  842. displaying the password change form. Defaults to
  843. :file:`registration/password_change_form.html` if not supplied.
  844. * ``post_change_redirect``: The URL to redirect to after a successful
  845. password change.
  846. * ``password_change_form``: A custom "change password" form which must
  847. accept a ``user`` keyword argument. The form is responsible for
  848. actually changing the user's password. Defaults to
  849. :class:`~django.contrib.auth.forms.PasswordChangeForm`.
  850. * ``current_app``: A hint indicating which application contains the current
  851. view. See the :ref:`namespaced URL resolution strategy
  852. <topics-http-reversing-url-namespaces>` for more information.
  853. * ``extra_context``: A dictionary of context data that will be added to the
  854. default context data passed to the template.
  855. .. deprecated:: 1.9
  856. The ``current_app`` parameter is deprecated and will be removed in
  857. Django 2.0. Callers should set ``request.current_app`` instead.
  858. **Template context:**
  859. * ``form``: The password change form (see ``password_change_form`` above).
  860. .. function:: password_change_done(request, template_name='registration/password_change_done.html', current_app=None, extra_context=None)
  861. The page shown after a user has changed their password.
  862. **URL name:** ``password_change_done``
  863. **Optional arguments:**
  864. * ``template_name``: The full name of a template to use.
  865. Defaults to :file:`registration/password_change_done.html` if not
  866. supplied.
  867. * ``current_app``: A hint indicating which application contains the current
  868. view. See the :ref:`namespaced URL resolution strategy
  869. <topics-http-reversing-url-namespaces>` for more information.
  870. * ``extra_context``: A dictionary of context data that will be added to the
  871. default context data passed to the template.
  872. .. deprecated:: 1.9
  873. The ``current_app`` parameter is deprecated and will be removed in
  874. Django 2.0. Callers should set ``request.current_app`` instead.
  875. .. 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, current_app=None, extra_context=None, html_email_template_name=None, extra_email_context=None)
  876. Allows a user to reset their password by generating a one-time use link
  877. that can be used to reset the password, and sending that link to the
  878. user's registered email address.
  879. If the email address provided does not exist in the system, this view
  880. won't send an email, but the user won't receive any error message either.
  881. This prevents information leaking to potential attackers. If you want to
  882. provide an error message in this case, you can subclass
  883. :class:`~django.contrib.auth.forms.PasswordResetForm` and use the
  884. ``password_reset_form`` argument.
  885. Users flagged with an unusable password (see
  886. :meth:`~django.contrib.auth.models.User.set_unusable_password()` aren't
  887. allowed to request a password reset to prevent misuse when using an
  888. external authentication source like LDAP. Note that they won't receive any
  889. error message since this would expose their account's existence but no
  890. mail will be sent either.
  891. **URL name:** ``password_reset``
  892. **Optional arguments:**
  893. * ``template_name``: The full name of a template to use for
  894. displaying the password reset form. Defaults to
  895. :file:`registration/password_reset_form.html` if not supplied.
  896. * ``email_template_name``: The full name of a template to use for
  897. generating the email with the reset password link. Defaults to
  898. :file:`registration/password_reset_email.html` if not supplied.
  899. * ``subject_template_name``: The full name of a template to use for
  900. the subject of the email with the reset password link. Defaults
  901. to :file:`registration/password_reset_subject.txt` if not supplied.
  902. * ``password_reset_form``: Form that will be used to get the email of
  903. the user to reset the password for. Defaults to
  904. :class:`~django.contrib.auth.forms.PasswordResetForm`.
  905. * ``token_generator``: Instance of the class to check the one time link.
  906. This will default to ``default_token_generator``, it's an instance of
  907. ``django.contrib.auth.tokens.PasswordResetTokenGenerator``.
  908. * ``post_reset_redirect``: The URL to redirect to after a successful
  909. password reset request.
  910. * ``from_email``: A valid email address. By default Django uses
  911. the :setting:`DEFAULT_FROM_EMAIL`.
  912. * ``current_app``: A hint indicating which application contains the current
  913. view. See the :ref:`namespaced URL resolution strategy
  914. <topics-http-reversing-url-namespaces>` for more information.
  915. * ``extra_context``: A dictionary of context data that will be added to the
  916. default context data passed to the template.
  917. * ``html_email_template_name``: The full name of a template to use
  918. for generating a ``text/html`` multipart email with the password reset
  919. link. By default, HTML email is not sent.
  920. * ``extra_email_context``: A dictionary of context data that will available
  921. in the email template.
  922. .. deprecated:: 1.9
  923. The ``current_app`` parameter is deprecated and will be removed in
  924. Django 2.0. Callers should set ``request.current_app`` instead.
  925. .. versionadded:: 1.9
  926. The ``extra_email_context`` parameter was added.
  927. **Template context:**
  928. * ``form``: The form (see ``password_reset_form`` above) for resetting
  929. the user's password.
  930. **Email template context:**
  931. * ``email``: An alias for ``user.email``
  932. * ``user``: The current :class:`~django.contrib.auth.models.User`,
  933. according to the ``email`` form field. Only active users are able to
  934. reset their passwords (``User.is_active is True``).
  935. * ``site_name``: An alias for ``site.name``. If you don't have the site
  936. framework installed, this will be set to the value of
  937. :attr:`request.META['SERVER_NAME'] <django.http.HttpRequest.META>`.
  938. For more on sites, see :doc:`/ref/contrib/sites`.
  939. * ``domain``: An alias for ``site.domain``. If you don't have the site
  940. framework installed, this will be set to the value of
  941. ``request.get_host()``.
  942. * ``protocol``: http or https
  943. * ``uid``: The user's primary key encoded in base 64.
  944. * ``token``: Token to check that the reset link is valid.
  945. Sample ``registration/password_reset_email.html`` (email body template):
  946. .. code-block:: html+django
  947. Someone asked for password reset for email {{ email }}. Follow the link below:
  948. {{ protocol}}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %}
  949. The same template context is used for subject template. Subject must be
  950. single line plain text string.
  951. .. function:: password_reset_done(request, template_name='registration/password_reset_done.html', current_app=None, extra_context=None)
  952. The page shown after a user has been emailed a link to reset their
  953. password. This view is called by default if the :func:`password_reset` view
  954. doesn't have an explicit ``post_reset_redirect`` URL set.
  955. **URL name:** ``password_reset_done``
  956. .. note::
  957. If the email address provided does not exist in the system, the user is
  958. inactive, or has an unusable password, the user will still be
  959. redirected to this view but no email will be sent.
  960. **Optional arguments:**
  961. * ``template_name``: The full name of a template to use.
  962. Defaults to :file:`registration/password_reset_done.html` if not
  963. supplied.
  964. * ``current_app``: A hint indicating which application contains the current
  965. view. See the :ref:`namespaced URL resolution strategy
  966. <topics-http-reversing-url-namespaces>` for more information.
  967. * ``extra_context``: A dictionary of context data that will be added to the
  968. default context data passed to the template.
  969. .. deprecated:: 1.9
  970. The ``current_app`` parameter is deprecated and will be removed in
  971. Django 2.0. Callers should set ``request.current_app`` instead.
  972. .. 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, current_app=None, extra_context=None)
  973. Presents a form for entering a new password.
  974. **URL name:** ``password_reset_confirm``
  975. **Optional arguments:**
  976. * ``uidb64``: The user's id encoded in base 64. Defaults to ``None``.
  977. * ``token``: Token to check that the password is valid. Defaults to
  978. ``None``.
  979. * ``template_name``: The full name of a template to display the confirm
  980. password view. Default value is :file:`registration/password_reset_confirm.html`.
  981. * ``token_generator``: Instance of the class to check the password. This
  982. will default to ``default_token_generator``, it's an instance of
  983. ``django.contrib.auth.tokens.PasswordResetTokenGenerator``.
  984. * ``set_password_form``: Form that will be used to set the password.
  985. Defaults to :class:`~django.contrib.auth.forms.SetPasswordForm`
  986. * ``post_reset_redirect``: URL to redirect after the password reset
  987. done. Defaults to ``None``.
  988. * ``current_app``: A hint indicating which application contains the current
  989. view. See the :ref:`namespaced URL resolution strategy
  990. <topics-http-reversing-url-namespaces>` for more information.
  991. * ``extra_context``: A dictionary of context data that will be added to the
  992. default context data passed to the template.
  993. **Template context:**
  994. * ``form``: The form (see ``set_password_form`` above) for setting the
  995. new user's password.
  996. * ``validlink``: Boolean, True if the link (combination of ``uidb64`` and
  997. ``token``) is valid or unused yet.
  998. .. deprecated:: 1.9
  999. The ``current_app`` parameter is deprecated and will be removed in
  1000. Django 2.0. Callers should set ``request.current_app`` instead.
  1001. .. function:: password_reset_complete(request, template_name='registration/password_reset_complete.html', current_app=None, extra_context=None)
  1002. Presents a view which informs the user that the password has been
  1003. successfully changed.
  1004. **URL name:** ``password_reset_complete``
  1005. **Optional arguments:**
  1006. * ``template_name``: The full name of a template to display the view.
  1007. Defaults to :file:`registration/password_reset_complete.html`.
  1008. * ``current_app``: A hint indicating which application contains the current
  1009. view. See the :ref:`namespaced URL resolution strategy
  1010. <topics-http-reversing-url-namespaces>` for more information.
  1011. * ``extra_context``: A dictionary of context data that will be added to the
  1012. default context data passed to the template.
  1013. .. deprecated:: 1.9
  1014. The ``current_app`` parameter is deprecated and will be removed in
  1015. Django 2.0. Callers should set ``request.current_app`` instead.
  1016. Helper functions
  1017. ----------------
  1018. .. currentmodule:: django.contrib.auth.views
  1019. .. function:: redirect_to_login(next, login_url=None, redirect_field_name='next')
  1020. Redirects to the login page, and then back to another URL after a
  1021. successful login.
  1022. **Required arguments:**
  1023. * ``next``: The URL to redirect to after a successful login.
  1024. **Optional arguments:**
  1025. * ``login_url``: The URL of the login page to redirect to.
  1026. Defaults to :setting:`settings.LOGIN_URL <LOGIN_URL>` if not supplied.
  1027. * ``redirect_field_name``: The name of a ``GET`` field containing the
  1028. URL to redirect to after log out. Overrides ``next`` if the given
  1029. ``GET`` parameter is passed.
  1030. .. _built-in-auth-forms:
  1031. Built-in forms
  1032. --------------
  1033. .. module:: django.contrib.auth.forms
  1034. If you don't want to use the built-in views, but want the convenience of not
  1035. having to write forms for this functionality, the authentication system
  1036. provides several built-in forms located in :mod:`django.contrib.auth.forms`:
  1037. .. note::
  1038. The built-in authentication forms make certain assumptions about the user
  1039. model that they are working with. If you're using a :ref:`custom User model
  1040. <auth-custom-user>`, it may be necessary to define your own forms for the
  1041. authentication system. For more information, refer to the documentation
  1042. about :ref:`using the built-in authentication forms with custom user models
  1043. <custom-users-and-the-built-in-auth-forms>`.
  1044. .. class:: AdminPasswordChangeForm
  1045. A form used in the admin interface to change a user's password.
  1046. Takes the ``user`` as the first positional argument.
  1047. .. class:: AuthenticationForm
  1048. A form for logging a user in.
  1049. Takes ``request`` as its first positional argument, which is stored on the
  1050. form instance for use by sub-classes.
  1051. .. method:: confirm_login_allowed(user)
  1052. By default, ``AuthenticationForm`` rejects users whose ``is_active``
  1053. flag is set to ``False``. You may override this behavior with a custom
  1054. policy to determine which users can log in. Do this with a custom form
  1055. that subclasses ``AuthenticationForm`` and overrides the
  1056. ``confirm_login_allowed()`` method. This method should raise a
  1057. :exc:`~django.core.exceptions.ValidationError` if the given user may
  1058. not log in.
  1059. For example, to allow all users to log in regardless of "active"
  1060. status::
  1061. from django.contrib.auth.forms import AuthenticationForm
  1062. class AuthenticationFormWithInactiveUsersOkay(AuthenticationForm):
  1063. def confirm_login_allowed(self, user):
  1064. pass
  1065. Or to allow only some active users to log in::
  1066. class PickyAuthenticationForm(AuthenticationForm):
  1067. def confirm_login_allowed(self, user):
  1068. if not user.is_active:
  1069. raise forms.ValidationError(
  1070. _("This account is inactive."),
  1071. code='inactive',
  1072. )
  1073. if user.username.startswith('b'):
  1074. raise forms.ValidationError(
  1075. _("Sorry, accounts starting with 'b' aren't welcome here."),
  1076. code='no_b_users',
  1077. )
  1078. .. class:: PasswordChangeForm
  1079. A form for allowing a user to change their password.
  1080. .. class:: PasswordResetForm
  1081. A form for generating and emailing a one-time use link to reset a
  1082. user's password.
  1083. .. method:: send_email(subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None)
  1084. Uses the arguments to send an ``EmailMultiAlternatives``.
  1085. Can be overridden to customize how the email is sent to the user.
  1086. :param subject_template_name: the template for the subject.
  1087. :param email_template_name: the template for the email body.
  1088. :param context: context passed to the ``subject_template``,
  1089. ``email_template``, and ``html_email_template`` (if it is not
  1090. ``None``).
  1091. :param from_email: the sender's email.
  1092. :param to_email: the email of the requester.
  1093. :param html_email_template_name: the template for the HTML body;
  1094. defaults to ``None``, in which case a plain text email is sent.
  1095. By default, ``save()`` populates the ``context`` with the
  1096. same variables that :func:`~django.contrib.auth.views.password_reset`
  1097. passes to its email context.
  1098. .. class:: SetPasswordForm
  1099. A form that lets a user change their password without entering the old
  1100. password.
  1101. .. class:: UserChangeForm
  1102. A form used in the admin interface to change a user's information and
  1103. permissions.
  1104. .. class:: UserCreationForm
  1105. A form for creating a new user.
  1106. .. currentmodule:: django.contrib.auth
  1107. Authentication data in templates
  1108. --------------------------------
  1109. The currently logged-in user and their permissions are made available in the
  1110. :doc:`template context </ref/templates/api>` when you use
  1111. :class:`~django.template.RequestContext`.
  1112. .. admonition:: Technicality
  1113. Technically, these variables are only made available in the template
  1114. context if you use :class:`~django.template.RequestContext` and the
  1115. ``'django.contrib.auth.context_processors.auth'`` context processor is
  1116. enabled. It is in the default generated settings file. For more, see the
  1117. :ref:`RequestContext docs <subclassing-context-requestcontext>`.
  1118. Users
  1119. ~~~~~
  1120. When rendering a template :class:`~django.template.RequestContext`, the
  1121. currently logged-in user, either a :class:`~django.contrib.auth.models.User`
  1122. instance or an :class:`~django.contrib.auth.models.AnonymousUser` instance, is
  1123. stored in the template variable ``{{ user }}``:
  1124. .. code-block:: html+django
  1125. {% if user.is_authenticated %}
  1126. <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
  1127. {% else %}
  1128. <p>Welcome, new user. Please log in.</p>
  1129. {% endif %}
  1130. This template context variable is not available if a ``RequestContext`` is not
  1131. being used.
  1132. Permissions
  1133. ~~~~~~~~~~~
  1134. The currently logged-in user's permissions are stored in the template variable
  1135. ``{{ perms }}``. This is an instance of
  1136. ``django.contrib.auth.context_processors.PermWrapper``, which is a
  1137. template-friendly proxy of permissions.
  1138. In the ``{{ perms }}`` object, single-attribute lookup is a proxy to
  1139. :meth:`User.has_module_perms <django.contrib.auth.models.User.has_module_perms>`.
  1140. This example would display ``True`` if the logged-in user had any permissions
  1141. in the ``foo`` app::
  1142. {{ perms.foo }}
  1143. Two-level-attribute lookup is a proxy to
  1144. :meth:`User.has_perm <django.contrib.auth.models.User.has_perm>`. This example
  1145. would display ``True`` if the logged-in user had the permission
  1146. ``foo.can_vote``::
  1147. {{ perms.foo.can_vote }}
  1148. Thus, you can check permissions in template ``{% if %}`` statements:
  1149. .. code-block:: html+django
  1150. {% if perms.foo %}
  1151. <p>You have permission to do something in the foo app.</p>
  1152. {% if perms.foo.can_vote %}
  1153. <p>You can vote!</p>
  1154. {% endif %}
  1155. {% if perms.foo.can_drive %}
  1156. <p>You can drive!</p>
  1157. {% endif %}
  1158. {% else %}
  1159. <p>You don't have permission to do anything in the foo app.</p>
  1160. {% endif %}
  1161. It is possible to also look permissions up by ``{% if in %}`` statements.
  1162. For example:
  1163. .. code-block:: html+django
  1164. {% if 'foo' in perms %}
  1165. {% if 'foo.can_vote' in perms %}
  1166. <p>In lookup works, too.</p>
  1167. {% endif %}
  1168. {% endif %}
  1169. .. _auth-admin:
  1170. Managing users in the admin
  1171. ===========================
  1172. When you have both ``django.contrib.admin`` and ``django.contrib.auth``
  1173. installed, the admin provides a convenient way to view and manage users,
  1174. groups, and permissions. Users can be created and deleted like any Django
  1175. model. Groups can be created, and permissions can be assigned to users or
  1176. groups. A log of user edits to models made within the admin is also stored and
  1177. displayed.
  1178. Creating Users
  1179. --------------
  1180. You should see a link to "Users" in the "Auth"
  1181. section of the main admin index page. The "Add user" admin page is different
  1182. than standard admin pages in that it requires you to choose a username and
  1183. password before allowing you to edit the rest of the user's fields.
  1184. Also note: if you want a user account to be able to create users using the
  1185. Django admin site, you'll need to give them permission to add users *and*
  1186. change users (i.e., the "Add user" and "Change user" permissions). If an
  1187. account has permission to add users but not to change them, that account won't
  1188. be able to add users. Why? Because if you have permission to add users, you
  1189. have the power to create superusers, which can then, in turn, change other
  1190. users. So Django requires add *and* change permissions as a slight security
  1191. measure.
  1192. Be thoughtful about how you allow users to manage permissions. If you give a
  1193. non-superuser the ability to edit users, this is ultimately the same as giving
  1194. them superuser status because they will be able to elevate permissions of
  1195. users including themselves!
  1196. Changing Passwords
  1197. ------------------
  1198. User passwords are not displayed in the admin (nor stored in the database), but
  1199. the :doc:`password storage details </topics/auth/passwords>` are displayed.
  1200. Included in the display of this information is a link to
  1201. a password change form that allows admins to change user passwords.