authentication.txt 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173
  1. =============================
  2. User authentication in Django
  3. =============================
  4. Django comes with a user authentication system. It handles user accounts,
  5. groups, permissions and cookie-based user sessions. This document explains how
  6. things work.
  7. Overview
  8. ========
  9. The auth system consists of:
  10. * Users
  11. * Permissions: Binary (yes/no) flags designating whether a user may perform
  12. a certain task.
  13. * Groups: A generic way of applying labels and permissions to more than one
  14. user.
  15. * Messages: A simple way to queue messages for given users.
  16. Installation
  17. ============
  18. Authentication support is bundled as a Django application in
  19. ``django.contrib.auth``. To install it, do the following:
  20. 1. Put ``'django.contrib.auth'`` in your ``INSTALLED_APPS`` setting.
  21. 2. Run the command ``manage.py syncdb``.
  22. Note that the default ``settings.py`` file created by
  23. ``django-admin.py startproject`` includes ``'django.contrib.auth'`` in
  24. ``INSTALLED_APPS`` for convenience. If your ``INSTALLED_APPS`` already contains
  25. ``'django.contrib.auth'``, feel free to run ``manage.py syncdb`` again; you
  26. can run that command as many times as you'd like, and each time it'll only
  27. install what's needed.
  28. The ``syncdb`` command creates the necessary database tables, creates
  29. permission objects for all installed apps that need 'em, and prompts you to
  30. create a superuser account the first time you run it.
  31. Once you've taken those steps, that's it.
  32. Users
  33. =====
  34. Users are represented by a standard Django model, which lives in
  35. `django/contrib/auth/models.py`_.
  36. .. _django/contrib/auth/models.py: http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/models.py
  37. API reference
  38. -------------
  39. Fields
  40. ~~~~~~
  41. ``User`` objects have the following fields:
  42. * ``username`` -- Required. 30 characters or fewer. Alphanumeric characters
  43. only (letters, digits and underscores).
  44. * ``first_name`` -- Optional. 30 characters or fewer.
  45. * ``last_name`` -- Optional. 30 characters or fewer.
  46. * ``email`` -- Optional. E-mail address.
  47. * ``password`` -- Required. A hash of, and metadata about, the password.
  48. (Django doesn't store the raw password.) Raw passwords can be arbitrarily
  49. long and can contain any character. See the "Passwords" section below.
  50. * ``is_staff`` -- Boolean. Designates whether this user can access the
  51. admin site.
  52. * ``is_active`` -- Boolean. Designates whether this account can be used
  53. to log in. Set this flag to ``False`` instead of deleting accounts.
  54. * ``is_superuser`` -- Boolean. Designates that this user has all permissions
  55. without explicitly assigning them.
  56. * ``last_login`` -- A datetime of the user's last login. Is set to the
  57. current date/time by default.
  58. * ``date_joined`` -- A datetime designating when the account was created.
  59. Is set to the current date/time by default when the account is created.
  60. Methods
  61. ~~~~~~~
  62. ``User`` objects have two many-to-many fields: ``groups`` and
  63. ``user_permissions``. ``User`` objects can access their related
  64. objects in the same way as any other `Django model`_::
  65. myuser.groups = [group_list]
  66. myuser.groups.add(group, group, ...)
  67. myuser.groups.remove(group, group, ...)
  68. myuser.groups.clear()
  69. myuser.user_permissions = [permission_list]
  70. myuser.user_permissions.add(permission, permission, ...)
  71. myuser.user_permissions.remove(permission, permission, ...)
  72. myuser.user_permissions.clear()
  73. In addition to those automatic API methods, ``User`` objects have the following
  74. custom methods:
  75. * ``is_anonymous()`` -- Always returns ``False``. This is a way of
  76. differentiating ``User`` and ``AnonymousUser`` objects. Generally, you
  77. should prefer using ``is_authenticated()`` to this method.
  78. * ``is_authenticated()`` -- Always returns ``True``. This is a way to
  79. tell if the user has been authenticated. This does not imply any
  80. permissions, and doesn't check if the user is active - it only indicates
  81. that the user has provided a valid username and password.
  82. * ``get_full_name()`` -- Returns the ``first_name`` plus the ``last_name``,
  83. with a space in between.
  84. * ``set_password(raw_password)`` -- Sets the user's password to the given
  85. raw string, taking care of the password hashing. Doesn't save the
  86. ``User`` object.
  87. * ``check_password(raw_password)`` -- Returns ``True`` if the given raw
  88. string is the correct password for the user. (This takes care of the
  89. password hashing in making the comparison.)
  90. * ``set_unusable_password()`` -- **New in Django development version.**
  91. Marks the user as having no password set. This isn't the same as having
  92. a blank string for a password. ``check_password()`` for this user will
  93. never return ``True``. Doesn't save the ``User`` object.
  94. You may need this if authentication for your application takes place
  95. against an existing external source such as an LDAP directory.
  96. * ``has_usable_password()`` -- **New in Django development version.**
  97. Returns ``False`` if ``set_unusable_password()`` has been called for this
  98. user.
  99. * ``get_group_permissions()`` -- Returns a list of permission strings that
  100. the user has, through his/her groups.
  101. * ``get_all_permissions()`` -- Returns a list of permission strings that
  102. the user has, both through group and user permissions.
  103. * ``has_perm(perm)`` -- Returns ``True`` if the user has the specified
  104. permission, where perm is in the format ``"package.codename"``.
  105. If the user is inactive, this method will always return ``False``.
  106. * ``has_perms(perm_list)`` -- Returns ``True`` if the user has each of the
  107. specified permissions, where each perm is in the format
  108. ``"package.codename"``. If the user is inactive, this method will
  109. always return ``False``.
  110. * ``has_module_perms(package_name)`` -- Returns ``True`` if the user has
  111. any permissions in the given package (the Django app label).
  112. If the user is inactive, this method will always return ``False``.
  113. * ``get_and_delete_messages()`` -- Returns a list of ``Message`` objects in
  114. the user's queue and deletes the messages from the queue.
  115. * ``email_user(subject, message, from_email=None)`` -- Sends an e-mail to
  116. the user. If ``from_email`` is ``None``, Django uses the
  117. `DEFAULT_FROM_EMAIL`_ setting.
  118. * ``get_profile()`` -- Returns a site-specific profile for this user.
  119. Raises ``django.contrib.auth.models.SiteProfileNotAvailable`` if the current site
  120. doesn't allow profiles. For information on how to define a
  121. site-specific user profile, see the section on `storing additional
  122. user information`_ below.
  123. .. _Django model: ../model-api/
  124. .. _DEFAULT_FROM_EMAIL: ../settings/#default-from-email
  125. .. _storing additional user information: #storing-additional-information-about-users
  126. Manager functions
  127. ~~~~~~~~~~~~~~~~~
  128. The ``User`` model has a custom manager that has the following helper functions:
  129. * ``create_user(username, email, password=None)`` -- Creates, saves and
  130. returns a ``User``. The ``username``, ``email`` and ``password`` are set
  131. as given, and the ``User`` gets ``is_active=True``.
  132. If no password is provided, ``set_unusable_password()`` will be called.
  133. See `Creating users`_ for example usage.
  134. * ``make_random_password(length=10, allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789')``
  135. Returns a random password with the given length and given string of
  136. allowed characters. (Note that the default value of ``allowed_chars``
  137. doesn't contain letters that can cause user confusion, including
  138. ``1``, ``I`` and ``0``).
  139. Basic usage
  140. -----------
  141. Creating users
  142. ~~~~~~~~~~~~~~
  143. The most basic way to create users is to use the ``create_user`` helper
  144. function that comes with Django::
  145. >>> from django.contrib.auth.models import User
  146. >>> user = User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword')
  147. # At this point, user is a User object that has already been saved
  148. # to the database. You can continue to change its attributes
  149. # if you want to change other fields.
  150. >>> user.is_staff = True
  151. >>> user.save()
  152. Changing passwords
  153. ~~~~~~~~~~~~~~~~~~
  154. Change a password with ``set_password()``::
  155. >>> from django.contrib.auth.models import User
  156. >>> u = User.objects.get(username__exact='john')
  157. >>> u.set_password('new password')
  158. >>> u.save()
  159. Don't set the ``password`` attribute directly unless you know what you're
  160. doing. This is explained in the next section.
  161. Passwords
  162. ---------
  163. The ``password`` attribute of a ``User`` object is a string in this format::
  164. hashtype$salt$hash
  165. That's hashtype, salt and hash, separated by the dollar-sign character.
  166. Hashtype is either ``sha1`` (default), ``md5`` or ``crypt`` -- the algorithm
  167. used to perform a one-way hash of the password. Salt is a random string used
  168. to salt the raw password to create the hash. Note that the ``crypt`` method is
  169. only supported on platforms that have the standard Python ``crypt`` module
  170. available, and ``crypt`` support is only available in the Django development
  171. version.
  172. For example::
  173. sha1$a1976$a36cc8cbf81742a8fb52e221aaeab48ed7f58ab4
  174. The ``User.set_password()`` and ``User.check_password()`` functions handle
  175. the setting and checking of these values behind the scenes.
  176. Previous Django versions, such as 0.90, used simple MD5 hashes without password
  177. salts. For backwards compatibility, those are still supported; they'll be
  178. converted automatically to the new style the first time ``User.check_password()``
  179. works correctly for a given user.
  180. Anonymous users
  181. ---------------
  182. ``django.contrib.auth.models.AnonymousUser`` is a class that implements
  183. the ``django.contrib.auth.models.User`` interface, with these differences:
  184. * ``id`` is always ``None``.
  185. * ``is_staff`` and ``is_superuser`` are always ``False``.
  186. * ``is_active`` is always ``False``.
  187. * ``groups`` and ``user_permissions`` are always empty.
  188. * ``is_anonymous()`` returns ``True`` instead of ``False``.
  189. * ``is_authenticated()`` returns ``False`` instead of ``True``.
  190. * ``has_perm()`` always returns ``False``.
  191. * ``set_password()``, ``check_password()``, ``save()``, ``delete()``,
  192. ``set_groups()`` and ``set_permissions()`` raise ``NotImplementedError``.
  193. In practice, you probably won't need to use ``AnonymousUser`` objects on your
  194. own, but they're used by Web requests, as explained in the next section.
  195. Creating superusers
  196. -------------------
  197. ``manage.py syncdb`` prompts you to create a superuser the first time you run
  198. it after adding ``'django.contrib.auth'`` to your ``INSTALLED_APPS``. If you need
  199. to create a superuser at a later date, you can use a command line utility.
  200. **New in Django development version.**::
  201. manage.py createsuperuser --username=joe --email=joe@example.com
  202. You will be prompted for a password. After you enter one, the user will be
  203. created immediately. If you leave off the ``--username`` or the ``--email``
  204. options, it will prompt you for those values.
  205. If you're using an older release of Django, the old way of creating a superuser
  206. on the command line still works::
  207. python /path/to/django/contrib/auth/create_superuser.py
  208. ...where ``/path/to`` is the path to the Django codebase on your filesystem. The
  209. ``manage.py`` command is preferred because it figures out the correct path and
  210. environment for you.
  211. Storing additional information about users
  212. ------------------------------------------
  213. If you'd like to store additional information related to your users,
  214. Django provides a method to specify a site-specific related model --
  215. termed a "user profile" -- for this purpose.
  216. To make use of this feature, define a model with fields for the
  217. additional information you'd like to store, or additional methods
  218. you'd like to have available, and also add a ``ForeignKey`` from your
  219. model to the ``User`` model, specified with ``unique=True`` to ensure
  220. only one instance of your model can be created for each ``User``.
  221. To indicate that this model is the user profile model for a given
  222. site, fill in the setting ``AUTH_PROFILE_MODULE`` with a string
  223. consisting of the following items, separated by a dot:
  224. 1. The (normalized to lower-case) name of the application in which the
  225. user profile model is defined (in other words, an all-lowercase
  226. version of the name which was passed to ``manage.py startapp`` to
  227. create the application).
  228. 2. The (normalized to lower-case) name of the model class.
  229. For example, if the profile model was a class named ``UserProfile``
  230. and was defined inside an application named ``accounts``, the
  231. appropriate setting would be::
  232. AUTH_PROFILE_MODULE = 'accounts.userprofile'
  233. When a user profile model has been defined and specified in this
  234. manner, each ``User`` object will have a method -- ``get_profile()``
  235. -- which returns the instance of the user profile model associated
  236. with that ``User``.
  237. For more information, see `Chapter 12 of the Django book`_.
  238. .. _Chapter 12 of the Django book: http://www.djangobook.com/en/1.0/chapter12/#cn222
  239. Authentication in Web requests
  240. ==============================
  241. Until now, this document has dealt with the low-level APIs for manipulating
  242. authentication-related objects. On a higher level, Django can hook this
  243. authentication framework into its system of `request objects`_.
  244. First, install the ``SessionMiddleware`` and ``AuthenticationMiddleware``
  245. middlewares by adding them to your ``MIDDLEWARE_CLASSES`` setting. See the
  246. `session documentation`_ for more information.
  247. Once you have those middlewares installed, you'll be able to access
  248. ``request.user`` in views. ``request.user`` will give you a ``User`` object
  249. representing the currently logged-in user. If a user isn't currently logged in,
  250. ``request.user`` will be set to an instance of ``AnonymousUser`` (see the
  251. previous section). You can tell them apart with ``is_authenticated()``, like so::
  252. if request.user.is_authenticated():
  253. # Do something for authenticated users.
  254. else:
  255. # Do something for anonymous users.
  256. .. _request objects: ../request_response/#httprequest-objects
  257. .. _session documentation: ../sessions/
  258. How to log a user in
  259. --------------------
  260. Django provides two functions in ``django.contrib.auth``: ``authenticate()``
  261. and ``login()``.
  262. To authenticate a given username and password, use ``authenticate()``. It
  263. takes two keyword arguments, ``username`` and ``password``, and it returns
  264. a ``User`` object if the password is valid for the given username. If the
  265. password is invalid, ``authenticate()`` returns ``None``. Example::
  266. from django.contrib.auth import authenticate
  267. user = authenticate(username='john', password='secret')
  268. if user is not None:
  269. if user.is_active:
  270. print "You provided a correct username and password!"
  271. else:
  272. print "Your account has been disabled!"
  273. else:
  274. print "Your username and password were incorrect."
  275. To log a user in, in a view, use ``login()``. It takes an ``HttpRequest``
  276. object and a ``User`` object. ``login()`` saves the user's ID in the session,
  277. using Django's session framework, so, as mentioned above, you'll need to make
  278. sure to have the session middleware installed.
  279. This example shows how you might use both ``authenticate()`` and ``login()``::
  280. from django.contrib.auth import authenticate, login
  281. def my_view(request):
  282. username = request.POST['username']
  283. password = request.POST['password']
  284. user = authenticate(username=username, password=password)
  285. if user is not None:
  286. if user.is_active:
  287. login(request, user)
  288. # Redirect to a success page.
  289. else:
  290. # Return a 'disabled account' error message
  291. else:
  292. # Return an 'invalid login' error message.
  293. .. admonition:: Calling ``authenticate()`` first
  294. When you're manually logging a user in, you *must* call
  295. ``authenticate()`` before you call ``login()``. ``authenticate()``
  296. sets an attribute on the ``User`` noting which authentication
  297. backend successfully authenticated that user (see the `backends
  298. documentation`_ for details), and this information is needed later
  299. during the login process.
  300. .. _backends documentation: #other-authentication-sources
  301. Manually checking a user's password
  302. -----------------------------------
  303. If you'd like to manually authenticate a user by comparing a
  304. plain-text password to the hashed password in the database, use the
  305. convenience function ``django.contrib.auth.models.check_password``. It
  306. takes two arguments: the plain-text password to check, and the full
  307. value of a user's ``password`` field in the database to check against,
  308. and returns ``True`` if they match, ``False`` otherwise.
  309. How to log a user out
  310. ---------------------
  311. To log out a user who has been logged in via ``django.contrib.auth.login()``,
  312. use ``django.contrib.auth.logout()`` within your view. It takes an
  313. ``HttpRequest`` object and has no return value. Example::
  314. from django.contrib.auth import logout
  315. def logout_view(request):
  316. logout(request)
  317. # Redirect to a success page.
  318. Note that ``logout()`` doesn't throw any errors if the user wasn't logged in.
  319. **New in Django development version:** When you call ``logout()``, the session
  320. data for the current request is completely cleaned out. All existing data is
  321. removed. This is to prevent another person from using the same web browser to
  322. log in and have access to the previous user's session data. If you want to put
  323. anything into the session that will be available to the user immediately after
  324. logging out, do that *after* calling ``django.contrib.auth.logout()``.
  325. Limiting access to logged-in users
  326. ----------------------------------
  327. The raw way
  328. ~~~~~~~~~~~
  329. The simple, raw way to limit access to pages is to check
  330. ``request.user.is_authenticated()`` and either redirect to a login page::
  331. from django.http import HttpResponseRedirect
  332. def my_view(request):
  333. if not request.user.is_authenticated():
  334. return HttpResponseRedirect('/login/?next=%s' % request.path)
  335. # ...
  336. ...or display an error message::
  337. def my_view(request):
  338. if not request.user.is_authenticated():
  339. return render_to_response('myapp/login_error.html')
  340. # ...
  341. The login_required decorator
  342. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  343. As a shortcut, you can use the convenient ``login_required`` decorator::
  344. from django.contrib.auth.decorators import login_required
  345. def my_view(request):
  346. # ...
  347. my_view = login_required(my_view)
  348. Here's an equivalent example, using the more compact decorator syntax
  349. introduced in Python 2.4::
  350. from django.contrib.auth.decorators import login_required
  351. @login_required
  352. def my_view(request):
  353. # ...
  354. In the Django development version, ``login_required`` also takes an optional
  355. ``redirect_field_name`` parameter. Example::
  356. from django.contrib.auth.decorators import login_required
  357. def my_view(request):
  358. # ...
  359. my_view = login_required(redirect_field_name='redirect_to')(my_view)
  360. Again, an equivalent example of the more compact decorator syntax introduced in Python 2.4::
  361. from django.contrib.auth.decorators import login_required
  362. @login_required(redirect_field_name='redirect_to')
  363. def my_view(request):
  364. # ...
  365. ``login_required`` does the following:
  366. * If the user isn't logged in, redirect to ``settings.LOGIN_URL``
  367. (``/accounts/login/`` by default), passing the current absolute URL
  368. in the query string as ``next`` or the value of ``redirect_field_name``.
  369. For example:
  370. ``/accounts/login/?next=/polls/3/``.
  371. * If the user is logged in, execute the view normally. The view code is
  372. free to assume the user is logged in.
  373. Note that you'll need to map the appropriate Django view to ``settings.LOGIN_URL``.
  374. For example, using the defaults, add the following line to your URLconf::
  375. (r'^accounts/login/$', 'django.contrib.auth.views.login'),
  376. Here's what ``django.contrib.auth.views.login`` does:
  377. * If called via ``GET``, it displays a login form that POSTs to the same
  378. URL. More on this in a bit.
  379. * If called via ``POST``, it tries to log the user in. If login is
  380. successful, the view redirects to the URL specified in ``next``. If
  381. ``next`` isn't provided, it redirects to ``settings.LOGIN_REDIRECT_URL``
  382. (which defaults to ``/accounts/profile/``). If login isn't successful,
  383. it redisplays the login form.
  384. It's your responsibility to provide the login form in a template called
  385. ``registration/login.html`` by default. This template gets passed three
  386. template context variables:
  387. * ``form``: A ``Form`` object representing the login form. See the
  388. `forms documentation`_ for more on ``FormWrapper`` objects.
  389. * ``next``: The URL to redirect to after successful login. This may contain
  390. a query string, too.
  391. * ``site_name``: The name of the current ``Site``, according to the
  392. ``SITE_ID`` setting. If you're using the Django development version and
  393. you don't have the site framework installed, this will be set to the
  394. value of ``request.META['SERVER_NAME']``. For more on sites, see the
  395. `site framework docs`_.
  396. If you'd prefer not to call the template ``registration/login.html``, you can
  397. pass the ``template_name`` parameter via the extra arguments to the view in
  398. your URLconf. For example, this URLconf line would use ``myapp/login.html``
  399. instead::
  400. (r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'myapp/login.html'}),
  401. Here's a sample ``registration/login.html`` template you can use as a starting
  402. point. It assumes you have a ``base.html`` template that defines a ``content``
  403. block::
  404. {% extends "base.html" %}
  405. {% block content %}
  406. {% if form.errors %}
  407. <p>Your username and password didn't match. Please try again.</p>
  408. {% endif %}
  409. <form method="post" action=".">
  410. <table>
  411. <tr><td>{{ form.username.label_tag }}</td><td>{{ form.username }}</td></tr>
  412. <tr><td>{{ form.password.label_tag }}</td><td>{{ form.password }}</td></tr>
  413. </table>
  414. <input type="submit" value="login" />
  415. <input type="hidden" name="next" value="{{ next }}" />
  416. </form>
  417. {% endblock %}
  418. .. _forms documentation: ../forms/
  419. .. _site framework docs: ../sites/
  420. Other built-in views
  421. --------------------
  422. In addition to the ``login`` view, the authentication system includes a
  423. few other useful built-in views:
  424. ``django.contrib.auth.views.logout``
  425. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  426. **Description:**
  427. Logs a user out.
  428. **Optional arguments:**
  429. * ``template_name``: The full name of a template to display after
  430. logging the user out. This will default to
  431. ``registration/logged_out.html`` if no argument is supplied.
  432. **Template context:**
  433. * ``title``: The string "Logged out", localized.
  434. ``django.contrib.auth.views.logout_then_login``
  435. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  436. **Description:**
  437. Logs a user out, then redirects to the login page.
  438. **Optional arguments:**
  439. * ``login_url``: The URL of the login page to redirect to. This
  440. will default to ``settings.LOGIN_URL`` if not supplied.
  441. ``django.contrib.auth.views.password_change``
  442. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  443. **Description:**
  444. Allows a user to change their password.
  445. **Optional arguments:**
  446. * ``template_name``: The full name of a template to use for
  447. displaying the password change form. This will default to
  448. ``registration/password_change_form.html`` if not supplied.
  449. **Template context:**
  450. * ``form``: The password change form.
  451. ``django.contrib.auth.views.password_change_done``
  452. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  453. **Description:**
  454. The page shown after a user has changed their password.
  455. **Optional arguments:**
  456. * ``template_name``: The full name of a template to use. This will
  457. default to ``registration/password_change_done.html`` if not
  458. supplied.
  459. ``django.contrib.auth.views.password_reset``
  460. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  461. **Description:**
  462. Allows a user to reset their password, and sends them the new password
  463. in an e-mail.
  464. **Optional arguments:**
  465. * ``template_name``: The full name of a template to use for
  466. displaying the password reset form. This will default to
  467. ``registration/password_reset_form.html`` if not supplied.
  468. * ``email_template_name``: The full name of a template to use for
  469. generating the e-mail with the new password. This will default to
  470. ``registration/password_reset_email.html`` if not supplied.
  471. **Template context:**
  472. * ``form``: The form for resetting the user's password.
  473. ``django.contrib.auth.views.password_reset_done``
  474. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  475. **Description:**
  476. The page shown after a user has reset their password.
  477. **Optional arguments:**
  478. * ``template_name``: The full name of a template to use. This will
  479. default to ``registration/password_reset_done.html`` if not
  480. supplied.
  481. ``django.contrib.auth.views.redirect_to_login``
  482. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  483. **Description:**
  484. Redirects to the login page, and then back to another URL after a
  485. successful login.
  486. **Required arguments:**
  487. * ``next``: The URL to redirect to after a successful login.
  488. **Optional arguments:**
  489. * ``login_url``: The URL of the login page to redirect to. This
  490. will default to ``settings.LOGIN_URL`` if not supplied.
  491. Built-in forms
  492. --------------
  493. **New in Django development version.**
  494. If you don't want to use the built-in views, but want the convenience
  495. of not having to write forms for this functionality, the authentication
  496. system provides several built-in forms:
  497. * ``django.contrib.auth.forms.AdminPasswordChangeForm``: A form used in
  498. the admin interface to change a user's password.
  499. * ``django.contrib.auth.forms.AuthenticationForm``: A form for logging a
  500. user in.
  501. * ``django.contrib.auth.forms.PasswordChangeForm``: A form for allowing a
  502. user to change their password.
  503. * ``django.contrib.auth.forms.PasswordResetForm``: A form for resetting a
  504. user's password and e-mailing the new password to them.
  505. * ``django.contrib.auth.forms.UserCreationForm``: A form for creating a
  506. new user.
  507. Limiting access to logged-in users that pass a test
  508. ---------------------------------------------------
  509. To limit access based on certain permissions or some other test, you'd do
  510. essentially the same thing as described in the previous section.
  511. The simple way is to run your test on ``request.user`` in the view directly.
  512. For example, this view checks to make sure the user is logged in and has the
  513. permission ``polls.can_vote``::
  514. def my_view(request):
  515. if not (request.user.is_authenticated() and request.user.has_perm('polls.can_vote')):
  516. return HttpResponse("You can't vote in this poll.")
  517. # ...
  518. As a shortcut, you can use the convenient ``user_passes_test`` decorator::
  519. from django.contrib.auth.decorators import user_passes_test
  520. def my_view(request):
  521. # ...
  522. my_view = user_passes_test(lambda u: u.has_perm('polls.can_vote'))(my_view)
  523. We're using this particular test as a relatively simple example. However, if
  524. you just want to test whether a permission is available to a user, you can use
  525. the ``permission_required()`` decorator, described later in this document.
  526. Here's the same thing, using Python 2.4's decorator syntax::
  527. from django.contrib.auth.decorators import user_passes_test
  528. @user_passes_test(lambda u: u.has_perm('polls.can_vote'))
  529. def my_view(request):
  530. # ...
  531. ``user_passes_test`` takes a required argument: a callable that takes a
  532. ``User`` object and returns ``True`` if the user is allowed to view the page.
  533. Note that ``user_passes_test`` does not automatically check that the ``User``
  534. is not anonymous.
  535. ``user_passes_test()`` takes an optional ``login_url`` argument, which lets you
  536. specify the URL for your login page (``settings.LOGIN_URL`` by default).
  537. Example in Python 2.3 syntax::
  538. from django.contrib.auth.decorators import user_passes_test
  539. def my_view(request):
  540. # ...
  541. my_view = user_passes_test(lambda u: u.has_perm('polls.can_vote'), login_url='/login/')(my_view)
  542. Example in Python 2.4 syntax::
  543. from django.contrib.auth.decorators import user_passes_test
  544. @user_passes_test(lambda u: u.has_perm('polls.can_vote'), login_url='/login/')
  545. def my_view(request):
  546. # ...
  547. The permission_required decorator
  548. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  549. It's a relatively common task to check whether a user has a particular
  550. permission. For that reason, Django provides a shortcut for that case: the
  551. ``permission_required()`` decorator. Using this decorator, the earlier example
  552. can be written as::
  553. from django.contrib.auth.decorators import permission_required
  554. def my_view(request):
  555. # ...
  556. my_view = permission_required('polls.can_vote')(my_view)
  557. Note that ``permission_required()`` also takes an optional ``login_url``
  558. parameter. Example::
  559. from django.contrib.auth.decorators import permission_required
  560. def my_view(request):
  561. # ...
  562. my_view = permission_required('polls.can_vote', login_url='/loginpage/')(my_view)
  563. As in the ``login_required`` decorator, ``login_url`` defaults to
  564. ``settings.LOGIN_URL``.
  565. Limiting access to generic views
  566. --------------------------------
  567. To limit access to a `generic view`_, write a thin wrapper around the view,
  568. and point your URLconf to your wrapper instead of the generic view itself.
  569. For example::
  570. from django.views.generic.date_based import object_detail
  571. @login_required
  572. def limited_object_detail(*args, **kwargs):
  573. return object_detail(*args, **kwargs)
  574. .. _generic view: ../generic_views/
  575. Permissions
  576. ===========
  577. Django comes with a simple permissions system. It provides a way to assign
  578. permissions to specific users and groups of users.
  579. It's used by the Django admin site, but you're welcome to use it in your own
  580. code.
  581. The Django admin site uses permissions as follows:
  582. * Access to view the "add" form and add an object is limited to users with
  583. the "add" permission for that type of object.
  584. * Access to view the change list, view the "change" form and change an
  585. object is limited to users with the "change" permission for that type of
  586. object.
  587. * Access to delete an object is limited to users with the "delete"
  588. permission for that type of object.
  589. Permissions are set globally per type of object, not per specific object
  590. instance. For example, it's possible to say "Mary may change news stories," but
  591. it's not currently possible to say "Mary may change news stories, but only the
  592. ones she created herself" or "Mary may only change news stories that have a
  593. certain status, publication date or ID." The latter functionality is something
  594. Django developers are currently discussing.
  595. Default permissions
  596. -------------------
  597. When ``django.contrib.auth`` is listed in your ``INSTALLED_APPS``
  598. setting, it will ensure that three default permissions -- add, change
  599. and delete -- are created for each Django model defined in one of your
  600. installed applications.
  601. These permissions will be created when you run ``manage.py syncdb``;
  602. the first time you run ``syncdb`` after adding ``django.contrib.auth``
  603. to ``INSTALLED_APPS``, the default permissions will be created for all
  604. previously-installed models, as well as for any new models being
  605. installed at that time. Afterward, it will create default permissions
  606. for new models each time you run ``manage.py syncdb``.
  607. Custom permissions
  608. ------------------
  609. To create custom permissions for a given model object, use the ``permissions``
  610. `model Meta attribute`_.
  611. This example model creates three custom permissions::
  612. class USCitizen(models.Model):
  613. # ...
  614. class Meta:
  615. permissions = (
  616. ("can_drive", "Can drive"),
  617. ("can_vote", "Can vote in elections"),
  618. ("can_drink", "Can drink alcohol"),
  619. )
  620. The only thing this does is create those extra permissions when you run
  621. ``syncdb``.
  622. .. _model Meta attribute: ../model-api/#meta-options
  623. API reference
  624. -------------
  625. Just like users, permissions are implemented in a Django model that lives in
  626. `django/contrib/auth/models.py`_.
  627. .. _django/contrib/auth/models.py: http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/models.py
  628. Fields
  629. ~~~~~~
  630. ``Permission`` objects have the following fields:
  631. * ``name`` -- Required. 50 characters or fewer. Example: ``'Can vote'``.
  632. * ``content_type`` -- Required. A reference to the ``django_content_type``
  633. database table, which contains a record for each installed Django model.
  634. * ``codename`` -- Required. 100 characters or fewer. Example: ``'can_vote'``.
  635. Methods
  636. ~~~~~~~
  637. ``Permission`` objects have the standard data-access methods like any other
  638. `Django model`_.
  639. Authentication data in templates
  640. ================================
  641. The currently logged-in user and his/her permissions are made available in the
  642. `template context`_ when you use ``RequestContext``.
  643. .. admonition:: Technicality
  644. Technically, these variables are only made available in the template context
  645. if you use ``RequestContext`` *and* your ``TEMPLATE_CONTEXT_PROCESSORS``
  646. setting contains ``"django.core.context_processors.auth"``, which is default.
  647. For more, see the `RequestContext docs`_.
  648. .. _RequestContext docs: ../templates_python/#subclassing-context-requestcontext
  649. Users
  650. -----
  651. The currently logged-in user, either a ``User`` instance or an``AnonymousUser``
  652. instance, is stored in the template variable ``{{ user }}``::
  653. {% if user.is_authenticated %}
  654. <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
  655. {% else %}
  656. <p>Welcome, new user. Please log in.</p>
  657. {% endif %}
  658. Permissions
  659. -----------
  660. The currently logged-in user's permissions are stored in the template variable
  661. ``{{ perms }}``. This is an instance of ``django.core.context_processors.PermWrapper``,
  662. which is a template-friendly proxy of permissions.
  663. In the ``{{ perms }}`` object, single-attribute lookup is a proxy to
  664. ``User.has_module_perms``. This example would display ``True`` if the logged-in
  665. user had any permissions in the ``foo`` app::
  666. {{ perms.foo }}
  667. Two-level-attribute lookup is a proxy to ``User.has_perm``. This example would
  668. display ``True`` if the logged-in user had the permission ``foo.can_vote``::
  669. {{ perms.foo.can_vote }}
  670. Thus, you can check permissions in template ``{% if %}`` statements::
  671. {% if perms.foo %}
  672. <p>You have permission to do something in the foo app.</p>
  673. {% if perms.foo.can_vote %}
  674. <p>You can vote!</p>
  675. {% endif %}
  676. {% if perms.foo.can_drive %}
  677. <p>You can drive!</p>
  678. {% endif %}
  679. {% else %}
  680. <p>You don't have permission to do anything in the foo app.</p>
  681. {% endif %}
  682. .. _template context: ../templates_python/
  683. Groups
  684. ======
  685. Groups are a generic way of categorizing users so you can apply permissions, or
  686. some other label, to those users. A user can belong to any number of groups.
  687. A user in a group automatically has the permissions granted to that group. For
  688. example, if the group ``Site editors`` has the permission
  689. ``can_edit_home_page``, any user in that group will have that permission.
  690. Beyond permissions, groups are a convenient way to categorize users to give
  691. them some label, or extended functionality. For example, you could create a
  692. group ``'Special users'``, and you could write code that could, say, give them
  693. access to a members-only portion of your site, or send them members-only e-mail
  694. messages.
  695. Messages
  696. ========
  697. The message system is a lightweight way to queue messages for given users.
  698. A message is associated with a ``User``. There's no concept of expiration or
  699. timestamps.
  700. Messages are used by the Django admin after successful actions. For example,
  701. ``"The poll Foo was created successfully."`` is a message.
  702. The API is simple:
  703. * To create a new message, use
  704. ``user_obj.message_set.create(message='message_text')``.
  705. * To retrieve/delete messages, use ``user_obj.get_and_delete_messages()``,
  706. which returns a list of ``Message`` objects in the user's queue (if any)
  707. and deletes the messages from the queue.
  708. In this example view, the system saves a message for the user after creating
  709. a playlist::
  710. def create_playlist(request, songs):
  711. # Create the playlist with the given songs.
  712. # ...
  713. request.user.message_set.create(message="Your playlist was added successfully.")
  714. return render_to_response("playlists/create.html",
  715. context_instance=RequestContext(request))
  716. When you use ``RequestContext``, the currently logged-in user and his/her
  717. messages are made available in the `template context`_ as the template variable
  718. ``{{ messages }}``. Here's an example of template code that displays messages::
  719. {% if messages %}
  720. <ul>
  721. {% for message in messages %}
  722. <li>{{ message }}</li>
  723. {% endfor %}
  724. </ul>
  725. {% endif %}
  726. Note that ``RequestContext`` calls ``get_and_delete_messages`` behind the
  727. scenes, so any messages will be deleted even if you don't display them.
  728. Finally, note that this messages framework only works with users in the user
  729. database. To send messages to anonymous users, use the `session framework`_.
  730. .. _session framework: ../sessions/
  731. Other authentication sources
  732. ============================
  733. The authentication that comes with Django is good enough for most common cases,
  734. but you may have the need to hook into another authentication source -- that
  735. is, another source of usernames and passwords or authentication methods.
  736. For example, your company may already have an LDAP setup that stores a username
  737. and password for every employee. It'd be a hassle for both the network
  738. administrator and the users themselves if users had separate accounts in LDAP
  739. and the Django-based applications.
  740. So, to handle situations like this, the Django authentication system lets you
  741. plug in another authentication sources. You can override Django's default
  742. database-based scheme, or you can use the default system in tandem with other
  743. systems.
  744. Specifying authentication backends
  745. ----------------------------------
  746. Behind the scenes, Django maintains a list of "authentication backends" that it
  747. checks for authentication. When somebody calls
  748. ``django.contrib.auth.authenticate()`` -- as described in "How to log a user in"
  749. above -- Django tries authenticating across all of its authentication backends.
  750. If the first authentication method fails, Django tries the second one, and so
  751. on, until all backends have been attempted.
  752. The list of authentication backends to use is specified in the
  753. ``AUTHENTICATION_BACKENDS`` setting. This should be a tuple of Python path
  754. names that point to Python classes that know how to authenticate. These classes
  755. can be anywhere on your Python path.
  756. By default, ``AUTHENTICATION_BACKENDS`` is set to::
  757. ('django.contrib.auth.backends.ModelBackend',)
  758. That's the basic authentication scheme that checks the Django users database.
  759. The order of ``AUTHENTICATION_BACKENDS`` matters, so if the same username and
  760. password is valid in multiple backends, Django will stop processing at the
  761. first positive match.
  762. Writing an authentication backend
  763. ---------------------------------
  764. An authentication backend is a class that implements two methods:
  765. ``get_user(user_id)`` and ``authenticate(**credentials)``.
  766. The ``get_user`` method takes a ``user_id`` -- which could be a username,
  767. database ID or whatever -- and returns a ``User`` object.
  768. The ``authenticate`` method takes credentials as keyword arguments. Most of
  769. the time, it'll just look like this::
  770. class MyBackend:
  771. def authenticate(self, username=None, password=None):
  772. # Check the username/password and return a User.
  773. But it could also authenticate a token, like so::
  774. class MyBackend:
  775. def authenticate(self, token=None):
  776. # Check the token and return a User.
  777. Either way, ``authenticate`` should check the credentials it gets, and it
  778. should return a ``User`` object that matches those credentials, if the
  779. credentials are valid. If they're not valid, it should return ``None``.
  780. The Django admin system is tightly coupled to the Django ``User`` object
  781. described at the beginning of this document. For now, the best way to deal with
  782. this is to create a Django ``User`` object for each user that exists for your
  783. backend (e.g., in your LDAP directory, your external SQL database, etc.) You
  784. can either write a script to do this in advance, or your ``authenticate``
  785. method can do it the first time a user logs in.
  786. Here's an example backend that authenticates against a username and password
  787. variable defined in your ``settings.py`` file and creates a Django ``User``
  788. object the first time a user authenticates::
  789. from django.conf import settings
  790. from django.contrib.auth.models import User, check_password
  791. class SettingsBackend:
  792. """
  793. Authenticate against the settings ADMIN_LOGIN and ADMIN_PASSWORD.
  794. Use the login name, and a hash of the password. For example:
  795. ADMIN_LOGIN = 'admin'
  796. ADMIN_PASSWORD = 'sha1$4e987$afbcf42e21bd417fb71db8c66b321e9fc33051de'
  797. """
  798. def authenticate(self, username=None, password=None):
  799. login_valid = (settings.ADMIN_LOGIN == username)
  800. pwd_valid = check_password(password, settings.ADMIN_PASSWORD)
  801. if login_valid and pwd_valid:
  802. try:
  803. user = User.objects.get(username=username)
  804. except User.DoesNotExist:
  805. # Create a new user. Note that we can set password
  806. # to anything, because it won't be checked; the password
  807. # from settings.py will.
  808. user = User(username=username, password='get from settings.py')
  809. user.is_staff = True
  810. user.is_superuser = True
  811. user.save()
  812. return user
  813. return None
  814. def get_user(self, user_id):
  815. try:
  816. return User.objects.get(pk=user_id)
  817. except User.DoesNotExist:
  818. return None
  819. Handling authorization in custom backends
  820. -----------------------------------------
  821. Custom auth backends can provide their own permissions.
  822. The user model will delegate permission lookup functions
  823. (``get_group_permissions()``, ``get_all_permissions()``, ``has_perm()``, and
  824. ``has_module_perms()``) to any authentication backend that implements these
  825. functions.
  826. The permissions given to the user will be the superset of all permissions
  827. returned by all backends. That is, Django grants a permission to a user that any
  828. one backend grants.
  829. The simple backend above could implement permissions for the magic admin fairly
  830. simply::
  831. class SettingsBackend:
  832. # ...
  833. def has_perm(self, user_obj, perm):
  834. if user_obj.username == settings.ADMIN_LOGIN:
  835. return True
  836. else:
  837. return False
  838. This gives full permissions to the user granted access in the above example. Notice
  839. that the backend auth functions all take the user object as an argument, and
  840. they also accept the same arguments given to the associated ``User`` functions.
  841. A full authorization implementation can be found in
  842. ``django/contrib/auth/backends.py`` _, which is the default backend and queries
  843. the ``auth_permission`` table most of the time.
  844. .. _django/contrib/auth/backends.py: http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/backends.py