default.txt 48 KB

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