default.txt 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234
  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, and can handle many projects as
  9. is. For projects where authentication needs differ from the default, Django
  10. supports extensive :doc:`extension and customization
  11. </topics/auth/customizing>` of authentication.
  12. Django authentication provides both authentication and authorization, together
  13. and is generally referred to as the authentication system, as these features
  14. somewhat coupled.
  15. .. _user-objects:
  16. User objects
  17. ============
  18. :class:`~django.contrib.auth.models.User` objects are the core of the
  19. authentication system. They typically represent the people interacting with
  20. your site and are used to enable things like restricting access, registering
  21. user profiles, associating content with creators etc. Only one class of user
  22. exists in Django's authentication framework, i.e., 'superusers' or admin
  23. 'staff' users are just user objects with special attributes set, not different
  24. classes of user objects.
  25. The primary attributes of the default user are:
  26. * username
  27. * password
  28. * email
  29. * first name
  30. * 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. :djadmin:`manage.py syncdb <syncdb>` prompts you to create a superuser the
  51. first time you run it with ``'django.contrib.auth'`` in your
  52. :setting:`INSTALLED_APPS`. If you need to create a superuser at a later date,
  53. you can use a command line utility::
  54. manage.py createsuperuser --username=joe --email=joe@example.com
  55. You will be prompted for a password. After you enter one, the user will be
  56. created immediately. If you leave off the :djadminopt:`--username` or the
  57. :djadminopt:`--email` options, it will prompt you for those values.
  58. Changing passwords
  59. ------------------
  60. Django does not store raw (clear text) passwords on the user model, but only
  61. a hash (see :doc:`documentation of how passwords are managed
  62. </topics/auth/passwords>` for full details). Because of this, do not attempt to
  63. manipulate the password attribute of the user directly. This is why a helper
  64. function is used when creating a user.
  65. To change a user's password, you have several options:
  66. :djadmin:`manage.py changepassword *username* <changepassword>` offers a method
  67. of changing a User's password from the command line. It prompts you to
  68. change the password of a given user which you must enter twice. If
  69. they both match, the new password will be changed immediately. If you
  70. do not supply a user, the command will attempt to change the password
  71. whose username matches the current system user.
  72. You can also change a password programmatically, using
  73. :meth:`~django.contrib.auth.models.User.set_password()`:
  74. .. code-block:: python
  75. >>> from django.contrib.auth.models import User
  76. >>> u = User.objects.get(username__exact='john')
  77. >>> u.set_password('new password')
  78. >>> u.save()
  79. If you have the Django admin installed, you can also change user's passwords
  80. on the :ref:`authentication system's admin pages <auth-admin>`.
  81. Django also provides :ref:`views <built-in-auth-views>` and :ref:`forms
  82. <built-in-auth-forms>` that may be used to allow users to change their own
  83. passwords.
  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. .. _topic-authorization:
  106. Permissions and Authorization
  107. =============================
  108. Django comes with a simple permissions system. It provides a way to assign
  109. permissions to specific users and groups of users.
  110. It's used by the Django admin site, but you're welcome to use it in your own
  111. code.
  112. The Django admin site uses permissions as follows:
  113. * Access to view the "add" form and add an object is limited to users with
  114. the "add" permission for that type of object.
  115. * Access to view the change list, view the "change" form and change an
  116. object is limited to users with the "change" permission for that type of
  117. object.
  118. * Access to delete an object is limited to users with the "delete"
  119. permission for that type of object.
  120. Permissions can be set not only per type of object, but also per specific
  121. object instance. By using the
  122. :meth:`~django.contrib.admin.ModelAdmin.has_add_permission`,
  123. :meth:`~django.contrib.admin.ModelAdmin.has_change_permission` and
  124. :meth:`~django.contrib.admin.ModelAdmin.has_delete_permission` methods provided
  125. by the :class:`~django.contrib.admin.ModelAdmin` class, it is possible to
  126. customize permissions for different object instances of the same type.
  127. :class:`~django.contrib.auth.models.User` objects have two many-to-many
  128. fields: ``groups`` and ``user_permissions``.
  129. :class:`~django.contrib.auth.models.User` objects can access their related
  130. objects in the same way as any other :doc:`Django model
  131. </topics/db/models>`:
  132. .. code-block:: python
  133. myuser.groups = [group_list]
  134. myuser.groups.add(group, group, ...)
  135. myuser.groups.remove(group, group, ...)
  136. myuser.groups.clear()
  137. myuser.user_permissions = [permission_list]
  138. myuser.user_permissions.add(permission, permission, ...)
  139. myuser.user_permissions.remove(permission, permission, ...)
  140. myuser.user_permissions.clear()
  141. Default permissions
  142. -------------------
  143. When ``django.contrib.auth`` is listed in your :setting:`INSTALLED_APPS`
  144. setting, it will ensure that three default permissions -- add, change and
  145. delete -- are created for each Django model defined in one of your installed
  146. applications.
  147. These permissions will be created when you run :djadmin:`manage.py syncdb
  148. <syncdb>`; the first time you run ``syncdb`` after adding
  149. ``django.contrib.auth`` to :setting:`INSTALLED_APPS`, the default permissions
  150. will be created for all previously-installed models, as well as for any new
  151. models being installed at that time. Afterward, it will create default
  152. permissions for new models each time you run :djadmin:`manage.py syncdb
  153. <syncdb>`.
  154. Assuming you have an application with an
  155. :attr:`~django.db.models.Options.app_label` ``foo`` and a model named ``Bar``,
  156. to test for basic permissions you should use:
  157. * add: ``user.has_perm('foo.add_bar')``
  158. * change: ``user.has_perm('foo.change_bar')``
  159. * delete: ``user.has_perm('foo.delete_bar')``
  160. The :class:`~django.contrib.auth.models.Permission` model is rarely accessed
  161. directly.
  162. Groups
  163. ------
  164. :class:`django.contrib.auth.models.Group` models are a generic way of
  165. categorizing users so you can apply permissions, or some other label, to those
  166. users. A user can belong to any number of groups.
  167. A user in a group automatically has the permissions granted to that group. For
  168. example, if the group ``Site editors`` has the permission
  169. ``can_edit_home_page``, any user in that group will have that permission.
  170. Beyond permissions, groups are a convenient way to categorize users to give
  171. them some label, or extended functionality. For example, you could create a
  172. group ``'Special users'``, and you could write code that could, say, give them
  173. access to a members-only portion of your site, or send them members-only email
  174. messages.
  175. Programmatically creating permissions
  176. -------------------------------------
  177. While :ref:`custom permissions <custom-permissions>` can be defined within
  178. a model's ``Meta`` class, you can also create permissions directly. For
  179. example, you can create the ``can_publish`` permission for a ``BlogPost`` model
  180. in ``myapp``::
  181. from myapp.models import BlogPost
  182. from django.contrib.auth.models import Group, Permission
  183. from django.contrib.contenttypes.models import ContentType
  184. content_type = ContentType.objects.get_for_model(BlogPost)
  185. permission = Permission.objects.create(codename='can_publish',
  186. name='Can Publish Posts',
  187. content_type=content_type)
  188. The permission can then be assigned to a
  189. :class:`~django.contrib.auth.models.User` via its ``user_permissions``
  190. attribute or to a :class:`~django.contrib.auth.models.Group` via its
  191. ``permissions`` attribute.
  192. .. _auth-web-requests:
  193. Authentication in Web requests
  194. ==============================
  195. Django uses :doc:`sessions </topics/http/sessions>` and middleware to hook the
  196. authentication system into :class:`request objects <django.http.HttpRequest>`.
  197. These provide a :attr:`request.user <django.http.HttpRequest.user>` attribute
  198. on every request which represents the current user. If the current user has not
  199. logged in, this attribute will be set to an instance
  200. of :class:`~django.contrib.auth.models.AnonymousUser`, otherwise it will be an
  201. instance of :class:`~django.contrib.auth.models.User`.
  202. You can tell them apart with
  203. :meth:`~django.contrib.auth.models.User.is_authenticated()`, like so::
  204. if request.user.is_authenticated():
  205. # Do something for authenticated users.
  206. else:
  207. # Do something for anonymous users.
  208. .. _how-to-log-a-user-in:
  209. How to log a user in
  210. --------------------
  211. If you have an authenticated user you want to attach to the current session
  212. - this is done with a :func:`~django.contrib.auth.login` function.
  213. .. function:: login()
  214. To log a user in, from a view, use :func:`~django.contrib.auth.login()`. It
  215. takes an :class:`~django.http.HttpRequest` object and a
  216. :class:`~django.contrib.auth.models.User` object.
  217. :func:`~django.contrib.auth.login()` saves the user's ID in the session,
  218. using Django's session framework.
  219. Note that any data set during the anonymous session is retained in the
  220. session after a user logs in.
  221. This example shows how you might use both
  222. :func:`~django.contrib.auth.authenticate()` and
  223. :func:`~django.contrib.auth.login()`::
  224. from django.contrib.auth import authenticate, login
  225. def my_view(request):
  226. username = request.POST['username']
  227. password = request.POST['password']
  228. user = authenticate(username=username, password=password)
  229. if user is not None:
  230. if user.is_active:
  231. login(request, user)
  232. # Redirect to a success page.
  233. else:
  234. # Return a 'disabled account' error message
  235. else:
  236. # Return an 'invalid login' error message.
  237. .. admonition:: Calling ``authenticate()`` first
  238. When you're manually logging a user in, you *must* call
  239. :func:`~django.contrib.auth.authenticate()` before you call
  240. :func:`~django.contrib.auth.login()`.
  241. :func:`~django.contrib.auth.authenticate()`
  242. sets an attribute on the :class:`~django.contrib.auth.models.User` noting
  243. which authentication backend successfully authenticated that user (see the
  244. :ref:`backends documentation <authentication-backends>` for details), and
  245. this information is needed later during the login process. An error will be
  246. raised if you try to login a user object retrieved from the database
  247. directly.
  248. How to log a user out
  249. ---------------------
  250. .. function:: logout()
  251. To log out a user who has been logged in via
  252. :func:`django.contrib.auth.login()`, use
  253. :func:`django.contrib.auth.logout()` within your view. It takes an
  254. :class:`~django.http.HttpRequest` object and has no return value.
  255. Example::
  256. from django.contrib.auth import logout
  257. def logout_view(request):
  258. logout(request)
  259. # Redirect to a success page.
  260. Note that :func:`~django.contrib.auth.logout()` doesn't throw any errors if
  261. the user wasn't logged in.
  262. When you call :func:`~django.contrib.auth.logout()`, the session data for
  263. the current request is completely cleaned out. All existing data is
  264. removed. This is to prevent another person from using the same Web browser
  265. to log in and have access to the previous user's session data. If you want
  266. to put anything into the session that will be available to the user
  267. immediately after logging out, do that *after* calling
  268. :func:`django.contrib.auth.logout()`.
  269. Limiting access to logged-in users
  270. ----------------------------------
  271. The raw way
  272. ~~~~~~~~~~~
  273. The simple, raw way to limit access to pages is to check
  274. :meth:`request.user.is_authenticated()
  275. <django.contrib.auth.models.User.is_authenticated()>` and either redirect to a
  276. login page::
  277. from django.shortcuts import redirect
  278. def my_view(request):
  279. if not request.user.is_authenticated():
  280. return redirect('/login/?next=%s' % request.path)
  281. # ...
  282. ...or display an error message::
  283. from django.shortcuts import render
  284. def my_view(request):
  285. if not request.user.is_authenticated():
  286. return render(request, 'myapp/login_error.html')
  287. # ...
  288. .. currentmodule:: django.contrib.auth.decorators
  289. The login_required decorator
  290. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  291. .. function:: login_required([redirect_field_name=REDIRECT_FIELD_NAME, login_url=None])
  292. As a shortcut, you can use the convenient
  293. :func:`~django.contrib.auth.decorators.login_required` decorator::
  294. from django.contrib.auth.decorators import login_required
  295. @login_required
  296. def my_view(request):
  297. ...
  298. :func:`~django.contrib.auth.decorators.login_required` does the following:
  299. * If the user isn't logged in, redirect to
  300. :setting:`settings.LOGIN_URL <LOGIN_URL>`, passing the current absolute
  301. path in the query string. Example: ``/accounts/login/?next=/polls/3/``.
  302. * If the user is logged in, execute the view normally. The view code is
  303. free to assume the user is logged in.
  304. By default, the path that the user should be redirected to upon
  305. successful authentication is stored in a query string parameter called
  306. ``"next"``. If you would prefer to use a different name for this parameter,
  307. :func:`~django.contrib.auth.decorators.login_required` takes an
  308. optional ``redirect_field_name`` parameter::
  309. from django.contrib.auth.decorators import login_required
  310. @login_required(redirect_field_name='my_redirect_field')
  311. def my_view(request):
  312. ...
  313. Note that if you provide a value to ``redirect_field_name``, you will most
  314. likely need to customize your login template as well, since the template
  315. context variable which stores the redirect path will use the value of
  316. ``redirect_field_name`` as its key rather than ``"next"`` (the default).
  317. :func:`~django.contrib.auth.decorators.login_required` also takes an
  318. optional ``login_url`` parameter. Example::
  319. from django.contrib.auth.decorators import login_required
  320. @login_required(login_url='/accounts/login/')
  321. def my_view(request):
  322. ...
  323. Note that if you don't specify the ``login_url`` parameter, you'll need to
  324. ensure that the :setting:`settings.LOGIN_URL <LOGIN_URL>` and your login
  325. view are properly associated. For example, using the defaults, add the
  326. following line to your URLconf::
  327. (r'^accounts/login/$', 'django.contrib.auth.views.login'),
  328. The :setting:`settings.LOGIN_URL <LOGIN_URL>` also accepts view function
  329. names and :ref:`named URL patterns <naming-url-patterns>`. This allows you
  330. to freely remap your login view within your URLconf without having to
  331. update the setting.
  332. .. note::
  333. The login_required decorator does NOT check the is_active flag on a user.
  334. Limiting access to logged-in users that pass a test
  335. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  336. To limit access based on certain permissions or some other test, you'd do
  337. essentially the same thing as described in the previous section.
  338. The simple way is to run your test on :attr:`request.user
  339. <django.http.HttpRequest.user>` in the view directly. For example, this view
  340. checks to make sure the user has an email in the desired domain::
  341. def my_view(request):
  342. if not '@example.com' in request.user.email:
  343. return HttpResponse("You can't vote in this poll.")
  344. # ...
  345. .. function:: user_passes_test(func, [login_url=None])
  346. As a shortcut, you can use the convenient ``user_passes_test`` decorator::
  347. from django.contrib.auth.decorators import user_passes_test
  348. def email_check(user):
  349. return '@example.com' in user.email
  350. @user_passes_test(email_check)
  351. def my_view(request):
  352. ...
  353. :func:`~django.contrib.auth.decorators.user_passes_test` takes a required
  354. argument: a callable that takes a
  355. :class:`~django.contrib.auth.models.User` object and returns ``True`` if
  356. the user is allowed to view the page. Note that
  357. :func:`~django.contrib.auth.decorators.user_passes_test` does not
  358. automatically check that the :class:`~django.contrib.auth.models.User` is
  359. not anonymous.
  360. :func:`~django.contrib.auth.decorators.user_passes_test()` takes an
  361. optional ``login_url`` argument, which lets you specify the URL for your
  362. login page (:setting:`settings.LOGIN_URL <LOGIN_URL>` by default).
  363. For example::
  364. @user_passes_test(email_check, login_url='/login/')
  365. def my_view(request):
  366. ...
  367. The permission_required decorator
  368. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  369. .. function:: permission_required([login_url=None, raise_exception=False])
  370. It's a relatively common task to check whether a user has a particular
  371. permission. For that reason, Django provides a shortcut for that case: the
  372. :func:`~django.contrib.auth.decorators.permission_required()` decorator.::
  373. from django.contrib.auth.decorators import permission_required
  374. @permission_required('polls.can_vote')
  375. def my_view(request):
  376. ...
  377. As for the :meth:`~django.contrib.auth.models.User.has_perm` method,
  378. permission names take the form ``"<app label>.<permission codename>"``
  379. (i.e. ``polls.can_vote`` for a permission on a model in the ``polls``
  380. application).
  381. Note that :func:`~django.contrib.auth.decorators.permission_required()`
  382. also takes an optional ``login_url`` parameter. Example::
  383. from django.contrib.auth.decorators import permission_required
  384. @permission_required('polls.can_vote', login_url='/loginpage/')
  385. def my_view(request):
  386. ...
  387. As in the :func:`~django.contrib.auth.decorators.login_required` decorator,
  388. ``login_url`` defaults to :setting:`settings.LOGIN_URL <LOGIN_URL>`.
  389. If the ``raise_exception`` parameter is given, the decorator will raise
  390. :exc:`~django.core.exceptions.PermissionDenied`, prompting :ref:`the 403
  391. (HTTP Forbidden) view<http_forbidden_view>` instead of redirecting to the
  392. login page.
  393. .. versionchanged:: 1.7
  394. The :func:`~django.contrib.auth.decorators.permission_required`
  395. decorator can take a list of permissions as well as a single permission.
  396. Applying permissions to generic views
  397. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  398. To apply a permission to a :doc:`class-based generic view
  399. </ref/class-based-views/index>`, decorate the :meth:`View.dispatch
  400. <django.views.generic.base.View.dispatch>` method on the class. See
  401. :ref:`decorating-class-based-views` for details.
  402. .. _built-in-auth-views:
  403. Authentication Views
  404. --------------------
  405. .. module:: django.contrib.auth.views
  406. Django provides several views that you can use for handling login, logout, and
  407. password management. These make use of the :ref:`stock auth forms
  408. <built-in-auth-forms>` but you can pass in your own forms as well.
  409. Django provides no default template for the authentication views - however the
  410. template context is documented for each view below.
  411. The built-in views all return
  412. a :class:`~django.template.response.TemplateResponse` instance, which allows
  413. you to easily customize the response data before rendering. For more details,
  414. see the :doc:`TemplateResponse documentation </ref/template-response>`.
  415. Most built-in authentication views provide a URL name for easier reference. See
  416. :doc:`the URL documentation </topics/http/urls>` for details on using named URL
  417. patterns.
  418. .. function:: login(request, [template_name, redirect_field_name, authentication_form, current_app, extra_context])
  419. **URL name:** ``login``
  420. See :doc:`the URL documentation </topics/http/urls>` for details on using
  421. named URL patterns.
  422. **Optional arguments:**
  423. * ``template_name``: The name of a template to display for the view used to
  424. log the user in. Defaults to :file:`registration/login.html`.
  425. * ``redirect_field_name``: The name of a ``GET`` field containing the
  426. URL to redirect to after login. Overrides ``next`` if the given
  427. ``GET`` parameter is passed.
  428. * ``authentication_form``: A callable (typically just a form class) to
  429. use for authentication. Defaults to
  430. :class:`~django.contrib.auth.forms.AuthenticationForm`.
  431. * ``current_app``: A hint indicating which application contains the current
  432. view. See the :ref:`namespaced URL resolution strategy
  433. <topics-http-reversing-url-namespaces>` for more information.
  434. * ``extra_context``: A dictionary of context data that will be added to the
  435. default context data passed to the template.
  436. Here's what ``django.contrib.auth.views.login`` does:
  437. * If called via ``GET``, it displays a login form that POSTs to the
  438. same URL. More on this in a bit.
  439. * If called via ``POST`` with user submitted credentials, it tries to log
  440. the user in. If login is successful, the view redirects to the URL
  441. specified in ``next``. If ``next`` isn't provided, it redirects to
  442. :setting:`settings.LOGIN_REDIRECT_URL <LOGIN_REDIRECT_URL>` (which
  443. defaults to ``/accounts/profile/``). If login isn't successful, it
  444. redisplays the login form.
  445. It's your responsibility to provide the html for the login template
  446. , called ``registration/login.html`` by default. This template gets passed
  447. four template context variables:
  448. * ``form``: A :class:`~django.forms.Form` object representing the
  449. :class:`~django.contrib.auth.forms.AuthenticationForm`.
  450. * ``next``: The URL to redirect to after successful login. This may
  451. contain a query string, too.
  452. * ``site``: The current :class:`~django.contrib.sites.models.Site`,
  453. according to the :setting:`SITE_ID` setting. If you don't have the
  454. site framework installed, this will be set to an instance of
  455. :class:`~django.contrib.sites.models.RequestSite`, which derives the
  456. site name and domain from the current
  457. :class:`~django.http.HttpRequest`.
  458. * ``site_name``: An alias for ``site.name``. If you don't have the site
  459. framework installed, this will be set to the value of
  460. :attr:`request.META['SERVER_NAME'] <django.http.HttpRequest.META>`.
  461. For more on sites, see :doc:`/ref/contrib/sites`.
  462. If you'd prefer not to call the template :file:`registration/login.html`,
  463. you can pass the ``template_name`` parameter via the extra arguments to
  464. the view in your URLconf. For example, this URLconf line would use
  465. :file:`myapp/login.html` instead::
  466. (r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'myapp/login.html'}),
  467. You can also specify the name of the ``GET`` field which contains the URL
  468. to redirect to after login by passing ``redirect_field_name`` to the view.
  469. By default, the field is called ``next``.
  470. Here's a sample :file:`registration/login.html` template you can use as a
  471. starting point. It assumes you have a :file:`base.html` template that
  472. defines a ``content`` block:
  473. .. code-block:: html+django
  474. {% extends "base.html" %}
  475. {% block content %}
  476. {% if form.errors %}
  477. <p>Your username and password didn't match. Please try again.</p>
  478. {% endif %}
  479. <form method="post" action="{% url 'django.contrib.auth.views.login' %}">
  480. {% csrf_token %}
  481. <table>
  482. <tr>
  483. <td>{{ form.username.label_tag }}</td>
  484. <td>{{ form.username }}</td>
  485. </tr>
  486. <tr>
  487. <td>{{ form.password.label_tag }}</td>
  488. <td>{{ form.password }}</td>
  489. </tr>
  490. </table>
  491. <input type="submit" value="login" />
  492. <input type="hidden" name="next" value="{{ next }}" />
  493. </form>
  494. {% endblock %}
  495. If you have customized authentication (see
  496. :doc:`Customizing Authentication </topics/auth/customizing>`) you can pass a custom authentication form
  497. to the login view via the ``authentication_form`` parameter. This form must
  498. accept a ``request`` keyword argument in its ``__init__`` method, and
  499. provide a ``get_user`` method which returns the authenticated user object
  500. (this method is only ever called after successful form validation).
  501. .. _forms documentation: ../forms/
  502. .. _site framework docs: ../sites/
  503. .. function:: logout(request, [next_page, template_name, redirect_field_name, current_app, extra_context])
  504. Logs a user out.
  505. **URL name:** ``logout``
  506. **Optional arguments:**
  507. * ``next_page``: The URL to redirect to after logout.
  508. * ``template_name``: The full name of a template to display after
  509. logging the user out. Defaults to
  510. :file:`registration/logged_out.html` if no argument is supplied.
  511. * ``redirect_field_name``: The name of a ``GET`` field containing the
  512. URL to redirect to after log out. Overrides ``next_page`` if the given
  513. ``GET`` parameter is passed.
  514. * ``current_app``: A hint indicating which application contains the current
  515. view. See the :ref:`namespaced URL resolution strategy
  516. <topics-http-reversing-url-namespaces>` for more information.
  517. * ``extra_context``: A dictionary of context data that will be added to the
  518. default context data passed to the template.
  519. **Template context:**
  520. * ``title``: The string "Logged out", localized.
  521. * ``site``: The current :class:`~django.contrib.sites.models.Site`,
  522. according to the :setting:`SITE_ID` setting. If you don't have the
  523. site framework installed, this will be set to an instance of
  524. :class:`~django.contrib.sites.models.RequestSite`, which derives the
  525. site name and domain from the current
  526. :class:`~django.http.HttpRequest`.
  527. * ``site_name``: An alias for ``site.name``. If you don't have the site
  528. framework installed, this will be set to the value of
  529. :attr:`request.META['SERVER_NAME'] <django.http.HttpRequest.META>`.
  530. For more on sites, see :doc:`/ref/contrib/sites`.
  531. * ``current_app``: A hint indicating which application contains the current
  532. view. See the :ref:`namespaced URL resolution strategy
  533. <topics-http-reversing-url-namespaces>` for more information.
  534. * ``extra_context``: A dictionary of context data that will be added to the
  535. default context data passed to the template.
  536. .. function:: logout_then_login(request[, login_url, current_app, extra_context])
  537. Logs a user out, then redirects to the login page.
  538. **URL name:** No default URL provided
  539. **Optional arguments:**
  540. * ``login_url``: The URL of the login page to redirect to.
  541. Defaults to :setting:`settings.LOGIN_URL <LOGIN_URL>` if not supplied.
  542. * ``current_app``: A hint indicating which application contains the current
  543. view. See the :ref:`namespaced URL resolution strategy
  544. <topics-http-reversing-url-namespaces>` for more information.
  545. * ``extra_context``: A dictionary of context data that will be added to the
  546. default context data passed to the template.
  547. .. function:: password_change(request[, template_name, post_change_redirect, password_change_form, current_app, extra_context])
  548. Allows a user to change their password.
  549. **URL name:** ``password_change``
  550. **Optional arguments:**
  551. * ``template_name``: The full name of a template to use for
  552. displaying the password change form. Defaults to
  553. :file:`registration/password_change_form.html` if not supplied.
  554. * ``post_change_redirect``: The URL to redirect to after a successful
  555. password change.
  556. * ``password_change_form``: A custom "change password" form which must
  557. accept a ``user`` keyword argument. The form is responsible for
  558. actually changing the user's password. Defaults to
  559. :class:`~django.contrib.auth.forms.PasswordChangeForm`.
  560. * ``current_app``: A hint indicating which application contains the current
  561. view. See the :ref:`namespaced URL resolution strategy
  562. <topics-http-reversing-url-namespaces>` for more information.
  563. * ``extra_context``: A dictionary of context data that will be added to the
  564. default context data passed to the template.
  565. **Template context:**
  566. * ``form``: The password change form (see ``password_change_form`` above).
  567. .. function:: password_change_done(request[, template_name, current_app, extra_context])
  568. The page shown after a user has changed their password.
  569. **URL name:** ``password_change_done``
  570. **Optional arguments:**
  571. * ``template_name``: The full name of a template to use.
  572. Defaults to :file:`registration/password_change_done.html` if not
  573. supplied.
  574. * ``current_app``: A hint indicating which application contains the current
  575. view. See the :ref:`namespaced URL resolution strategy
  576. <topics-http-reversing-url-namespaces>` for more information.
  577. * ``extra_context``: A dictionary of context data that will be added to the
  578. default context data passed to the template.
  579. .. 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])
  580. Allows a user to reset their password by generating a one-time use link
  581. that can be used to reset the password, and sending that link to the
  582. user's registered email address.
  583. If the email address provided does not exist in the system, this view
  584. won't send an email, but the user won't receive any error message either.
  585. This prevents information leaking to potential attackers. If you want to
  586. provide an error message in this case, you can subclass
  587. :class:`~django.contrib.auth.forms.PasswordResetForm` and use the
  588. ``password_reset_form`` argument.
  589. Users flagged with an unusable password (see
  590. :meth:`~django.contrib.auth.models.User.set_unusable_password()` aren't
  591. allowed to request a password reset to prevent misuse when using an
  592. external authentication source like LDAP. Note that they won't receive any
  593. error message since this would expose their account's existence but no
  594. mail will be sent either.
  595. .. versionchanged:: 1.6
  596. Previously, error messages indicated whether a given email was
  597. registered.
  598. **URL name:** ``password_reset``
  599. **Optional arguments:**
  600. * ``template_name``: The full name of a template to use for
  601. displaying the password reset form. Defaults to
  602. :file:`registration/password_reset_form.html` if not supplied.
  603. * ``email_template_name``: The full name of a template to use for
  604. generating the email with the reset password link. Defaults to
  605. :file:`registration/password_reset_email.html` if not supplied.
  606. * ``subject_template_name``: The full name of a template to use for
  607. the subject of the email with the reset password link. Defaults
  608. to :file:`registration/password_reset_subject.txt` if not supplied.
  609. * ``password_reset_form``: Form that will be used to get the email of
  610. the user to reset the password for. Defaults to
  611. :class:`~django.contrib.auth.forms.PasswordResetForm`.
  612. * ``token_generator``: Instance of the class to check the one time link.
  613. This will default to ``default_token_generator``, it's an instance of
  614. ``django.contrib.auth.tokens.PasswordResetTokenGenerator``.
  615. * ``post_reset_redirect``: The URL to redirect to after a successful
  616. password reset request.
  617. * ``from_email``: A valid email address. By default Django uses
  618. the :setting:`DEFAULT_FROM_EMAIL`.
  619. * ``current_app``: A hint indicating which application contains the current
  620. view. See the :ref:`namespaced URL resolution strategy
  621. <topics-http-reversing-url-namespaces>` for more information.
  622. * ``extra_context``: A dictionary of context data that will be added to the
  623. default context data passed to the template.
  624. * ``html_email_template_name``: The full name of a template to use
  625. for generating a ``text/html`` multipart email with the password reset
  626. link. By default, HTML email is not sent.
  627. .. versionadded:: 1.7
  628. ``html_email_template_name`` was added.
  629. **Template context:**
  630. * ``form``: The form (see ``password_reset_form`` above) for resetting
  631. the user's password.
  632. **Email template context:**
  633. * ``email``: An alias for ``user.email``
  634. * ``user``: The current :class:`~django.contrib.auth.models.User`,
  635. according to the ``email`` form field. Only active users are able to
  636. reset their passwords (``User.is_active is True``).
  637. * ``site_name``: An alias for ``site.name``. If you don't have the site
  638. framework installed, this will be set to the value of
  639. :attr:`request.META['SERVER_NAME'] <django.http.HttpRequest.META>`.
  640. For more on sites, see :doc:`/ref/contrib/sites`.
  641. * ``domain``: An alias for ``site.domain``. If you don't have the site
  642. framework installed, this will be set to the value of
  643. ``request.get_host()``.
  644. * ``protocol``: http or https
  645. * ``uid``: The user's primary key encoded in base 64.
  646. * ``token``: Token to check that the reset link is valid.
  647. Sample ``registration/password_reset_email.html`` (email body template):
  648. .. code-block:: html+django
  649. Someone asked for password reset for email {{ email }}. Follow the link below:
  650. {{ protocol}}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %}
  651. .. versionchanged:: 1.6
  652. Reversing ``password_reset_confirm`` takes a ``uidb64`` argument instead
  653. of ``uidb36``.
  654. The same template context is used for subject template. Subject must be
  655. single line plain text string.
  656. .. function:: password_reset_done(request[, template_name, current_app, extra_context])
  657. The page shown after a user has been emailed a link to reset their
  658. password. This view is called by default if the :func:`password_reset` view
  659. doesn't have an explicit ``post_reset_redirect`` URL set.
  660. **URL name:** ``password_reset_done``
  661. **Optional arguments:**
  662. * ``template_name``: The full name of a template to use.
  663. Defaults to :file:`registration/password_reset_done.html` if not
  664. supplied.
  665. * ``current_app``: A hint indicating which application contains the current
  666. view. See the :ref:`namespaced URL resolution strategy
  667. <topics-http-reversing-url-namespaces>` for more information.
  668. * ``extra_context``: A dictionary of context data that will be added to the
  669. default context data passed to the template.
  670. .. function:: password_reset_confirm(request[, uidb64, token, template_name, token_generator, set_password_form, post_reset_redirect, current_app, extra_context])
  671. Presents a form for entering a new password.
  672. **URL name:** ``password_reset_confirm``
  673. **Optional arguments:**
  674. * ``uidb64``: The user's id encoded in base 64. Defaults to ``None``.
  675. .. versionchanged:: 1.6
  676. The ``uidb64`` parameter was previously base 36 encoded and named
  677. ``uidb36``.
  678. * ``token``: Token to check that the password is valid. Defaults to
  679. ``None``.
  680. * ``template_name``: The full name of a template to display the confirm
  681. password view. Default value is :file:`registration/password_reset_confirm.html`.
  682. * ``token_generator``: Instance of the class to check the password. This
  683. will default to ``default_token_generator``, it's an instance of
  684. ``django.contrib.auth.tokens.PasswordResetTokenGenerator``.
  685. * ``set_password_form``: Form that will be used to set the password.
  686. Defaults to :class:`~django.contrib.auth.forms.SetPasswordForm`
  687. * ``post_reset_redirect``: URL to redirect after the password reset
  688. done. Defaults to ``None``.
  689. * ``current_app``: A hint indicating which application contains the current
  690. view. See the :ref:`namespaced URL resolution strategy
  691. <topics-http-reversing-url-namespaces>` for more information.
  692. * ``extra_context``: A dictionary of context data that will be added to the
  693. default context data passed to the template.
  694. **Template context:**
  695. * ``form``: The form (see ``set_password_form`` above) for setting the
  696. new user's password.
  697. * ``validlink``: Boolean, True if the link (combination of ``uidb64`` and
  698. ``token``) is valid or unused yet.
  699. .. function:: password_reset_complete(request[,template_name, current_app, extra_context])
  700. Presents a view which informs the user that the password has been
  701. successfully changed.
  702. **URL name:** ``password_reset_complete``
  703. **Optional arguments:**
  704. * ``template_name``: The full name of a template to display the view.
  705. Defaults to :file:`registration/password_reset_complete.html`.
  706. * ``current_app``: A hint indicating which application contains the current
  707. view. See the :ref:`namespaced URL resolution strategy
  708. <topics-http-reversing-url-namespaces>` for more information.
  709. * ``extra_context``: A dictionary of context data that will be added to the
  710. default context data passed to the template.
  711. Helper functions
  712. ----------------
  713. .. currentmodule:: django.contrib.auth.views
  714. .. function:: redirect_to_login(next[, login_url, redirect_field_name])
  715. Redirects to the login page, and then back to another URL after a
  716. successful login.
  717. **Required arguments:**
  718. * ``next``: The URL to redirect to after a successful login.
  719. **Optional arguments:**
  720. * ``login_url``: The URL of the login page to redirect to.
  721. Defaults to :setting:`settings.LOGIN_URL <LOGIN_URL>` if not supplied.
  722. * ``redirect_field_name``: The name of a ``GET`` field containing the
  723. URL to redirect to after log out. Overrides ``next`` if the given
  724. ``GET`` parameter is passed.
  725. .. _built-in-auth-forms:
  726. Built-in forms
  727. --------------
  728. .. module:: django.contrib.auth.forms
  729. If you don't want to use the built-in views, but want the convenience of not
  730. having to write forms for this functionality, the authentication system
  731. provides several built-in forms located in :mod:`django.contrib.auth.forms`:
  732. .. note::
  733. The built-in authentication forms make certain assumptions about the user
  734. model that they are working with. If you're using a :ref:`custom User model
  735. <auth-custom-user>`, it may be necessary to define your own forms for the
  736. authentication system. For more information, refer to the documentation
  737. about :ref:`using the built-in authentication forms with custom user models
  738. <custom-users-and-the-built-in-auth-forms>`.
  739. .. class:: AdminPasswordChangeForm
  740. A form used in the admin interface to change a user's password.
  741. Takes the ``user`` as the first positional argument.
  742. .. class:: AuthenticationForm
  743. A form for logging a user in.
  744. Takes ``request`` as its first positional argument, which is stored on the
  745. form instance for use by sub-classes.
  746. .. method:: confirm_login_allowed(user)
  747. .. versionadded:: 1.7
  748. By default, ``AuthenticationForm`` rejects users whose ``is_active`` flag
  749. is set to ``False``. You may override this behavior with a custom policy to
  750. determine which users can log in. Do this with a custom form that subclasses
  751. ``AuthenticationForm`` and overrides the ``confirm_login_allowed`` method.
  752. This method should raise a :exc:`~django.core.exceptions.ValidationError`
  753. if the given user may not log in.
  754. For example, to allow all users to log in, regardless of "active" status::
  755. from django.contrib.auth.forms import AuthenticationForm
  756. class AuthenticationFormWithInactiveUsersOkay(AuthenticationForm):
  757. def confirm_login_allowed(self, user):
  758. pass
  759. Or to allow only some active users to log in::
  760. class PickyAuthenticationForm(AuthenticationForm):
  761. def confirm_login_allowed(self, user):
  762. if not user.is_active:
  763. raise forms.ValidationError(
  764. _("This account is inactive."),
  765. code='inactive',
  766. )
  767. if user.username.startswith('b'):
  768. raise forms.ValidationError(
  769. _("Sorry, accounts starting with 'b' aren't welcome here."),
  770. code='no_b_users',
  771. )
  772. .. class:: PasswordChangeForm
  773. A form for allowing a user to change their password.
  774. .. class:: PasswordResetForm
  775. A form for generating and emailing a one-time use link to reset a
  776. user's password.
  777. .. class:: SetPasswordForm
  778. A form that lets a user change his/her password without entering the old
  779. password.
  780. .. class:: UserChangeForm
  781. A form used in the admin interface to change a user's information and
  782. permissions.
  783. .. class:: UserCreationForm
  784. A form for creating a new user.
  785. .. currentmodule:: django.contrib.auth
  786. Authentication data in templates
  787. --------------------------------
  788. The currently logged-in user and his/her permissions are made available in the
  789. :doc:`template context </ref/templates/api>` when you use
  790. :class:`~django.template.RequestContext`.
  791. .. admonition:: Technicality
  792. Technically, these variables are only made available in the template context
  793. if you use :class:`~django.template.RequestContext` *and* your
  794. :setting:`TEMPLATE_CONTEXT_PROCESSORS` setting contains
  795. ``"django.contrib.auth.context_processors.auth"``, which is default. For
  796. more, see the :ref:`RequestContext docs <subclassing-context-requestcontext>`.
  797. Users
  798. ~~~~~
  799. When rendering a template :class:`~django.template.RequestContext`, the
  800. currently logged-in user, either a :class:`~django.contrib.auth.models.User`
  801. instance or an :class:`~django.contrib.auth.models.AnonymousUser` instance, is
  802. stored in the template variable ``{{ user }}``:
  803. .. code-block:: html+django
  804. {% if user.is_authenticated %}
  805. <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
  806. {% else %}
  807. <p>Welcome, new user. Please log in.</p>
  808. {% endif %}
  809. This template context variable is not available if a ``RequestContext`` is not
  810. being used.
  811. Permissions
  812. ~~~~~~~~~~~
  813. The currently logged-in user's permissions are stored in the template variable
  814. ``{{ perms }}``. This is an instance of
  815. ``django.contrib.auth.context_processors.PermWrapper``, which is a
  816. template-friendly proxy of permissions.
  817. In the ``{{ perms }}`` object, single-attribute lookup is a proxy to
  818. :meth:`User.has_module_perms <django.contrib.auth.models.User.has_module_perms>`.
  819. This example would display ``True`` if the logged-in user had any permissions
  820. in the ``foo`` app::
  821. {{ perms.foo }}
  822. Two-level-attribute lookup is a proxy to
  823. :meth:`User.has_perm <django.contrib.auth.models.User.has_perm>`. This example
  824. would display ``True`` if the logged-in user had the permission
  825. ``foo.can_vote``::
  826. {{ perms.foo.can_vote }}
  827. Thus, you can check permissions in template ``{% if %}`` statements:
  828. .. code-block:: html+django
  829. {% if perms.foo %}
  830. <p>You have permission to do something in the foo app.</p>
  831. {% if perms.foo.can_vote %}
  832. <p>You can vote!</p>
  833. {% endif %}
  834. {% if perms.foo.can_drive %}
  835. <p>You can drive!</p>
  836. {% endif %}
  837. {% else %}
  838. <p>You don't have permission to do anything in the foo app.</p>
  839. {% endif %}
  840. It is possible to also look permissions up by ``{% if in %}`` statements.
  841. For example:
  842. .. code-block:: html+django
  843. {% if 'foo' in perms %}
  844. {% if 'foo.can_vote' in perms %}
  845. <p>In lookup works, too.</p>
  846. {% endif %}
  847. {% endif %}
  848. .. _auth-admin:
  849. Managing users in the admin
  850. ===========================
  851. When you have both ``django.contrib.admin`` and ``django.contrib.auth``
  852. installed, the admin provides a convenient way to view and manage users,
  853. groups, and permissions. Users can be created and deleted like any Django
  854. model. Groups can be created, and permissions can be assigned to users or
  855. groups. A log of user edits to models made within the admin is also stored and
  856. displayed.
  857. Creating Users
  858. --------------
  859. You should see a link to "Users" in the "Auth"
  860. section of the main admin index page. The "Add user" admin page is different
  861. than standard admin pages in that it requires you to choose a username and
  862. password before allowing you to edit the rest of the user's fields.
  863. Also note: if you want a user account to be able to create users using the
  864. Django admin site, you'll need to give them permission to add users *and*
  865. change users (i.e., the "Add user" and "Change user" permissions). If an
  866. account has permission to add users but not to change them, that account won't
  867. be able to add users. Why? Because if you have permission to add users, you
  868. have the power to create superusers, which can then, in turn, change other
  869. users. So Django requires add *and* change permissions as a slight security
  870. measure.
  871. Changing Passwords
  872. ------------------
  873. User passwords are not displayed in the admin (nor stored in the database), but
  874. the :doc:`password storage details </topics/auth/passwords>` are displayed.
  875. Included in the display of this information is a link to
  876. a password change form that allows admins to change user passwords.