default.txt 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094
  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 django.contrib.auth.models import Group, Permission
  182. from django.contrib.contenttypes.models import ContentType
  183. content_type = ContentType.objects.get(app_label='myapp', model='BlogPost')
  184. permission = Permission.objects.create(codename='can_publish',
  185. name='Can Publish Posts',
  186. content_type=content_type)
  187. The permission can then be assigned to a
  188. :class:`~django.contrib.auth.models.User` via its ``user_permissions``
  189. attribute or to a :class:`~django.contrib.auth.models.Group` via its
  190. ``permissions`` attribute.
  191. .. _auth-web-requests:
  192. Authentication in Web requests
  193. ==============================
  194. Django uses :doc:`sessions </topics/http/sessions>` and middleware to hook the
  195. authentication system into :class:`request objects <django.http.HttpRequest>`.
  196. These provide a :attr:`request.user <django.http.HttpRequest.user>` attribute
  197. on every request which represents the current user. If the current user has not
  198. logged in, this attribute will be set to an instance
  199. of :class:`~django.contrib.auth.models.AnonymousUser`, otherwise it will be an
  200. instance of :class:`~django.contrib.auth.models.User`.
  201. You can tell them apart with
  202. :meth:`~django.contrib.auth.models.User.is_authenticated()`, like so::
  203. if request.user.is_authenticated():
  204. # Do something for authenticated users.
  205. else:
  206. # Do something for anonymous users.
  207. .. _how-to-log-a-user-in:
  208. How to log a user in
  209. --------------------
  210. If you have an authenticated user you want to attach to the current session
  211. - this is done with a :func:`~django.contrib.auth.login` function.
  212. .. function:: login()
  213. To log a user in, from a view, use :func:`~django.contrib.auth.login()`. It
  214. takes an :class:`~django.http.HttpRequest` object and a
  215. :class:`~django.contrib.auth.models.User` object.
  216. :func:`~django.contrib.auth.login()` saves the user's ID in the session,
  217. using Django's session framework.
  218. Note that any data set during the anonymous session is retained in the
  219. session after a user logs in.
  220. This example shows how you might use both
  221. :func:`~django.contrib.auth.authenticate()` and
  222. :func:`~django.contrib.auth.login()`::
  223. from django.contrib.auth import authenticate, login
  224. def my_view(request):
  225. username = request.POST['username']
  226. password = request.POST['password']
  227. user = authenticate(username=username, password=password)
  228. if user is not None:
  229. if user.is_active:
  230. login(request, user)
  231. # Redirect to a success page.
  232. else:
  233. # Return a 'disabled account' error message
  234. else:
  235. # Return an 'invalid login' error message.
  236. .. admonition:: Calling ``authenticate()`` first
  237. When you're manually logging a user in, you *must* call
  238. :func:`~django.contrib.auth.authenticate()` before you call
  239. :func:`~django.contrib.auth.login()`.
  240. :func:`~django.contrib.auth.authenticate()`
  241. sets an attribute on the :class:`~django.contrib.auth.models.User` noting
  242. which authentication backend successfully authenticated that user (see the
  243. :ref:`backends documentation <authentication-backends>` for details), and
  244. this information is needed later during the login process. An error will be
  245. raise if you try to login a user object retrieved from the database
  246. directly.
  247. How to log a user out
  248. ---------------------
  249. .. function:: logout()
  250. To log out a user who has been logged in via
  251. :func:`django.contrib.auth.login()`, use
  252. :func:`django.contrib.auth.logout()` within your view. It takes an
  253. :class:`~django.http.HttpRequest` object and has no return value.
  254. Example::
  255. from django.contrib.auth import logout
  256. def logout_view(request):
  257. logout(request)
  258. # Redirect to a success page.
  259. Note that :func:`~django.contrib.auth.logout()` doesn't throw any errors if
  260. the user wasn't logged in.
  261. When you call :func:`~django.contrib.auth.logout()`, the session data for
  262. the current request is completely cleaned out. All existing data is
  263. removed. This is to prevent another person from using the same Web browser
  264. to log in and have access to the previous user's session data. If you want
  265. to put anything into the session that will be available to the user
  266. immediately after logging out, do that *after* calling
  267. :func:`django.contrib.auth.logout()`.
  268. Limiting access to logged-in users
  269. ----------------------------------
  270. The raw way
  271. ~~~~~~~~~~~
  272. The simple, raw way to limit access to pages is to check
  273. :meth:`request.user.is_authenticated()
  274. <django.contrib.auth.models.User.is_authenticated()>` and either redirect to a
  275. login page::
  276. from django.shortcuts import redirect
  277. def my_view(request):
  278. if not request.user.is_authenticated():
  279. return redirect('/login/?next=%s' % request.path)
  280. # ...
  281. ...or display an error message::
  282. from django.shortcuts import render
  283. def my_view(request):
  284. if not request.user.is_authenticated():
  285. return render(request, 'myapp/login_error.html')
  286. # ...
  287. .. currentmodule:: django.contrib.auth.decorators
  288. The login_required decorator
  289. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  290. .. function:: login_required([redirect_field_name=REDIRECT_FIELD_NAME, login_url=None])
  291. As a shortcut, you can use the convenient
  292. :func:`~django.contrib.auth.decorators.login_required` decorator::
  293. from django.contrib.auth.decorators import login_required
  294. @login_required
  295. def my_view(request):
  296. ...
  297. :func:`~django.contrib.auth.decorators.login_required` does the following:
  298. * If the user isn't logged in, redirect to
  299. :setting:`settings.LOGIN_URL <LOGIN_URL>`, passing the current absolute
  300. path in the query string. Example: ``/accounts/login/?next=/polls/3/``.
  301. * If the user is logged in, execute the view normally. The view code is
  302. free to assume the user is logged in.
  303. By default, the path that the user should be redirected to upon
  304. successful authentication is stored in a query string parameter called
  305. ``"next"``. If you would prefer to use a different name for this parameter,
  306. :func:`~django.contrib.auth.decorators.login_required` takes an
  307. optional ``redirect_field_name`` parameter::
  308. from django.contrib.auth.decorators import login_required
  309. @login_required(redirect_field_name='my_redirect_field')
  310. def my_view(request):
  311. ...
  312. Note that if you provide a value to ``redirect_field_name``, you will most
  313. likely need to customize your login template as well, since the template
  314. context variable which stores the redirect path will use the value of
  315. ``redirect_field_name`` as its key rather than ``"next"`` (the default).
  316. :func:`~django.contrib.auth.decorators.login_required` also takes an
  317. optional ``login_url`` parameter. Example::
  318. from django.contrib.auth.decorators import login_required
  319. @login_required(login_url='/accounts/login/')
  320. def my_view(request):
  321. ...
  322. Note that if you don't specify the ``login_url`` parameter, you'll need to
  323. ensure that the :setting:`settings.LOGIN_URL <LOGIN_URL>` and your login
  324. view are properly associated. For example, using the defaults, add the
  325. following line to your URLconf::
  326. (r'^accounts/login/$', 'django.contrib.auth.views.login'),
  327. .. versionchanged:: 1.5
  328. The :setting:`settings.LOGIN_URL <LOGIN_URL>` also accepts
  329. view function names and :ref:`named URL patterns <naming-url-patterns>`.
  330. This allows you to freely remap your login view within your URLconf
  331. without having to 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. Applying permissions to generic views
  394. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  395. To apply a permission to a :doc:`class-based generic view
  396. </ref/class-based-views/index>`, decorate the :meth:`View.dispatch
  397. <django.views.generic.base.View.dispatch>` method on the class. See
  398. :ref:`decorating-class-based-views` for details.
  399. .. _built-in-auth-views:
  400. Authentication Views
  401. --------------------
  402. .. module:: django.contrib.auth.views
  403. Django provides several views that you can use for handling login, logout, and
  404. password management. These make use of the :ref:`stock auth forms
  405. <built-in-auth-forms>` but you can pass in your own forms as well.
  406. Django provides no default template for the authentication views - however the
  407. template context is documented for each view below.
  408. The built-in views all return
  409. a :class:`~django.template.response.TemplateResponse` instance, which allows
  410. you to easily customize the response data before rendering. For more details,
  411. see the :doc:`TemplateResponse documentation </ref/template-response>`.
  412. Most built-in authentication views provide a URL name for easier reference. See
  413. :doc:`the URL documentation </topics/http/urls>` for details on using named URL
  414. patterns.
  415. .. function:: login(request, [template_name, redirect_field_name, authentication_form])
  416. **URL name:** ``login``
  417. See :doc:`the URL documentation </topics/http/urls>` for details on using
  418. named URL patterns.
  419. Here's what ``django.contrib.auth.views.login`` does:
  420. * If called via ``GET``, it displays a login form that POSTs to the
  421. same URL. More on this in a bit.
  422. * If called via ``POST`` with user submitted credentials, it tries to log
  423. the user in. If login is successful, the view redirects to the URL
  424. specified in ``next``. If ``next`` isn't provided, it redirects to
  425. :setting:`settings.LOGIN_REDIRECT_URL <LOGIN_REDIRECT_URL>` (which
  426. defaults to ``/accounts/profile/``). If login isn't successful, it
  427. redisplays the login form.
  428. It's your responsibility to provide the html for the login template
  429. , called ``registration/login.html`` by default. This template gets passed
  430. four template context variables:
  431. * ``form``: A :class:`~django.forms.Form` object representing the
  432. :class:`~django.contrib.auth.forms.AuthenticationForm`.
  433. * ``next``: The URL to redirect to after successful login. This may
  434. contain a query string, too.
  435. * ``site``: The current :class:`~django.contrib.sites.models.Site`,
  436. according to the :setting:`SITE_ID` setting. If you don't have the
  437. site framework installed, this will be set to an instance of
  438. :class:`~django.contrib.sites.models.RequestSite`, which derives the
  439. site name and domain from the current
  440. :class:`~django.http.HttpRequest`.
  441. * ``site_name``: An alias for ``site.name``. If you don't have the site
  442. framework installed, this will be set to the value of
  443. :attr:`request.META['SERVER_NAME'] <django.http.HttpRequest.META>`.
  444. For more on sites, see :doc:`/ref/contrib/sites`.
  445. If you'd prefer not to call the template :file:`registration/login.html`,
  446. you can pass the ``template_name`` parameter via the extra arguments to
  447. the view in your URLconf. For example, this URLconf line would use
  448. :file:`myapp/login.html` instead::
  449. (r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'myapp/login.html'}),
  450. You can also specify the name of the ``GET`` field which contains the URL
  451. to redirect to after login by passing ``redirect_field_name`` to the view.
  452. By default, the field is called ``next``.
  453. Here's a sample :file:`registration/login.html` template you can use as a
  454. starting point. It assumes you have a :file:`base.html` template that
  455. defines a ``content`` block:
  456. .. code-block:: html+django
  457. {% extends "base.html" %}
  458. {% block content %}
  459. {% if form.errors %}
  460. <p>Your username and password didn't match. Please try again.</p>
  461. {% endif %}
  462. <form method="post" action="{% url 'django.contrib.auth.views.login' %}">
  463. {% csrf_token %}
  464. <table>
  465. <tr>
  466. <td>{{ form.username.label_tag }}</td>
  467. <td>{{ form.username }}</td>
  468. </tr>
  469. <tr>
  470. <td>{{ form.password.label_tag }}</td>
  471. <td>{{ form.password }}</td>
  472. </tr>
  473. </table>
  474. <input type="submit" value="login" />
  475. <input type="hidden" name="next" value="{{ next }}" />
  476. </form>
  477. {% endblock %}
  478. If you have customized authentication (see
  479. :doc:`Customizing Authentication </topics/auth/customizing>`) you can pass a custom authentication form
  480. to the login view via the ``authentication_form`` parameter. This form must
  481. accept a ``request`` keyword argument in its ``__init__`` method, and
  482. provide a ``get_user`` method which returns the authenticated user object
  483. (this method is only ever called after successful form validation).
  484. .. _forms documentation: ../forms/
  485. .. _site framework docs: ../sites/
  486. .. function:: logout(request, [next_page, template_name, redirect_field_name])
  487. Logs a user out.
  488. **URL name:** ``logout``
  489. **Optional arguments:**
  490. * ``next_page``: The URL to redirect to after logout.
  491. * ``template_name``: The full name of a template to display after
  492. logging the user out. Defaults to
  493. :file:`registration/logged_out.html` if no argument is supplied.
  494. * ``redirect_field_name``: The name of a ``GET`` field containing the
  495. URL to redirect to after log out. Overrides ``next_page`` if the given
  496. ``GET`` parameter is passed.
  497. **Template context:**
  498. * ``title``: The string "Logged out", localized.
  499. * ``site``: The current :class:`~django.contrib.sites.models.Site`,
  500. according to the :setting:`SITE_ID` setting. If you don't have the
  501. site framework installed, this will be set to an instance of
  502. :class:`~django.contrib.sites.models.RequestSite`, which derives the
  503. site name and domain from the current
  504. :class:`~django.http.HttpRequest`.
  505. * ``site_name``: An alias for ``site.name``. If you don't have the site
  506. framework installed, this will be set to the value of
  507. :attr:`request.META['SERVER_NAME'] <django.http.HttpRequest.META>`.
  508. For more on sites, see :doc:`/ref/contrib/sites`.
  509. .. function:: logout_then_login(request[, login_url])
  510. Logs a user out, then redirects to the login page.
  511. **URL name:** No default URL provided
  512. **Optional arguments:**
  513. * ``login_url``: The URL of the login page to redirect to.
  514. Defaults to :setting:`settings.LOGIN_URL <LOGIN_URL>` if not supplied.
  515. .. function:: password_change(request[, template_name, post_change_redirect, password_change_form])
  516. Allows a user to change their password.
  517. **URL name:** ``password_change``
  518. **Optional arguments:**
  519. * ``template_name``: The full name of a template to use for
  520. displaying the password change form. Defaults to
  521. :file:`registration/password_change_form.html` if not supplied.
  522. * ``post_change_redirect``: The URL to redirect to after a successful
  523. password change.
  524. * ``password_change_form``: A custom "change password" form which must
  525. accept a ``user`` keyword argument. The form is responsible for
  526. actually changing the user's password. Defaults to
  527. :class:`~django.contrib.auth.forms.PasswordChangeForm`.
  528. **Template context:**
  529. * ``form``: The password change form (see ``password_change_form`` above).
  530. .. function:: password_change_done(request[, template_name])
  531. The page shown after a user has changed their password.
  532. **URL name:** ``password_change_done``
  533. **Optional arguments:**
  534. * ``template_name``: The full name of a template to use.
  535. Defaults to :file:`registration/password_change_done.html` if not
  536. supplied.
  537. .. function:: password_reset(request[, is_admin_site, template_name, email_template_name, password_reset_form, token_generator, post_reset_redirect, from_email])
  538. Allows a user to reset their password by generating a one-time use link
  539. that can be used to reset the password, and sending that link to the
  540. user's registered email address.
  541. If the email address provided does not exist in the system, this view
  542. won't send an email, but the user won't receive any error message either.
  543. This prevents information leaking to potential attackers. If you want to
  544. provide an error message in this case, you can subclass
  545. :class:`~django.contrib.auth.forms.PasswordResetForm` and use the
  546. ``password_reset_form`` argument.
  547. Users flagged with an unusable password (see
  548. :meth:`~django.contrib.auth.models.User.set_unusable_password()` aren't
  549. allowed to request a password reset to prevent misuse when using an
  550. external authentication source like LDAP. Note that they won't receive any
  551. error message since this would expose their account's existence but no
  552. mail will be sent either.
  553. .. versionchanged:: 1.6
  554. Previously, error messages indicated whether a given email was
  555. registered.
  556. **URL name:** ``password_reset``
  557. **Optional arguments:**
  558. * ``template_name``: The full name of a template to use for
  559. displaying the password reset form. Defaults to
  560. :file:`registration/password_reset_form.html` if not supplied.
  561. * ``email_template_name``: The full name of a template to use for
  562. generating the email with the reset password link. Defaults to
  563. :file:`registration/password_reset_email.html` if not supplied.
  564. * ``subject_template_name``: The full name of a template to use for
  565. the subject of the email with the reset password link. Defaults
  566. to :file:`registration/password_reset_subject.txt` if not supplied.
  567. * ``password_reset_form``: Form that will be used to get the email of
  568. the user to reset the password for. Defaults to
  569. :class:`~django.contrib.auth.forms.PasswordResetForm`.
  570. * ``token_generator``: Instance of the class to check the one time link.
  571. This will default to ``default_token_generator``, it's an instance of
  572. ``django.contrib.auth.tokens.PasswordResetTokenGenerator``.
  573. * ``post_reset_redirect``: The URL to redirect to after a successful
  574. password reset request.
  575. * ``from_email``: A valid email address. By default Django uses
  576. the :setting:`DEFAULT_FROM_EMAIL`.
  577. **Template context:**
  578. * ``form``: The form (see ``password_reset_form`` above) for resetting
  579. the user's password.
  580. **Email template context:**
  581. * ``email``: An alias for ``user.email``
  582. * ``user``: The current :class:`~django.contrib.auth.models.User`,
  583. according to the ``email`` form field. Only active users are able to
  584. reset their passwords (``User.is_active is True``).
  585. * ``site_name``: An alias for ``site.name``. If you don't have the site
  586. framework installed, this will be set to the value of
  587. :attr:`request.META['SERVER_NAME'] <django.http.HttpRequest.META>`.
  588. For more on sites, see :doc:`/ref/contrib/sites`.
  589. * ``domain``: An alias for ``site.domain``. If you don't have the site
  590. framework installed, this will be set to the value of
  591. ``request.get_host()``.
  592. * ``protocol``: http or https
  593. * ``uid``: The user's id encoded in base 36.
  594. * ``token``: Token to check that the reset link is valid.
  595. Sample ``registration/password_reset_email.html`` (email body template):
  596. .. code-block:: html+django
  597. Someone asked for password reset for email {{ email }}. Follow the link below:
  598. {{ protocol}}://{{ domain }}{% url 'password_reset_confirm' uidb36=uid token=token %}
  599. The same template context is used for subject template. Subject must be
  600. single line plain text string.
  601. .. function:: password_reset_done(request[, template_name])
  602. The page shown after a user has been emailed a link to reset their
  603. password. This view is called by default if the :func:`password_reset` view
  604. doesn't have an explicit ``post_reset_redirect`` URL set.
  605. **URL name:** ``password_reset_done``
  606. **Optional arguments:**
  607. * ``template_name``: The full name of a template to use.
  608. Defaults to :file:`registration/password_reset_done.html` if not
  609. supplied.
  610. .. function:: password_reset_confirm(request[, uidb36, token, template_name, token_generator, set_password_form, post_reset_redirect])
  611. Presents a form for entering a new password.
  612. **URL name:** ``password_reset_confirm``
  613. **Optional arguments:**
  614. * ``uidb36``: The user's id encoded in base 36. Defaults to ``None``.
  615. * ``token``: Token to check that the password is valid. Defaults to
  616. ``None``.
  617. * ``template_name``: The full name of a template to display the confirm
  618. password view. Default value is :file:`registration/password_reset_confirm.html`.
  619. * ``token_generator``: Instance of the class to check the password. This
  620. will default to ``default_token_generator``, it's an instance of
  621. ``django.contrib.auth.tokens.PasswordResetTokenGenerator``.
  622. * ``set_password_form``: Form that will be used to set the password.
  623. Defaults to :class:`~django.contrib.auth.forms.SetPasswordForm`
  624. * ``post_reset_redirect``: URL to redirect after the password reset
  625. done. Defaults to ``None``.
  626. **Template context:**
  627. * ``form``: The form (see ``set_password_form`` above) for setting the
  628. new user's password.
  629. * ``validlink``: Boolean, True if the link (combination of uidb36 and
  630. token) is valid or unused yet.
  631. .. function:: password_reset_complete(request[,template_name])
  632. Presents a view which informs the user that the password has been
  633. successfully changed.
  634. **URL name:** ``password_reset_complete``
  635. **Optional arguments:**
  636. * ``template_name``: The full name of a template to display the view.
  637. Defaults to :file:`registration/password_reset_complete.html`.
  638. Helper functions
  639. ----------------
  640. .. currentmodule:: django.contrib.auth.views
  641. .. function:: redirect_to_login(next[, login_url, redirect_field_name])
  642. Redirects to the login page, and then back to another URL after a
  643. successful login.
  644. **Required arguments:**
  645. * ``next``: The URL to redirect to after a successful login.
  646. **Optional arguments:**
  647. * ``login_url``: The URL of the login page to redirect to.
  648. Defaults to :setting:`settings.LOGIN_URL <LOGIN_URL>` if not supplied.
  649. * ``redirect_field_name``: The name of a ``GET`` field containing the
  650. URL to redirect to after log out. Overrides ``next`` if the given
  651. ``GET`` parameter is passed.
  652. .. _built-in-auth-forms:
  653. Built-in forms
  654. --------------
  655. .. module:: django.contrib.auth.forms
  656. If you don't want to use the built-in views, but want the convenience of not
  657. having to write forms for this functionality, the authentication system
  658. provides several built-in forms located in :mod:`django.contrib.auth.forms`:
  659. .. note::
  660. The built-in authentication forms make certain assumptions about the user
  661. model that they are working with. If you're using a :ref:`custom User model
  662. <auth-custom-user>`, it may be necessary to define your own forms for the
  663. authentication system. For more information, refer to the documentation
  664. about :ref:`using the built-in authentication forms with custom user models
  665. <custom-users-and-the-built-in-auth-forms>`.
  666. .. class:: AdminPasswordChangeForm
  667. A form used in the admin interface to change a user's password.
  668. .. class:: AuthenticationForm
  669. A form for logging a user in.
  670. .. class:: PasswordChangeForm
  671. A form for allowing a user to change their password.
  672. .. class:: PasswordResetForm
  673. A form for generating and emailing a one-time use link to reset a
  674. user's password.
  675. .. class:: SetPasswordForm
  676. A form that lets a user change his/her password without entering the old
  677. password.
  678. .. class:: UserChangeForm
  679. A form used in the admin interface to change a user's information and
  680. permissions.
  681. .. class:: UserCreationForm
  682. A form for creating a new user.
  683. .. currentmodule:: django.contrib.auth
  684. Authentication data in templates
  685. --------------------------------
  686. The currently logged-in user and his/her permissions are made available in the
  687. :doc:`template context </ref/templates/api>` when you use
  688. :class:`~django.template.RequestContext`.
  689. .. admonition:: Technicality
  690. Technically, these variables are only made available in the template context
  691. if you use :class:`~django.template.RequestContext` *and* your
  692. :setting:`TEMPLATE_CONTEXT_PROCESSORS` setting contains
  693. ``"django.contrib.auth.context_processors.auth"``, which is default. For
  694. more, see the :ref:`RequestContext docs <subclassing-context-requestcontext>`.
  695. Users
  696. ~~~~~
  697. When rendering a template :class:`~django.template.RequestContext`, the
  698. currently logged-in user, either a :class:`~django.contrib.auth.models.User`
  699. instance or an :class:`~django.contrib.auth.models.AnonymousUser` instance, is
  700. stored in the template variable ``{{ user }}``:
  701. .. code-block:: html+django
  702. {% if user.is_authenticated %}
  703. <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
  704. {% else %}
  705. <p>Welcome, new user. Please log in.</p>
  706. {% endif %}
  707. This template context variable is not available if a ``RequestContext`` is not
  708. being used.
  709. Permissions
  710. ~~~~~~~~~~~
  711. The currently logged-in user's permissions are stored in the template variable
  712. ``{{ perms }}``. This is an instance of
  713. ``django.contrib.auth.context_processors.PermWrapper``, which is a
  714. template-friendly proxy of permissions.
  715. In the ``{{ perms }}`` object, single-attribute lookup is a proxy to
  716. :meth:`User.has_module_perms <django.contrib.auth.models.User.has_module_perms>`.
  717. This example would display ``True`` if the logged-in user had any permissions
  718. in the ``foo`` app::
  719. {{ perms.foo }}
  720. Two-level-attribute lookup is a proxy to
  721. :meth:`User.has_perm <django.contrib.auth.models.User.has_perm>`. This example
  722. would display ``True`` if the logged-in user had the permission
  723. ``foo.can_vote``::
  724. {{ perms.foo.can_vote }}
  725. Thus, you can check permissions in template ``{% if %}`` statements:
  726. .. code-block:: html+django
  727. {% if perms.foo %}
  728. <p>You have permission to do something in the foo app.</p>
  729. {% if perms.foo.can_vote %}
  730. <p>You can vote!</p>
  731. {% endif %}
  732. {% if perms.foo.can_drive %}
  733. <p>You can drive!</p>
  734. {% endif %}
  735. {% else %}
  736. <p>You don't have permission to do anything in the foo app.</p>
  737. {% endif %}
  738. .. versionadded:: 1.5
  739. Permission lookup by "if in".
  740. It is possible to also look permissions up by ``{% if in %}`` statements.
  741. For example:
  742. .. code-block:: html+django
  743. {% if 'foo' in perms %}
  744. {% if 'foo.can_vote' in perms %}
  745. <p>In lookup works, too.</p>
  746. {% endif %}
  747. {% endif %}
  748. .. _auth-admin:
  749. Managing users in the admin
  750. ===========================
  751. When you have both ``django.contrib.admin`` and ``django.contrib.auth``
  752. installed, the admin provides a convenient way to view and manage users,
  753. groups, and permissions. Users can be created and deleted like any Django
  754. model. Groups can be created, and permissions can be assigned to users or
  755. groups. A log of user edits to models made within the admin is also stored and
  756. displayed.
  757. Creating Users
  758. --------------
  759. You should see a link to "Users" in the "Auth"
  760. section of the main admin index page. The "Add user" admin page is different
  761. than standard admin pages in that it requires you to choose a username and
  762. password before allowing you to edit the rest of the user's fields.
  763. Also note: if you want a user account to be able to create users using the
  764. Django admin site, you'll need to give them permission to add users *and*
  765. change users (i.e., the "Add user" and "Change user" permissions). If an
  766. account has permission to add users but not to change them, that account won't
  767. be able to add users. Why? Because if you have permission to add users, you
  768. have the power to create superusers, which can then, in turn, change other
  769. users. So Django requires add *and* change permissions as a slight security
  770. measure.
  771. Changing Passwords
  772. ------------------
  773. User passwords are not displayed in the admin (nor stored in the database), but
  774. the :doc:`password storage details </topics/auth/passwords>` are displayed.
  775. Included in the display of this information is a link to
  776. a password change form that allows admins to change user passwords.