3
=============================
4
User authentication in Django
5
=============================
7
.. module:: django.contrib.auth
8
:synopsis: Django's authentication framework.
10
Django comes with a user authentication system. It handles user accounts,
11
groups, permissions and cookie-based user sessions. This document explains how
17
The auth system consists of:
20
* Permissions: Binary (yes/no) flags designating whether a user may perform
22
* Groups: A generic way of applying labels and permissions to more than one
24
* Messages: A simple way to queue messages for given users.
29
Authentication support is bundled as a Django application in
30
``django.contrib.auth``. To install it, do the following:
32
1. Put ``'django.contrib.auth'`` in your :setting:`INSTALLED_APPS` setting.
33
2. Run the command ``manage.py syncdb``.
35
Note that the default :file:`settings.py` file created by
36
:djadmin:`django-admin.py startproject` includes ``'django.contrib.auth'`` in
37
:setting:`INSTALLED_APPS` for convenience. If your :setting:`INSTALLED_APPS`
38
already contains ``'django.contrib.auth'``, feel free to run
39
:djadmin:`manage.py syncdb` again; you can run that command as many times as
40
you'd like, and each time it'll only install what's needed.
42
The :djadmin:`syncdb` command creates the necessary database tables, creates
43
permission objects for all installed apps that need 'em, and prompts you to
44
create a superuser account the first time you run it.
46
Once you've taken those steps, that's it.
51
.. class:: models.User
59
.. class:: models.User
61
:class:`~django.contrib.auth.models.User` objects have the following fields:
63
.. attribute:: models.User.username
65
Required. 30 characters or fewer. Alphanumeric characters only (letters,
66
digits and underscores).
68
.. attribute:: models.User.first_name
70
Optional. 30 characters or fewer.
72
.. attribute:: models.User.last_name
74
Optional. 30 characters or fewer.
76
.. attribute:: models.User.email
78
Optional. E-mail address.
80
.. attribute:: models.User.password
82
Required. A hash of, and metadata about, the password. (Django doesn't
83
store the raw password.) Raw passwords can be arbitrarily long and can
84
contain any character. See the "Passwords" section below.
86
.. attribute:: models.User.is_staff
88
Boolean. Designates whether this user can access the admin site.
90
.. attribute:: models.User.is_active
92
Boolean. Designates whether this account can be used to log in. Set this
93
flag to ``False`` instead of deleting accounts.
95
.. attribute:: models.User.is_superuser
97
Boolean. Designates that this user has all permissions without explicitly
100
.. attribute:: models.User.last_login
102
A datetime of the user's last login. Is set to the current date/time by
105
.. attribute:: models.User.date_joined
107
A datetime designating when the account was created. Is set to the current
108
date/time by default when the account is created.
113
.. class:: models.User
115
:class:`~django.contrib.auth.models.User` objects have two many-to-many
116
fields: models.User. ``groups`` and ``user_permissions``.
117
:class:`~django.contrib.auth.models.User` objects can access their related
118
objects in the same way as any other :ref:`Django model <topics-db-models>`:
120
.. code-block:: python
122
myuser.groups = [group_list]
123
myuser.groups.add(group, group, ...)
124
myuser.groups.remove(group, group, ...)
125
myuser.groups.clear()
126
myuser.user_permissions = [permission_list]
127
myuser.user_permissions.add(permission, permission, ...)
128
myuser.user_permissions.remove(permission, permission, ...)
129
myuser.user_permissions.clear()
131
In addition to those automatic API methods,
132
:class:`~django.contrib.auth.models.User` objects have the following custom
135
.. method:: models.User.is_anonymous()
137
Always returns ``False``. This is a way of differentiating
138
:class:`~django.contrib.auth.models.User` and
139
:class:`~django.contrib.auth.models.AnonymousUser` objects.
140
Generally, you should prefer using
141
:meth:`~django.contrib.auth.models.User.is_authenticated()` to this
144
.. method:: models.User.is_authenticated()
146
Always returns ``True``. This is a way to
147
tell if the user has been authenticated. This does not imply any
148
permissions, and doesn't check if the user is active - it only indicates
149
that the user has provided a valid username and password.
151
.. method:: models.User.get_full_name()
153
Returns the :attr:`~django.contrib.auth.models.User.first_name` plus the
154
:attr:`~django.contrib.auth.models.User.last_name`,
155
with a space in between.
157
.. method:: models.User.set_password(raw_password)
159
Sets the user's password to the given raw string, taking care of the
160
password hashing. Doesn't save the
161
:class:`~django.contrib.auth.models.User` object.
163
.. method:: models.User.check_password(raw_password)
165
Returns ``True`` if the given raw string is the correct password for the
166
user. (This takes care of the password hashing in making the comparison.)
168
.. method:: models.User.set_unusable_password()
170
.. versionadded:: 1.0
172
Marks the user as having no password set. This isn't the same as having
173
a blank string for a password.
174
:meth:`~django.contrib.auth.models.User.check_password()` for this user
175
will never return ``True``. Doesn't save the
176
:class:`~django.contrib.auth.models.User` object.
178
You may need this if authentication for your application takes place
179
against an existing external source such as an LDAP directory.
181
.. method:: models.User.has_usable_password()
183
.. versionadded:: 1.0
186
:meth:`~django.contrib.auth.models.User.set_unusable_password()` has
187
been called for this user.
189
.. method:: models.User.get_group_permissions()
191
Returns a list of permission strings that the user has, through his/her
194
.. method:: models.User.get_all_permissions()
196
Returns a list of permission strings that the user has, both through group
197
and user permissions.
199
.. method:: models.User.has_perm(perm)
201
Returns ``True`` if the user has the specified permission, where perm is
202
in the format ``"package.codename"``. If the user is inactive, this method
203
will always return ``False``.
205
.. method:: models.User.has_perms(perm_list)
207
Returns ``True`` if the user has each of the specified permissions, where
208
each perm is in the format ``"package.codename"``. If the user is inactive,
209
this method will always return ``False``.
211
.. method:: models.User.has_module_perms(package_name)
213
Returns ``True`` if the user has any permissions in the given package (the
214
Django app label). If the user is inactive, this method will always return
217
.. method:: models.User.get_and_delete_messages()
219
Returns a list of :class:`~django.contrib.auth.models.Message` objects in
220
the user's queue and deletes the messages from the queue.
222
.. method:: models.User.email_user(subject, message, from_email=None)
224
Sends an e-mail to the user. If
225
:attr:`~django.contrib.auth.models.User.from_email` is ``None``, Django
226
uses the :setting:`DEFAULT_FROM_EMAIL`.
228
.. method:: models.User.get_profile()
230
Returns a site-specific profile for this user. Raises
231
:exc:`django.contrib.auth.models.SiteProfileNotAvailable` if the current
232
site doesn't allow profiles. For information on how to define a
233
site-specific user profile, see the section on
234
`storing additional user information`_ below.
236
.. _storing additional user information: #storing-additional-information-about-users
241
.. class:: models.UserManager
243
The :class:`~django.contrib.auth.models.User` model has a custom manager
244
that has the following helper functions:
246
.. method:: models.UserManager.create_user(username, email, password=None)
248
Creates, saves and returns a :class:`~django.contrib.auth.models.User`.
249
The :attr:`~django.contrib.auth.models.User.username`,
250
:attr:`~django.contrib.auth.models.User.email` and
251
:attr:`~django.contrib.auth.models.User.password` are set as given, and the
252
:class:`~django.contrib.auth.models.User` gets ``is_active=True``.
254
If no password is provided,
255
:meth:`~django.contrib.auth.models.User.set_unusable_password()` will be
258
See `Creating users`_ for example usage.
260
.. method:: models.UserManager.make_random_password(length=10, allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789')
262
Returns a random password with the given length and given string of
263
allowed characters. (Note that the default value of ``allowed_chars``
264
doesn't contain letters that can cause user confusion, including ``1``,
270
.. _topics-auth-creating-users:
275
The most basic way to create users is to use the
276
:meth:`~django.contrib.auth.models.UserManager.create_user` helper function
277
that comes with Django::
279
>>> from django.contrib.auth.models import User
280
>>> user = User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword')
282
# At this point, user is a User object that has already been saved
283
# to the database. You can continue to change its attributes
284
# if you want to change other fields.
285
>>> user.is_staff = True
291
Change a password with :meth:`~django.contrib.auth.models.User.set_password()`::
293
>>> from django.contrib.auth.models import User
294
>>> u = User.objects.get(username__exact='john')
295
>>> u.set_password('new password')
298
Don't set the :attr:`~django.contrib.auth.models.User.password` attribute
299
directly unless you know what you're doing. This is explained in the next
305
The :attr:`~django.contrib.auth.models.User.password` attribute of a
306
:class:`~django.contrib.auth.models.User` object is a string in this format::
310
That's hashtype, salt and hash, separated by the dollar-sign character.
312
Hashtype is either ``sha1`` (default), ``md5`` or ``crypt`` -- the algorithm
313
used to perform a one-way hash of the password. Salt is a random string used
314
to salt the raw password to create the hash. Note that the ``crypt`` method is
315
only supported on platforms that have the standard Python ``crypt`` module
316
available, and ``crypt`` support is only available in the Django development
321
sha1$a1976$a36cc8cbf81742a8fb52e221aaeab48ed7f58ab4
323
The :meth:`~django.contrib.auth.models.User.set_password` and
324
:meth:`~django.contrib.auth.models.User.check_password` functions handle the
325
setting and checking of these values behind the scenes.
327
Previous Django versions, such as 0.90, used simple MD5 hashes without password
328
salts. For backwards compatibility, those are still supported; they'll be
329
converted automatically to the new style the first time
330
:meth:`~django.contrib.auth.models.User.check_password()` works correctly for
336
.. class:: models.AnonymousUser
338
:class:`django.contrib.auth.models.AnonymousUser` is a class that
339
implements the :class:`django.contrib.auth.models.User` interface, with
342
* :attr:`~django.contrib.auth.models.User.id` is always ``None``.
343
* :attr:`~django.contrib.auth.models.User.is_staff` and
344
:attr:`~django.contrib.auth.models.User.is_superuser` are always ``False``.
345
* :attr:`~django.contrib.auth.models.User.is_active` is always ``False``.
346
* :attr:`~django.contrib.auth.models.User.groups` and
347
:attr:`~django.contrib.auth.models.User.user_permissions` are always empty.
348
* :meth:`~django.contrib.auth.models.User.is_anonymous()` returns ``True``
349
instead of ``False``.
350
* :meth:`~django.contrib.auth.models.User.is_authenticated()` returns
351
``False`` instead of ``True``.
352
* :meth:`~django.contrib.auth.models.User.has_perm()` always returns ``False``.
353
* :meth:`~django.contrib.auth.models.User.set_password()`,
354
:meth:`~django.contrib.auth.models.User.check_password()`,
355
:meth:`~django.contrib.auth.models.User.save()`,
356
:meth:`~django.contrib.auth.models.User.delete()`,
357
:meth:`~django.contrib.auth.models.User.set_groups()` and
358
:meth:`~django.contrib.auth.models.User.set_permissions()` raise
359
:exc:`NotImplementedError`.
361
In practice, you probably won't need to use
362
:class:`~django.contrib.auth.models.AnonymousUser` objects on your own, but
363
they're used by Web requests, as explained in the next section.
368
.. versionadded:: 1.0
369
The ``manage.py createsuperuser`` command is new.
371
:djadmin:`manage.py syncdb <syncdb>` prompts you to create a superuser the first time
372
you run it after adding ``'django.contrib.auth'`` to your
373
:setting:`INSTALLED_APPS`. If you need to create a superuser at a later date,
374
you can use a command line utility.
376
manage.py createsuperuser --username=joe --email=joe@example.com
378
You will be prompted for a password. After you enter one, the user will be
379
created immediately. If you leave off the :djadminopt:`--username` or the
380
:djadminopt:`--email` options, it will prompt you for those values.
382
If you're using an older release of Django, the old way of creating a superuser
383
on the command line still works::
385
python /path/to/django/contrib/auth/create_superuser.py
387
...where :file:`/path/to` is the path to the Django codebase on your
388
filesystem. The ``manage.py`` command is preferred because it figures
389
out the correct path and environment for you.
393
Storing additional information about users
394
------------------------------------------
396
If you'd like to store additional information related to your users,
397
Django provides a method to specify a site-specific related model --
398
termed a "user profile" -- for this purpose.
400
To make use of this feature, define a model with fields for the
401
additional information you'd like to store, or additional methods
402
you'd like to have available, and also add a
403
:class:`~django.db.models.Field.ForeignKey` from your model to the
404
:class:`~django.contrib.auth.models.User` model, specified with ``unique=True``
405
to ensure only one instance of your model can be created for each
406
:class:`~django.contrib.auth.models.User`.
408
To indicate that this model is the user profile model for a given
409
site, fill in the setting :setting:`AUTH_PROFILE_MODULE` with a string
410
consisting of the following items, separated by a dot:
412
1. The (normalized to lower-case) name of the application in which the
413
user profile model is defined (in other words, an all-lowercase
414
version of the name which was passed to
415
:djadmin:`manage.py startapp <startapp>` to create the application).
417
2. The (normalized to lower-case) name of the model class.
419
For example, if the profile model was a class named ``UserProfile``
420
and was defined inside an application named ``accounts``, the
421
appropriate setting would be::
423
AUTH_PROFILE_MODULE = 'accounts.userprofile'
425
When a user profile model has been defined and specified in this
426
manner, each :class:`~django.contrib.auth.models.User` object will have a
427
method -- :class:`~django.contrib.auth.models.User.get_profile()`
428
-- which returns the instance of the user profile model associated
429
with that :class:`~django.contrib.auth.models.User`.
431
For more information, see `Chapter 12 of the Django book`_.
433
.. _Chapter 12 of the Django book: http://www.djangobook.com/en/1.0/chapter12/#cn222
435
Authentication in Web requests
436
==============================
438
Until now, this document has dealt with the low-level APIs for manipulating
439
authentication-related objects. On a higher level, Django can hook this
440
authentication framework into its system of
441
:class:`request objects <django.http.HttpRequest>`.
444
:class:`~django.contrib.sessions.middleware.SessionMiddleware` and
445
:class:`~django.contrib.auth.middleware.AuthenticationMiddleware`
446
middlewares by adding them to your :setting:`MIDDLEWARE_CLASSES` setting. See
447
the :ref:`session documentation <topics-http-sessions>` for more information.
449
Once you have those middlewares installed, you'll be able to access
450
:attr:`request.user <django.http.HttpRequest.user>` in views.
451
:attr:`request.user <django.http.HttpRequest.user>` will give you a
452
:class:`~django.contrib.auth.models.User` object representing the currently
453
logged-in user. If a user isn't currently logged in,
454
:attr:`request.user <django.http.HttpRequest.user>` will be set to an instance
455
of :class:`~django.contrib.auth.models.AnonymousUser` (see the previous
456
section). You can tell them apart with
457
:meth:`~django.contrib.auth.models.User.is_authenticated()`, like so::
459
if request.user.is_authenticated():
460
# Do something for authenticated users.
462
# Do something for anonymous users.
467
Django provides two functions in :mod:`django.contrib.auth`:
468
:func:`~django.contrib.auth.authenticate()` and
469
:func:`~django.contrib.auth.login()`.
471
.. function:: authenticate()
473
To authenticate a given username and password, use
474
:func:`~django.contrib.auth.authenticate()`. It
475
takes two keyword arguments, ``username`` and ``password``, and it returns
476
a :class:`~django.contrib.auth.models.User` object if the password is
477
valid for the given username. If the password is invalid,
478
:func:`~django.contrib.auth.authenticate()` returns ``None``. Example::
480
from django.contrib.auth import authenticate
481
user = authenticate(username='john', password='secret')
484
print "You provided a correct username and password!"
486
print "Your account has been disabled!"
488
print "Your username and password were incorrect."
490
.. function:: login()
492
To log a user in, in a view, use :func:`~django.contrib.auth.login()`. It
493
takes an :class:`~django.http.HttpRequest` object and a
494
:class:`~django.contrib.auth.models.User` object.
495
:func:`~django.contrib.auth.login()` saves the user's ID in the session,
496
using Django's session framework, so, as mentioned above, you'll need to
497
make sure to have the session middleware installed.
499
This example shows how you might use both
500
:func:`~django.contrib.auth.authenticate()` and
501
:func:`~django.contrib.auth.login()`::
503
from django.contrib.auth import authenticate, login
505
def my_view(request):
506
username = request.POST['username']
507
password = request.POST['password']
508
user = authenticate(username=username, password=password)
512
# Redirect to a success page.
514
# Return a 'disabled account' error message
516
# Return an 'invalid login' error message.
518
.. admonition:: Calling ``authenticate()`` first
520
When you're manually logging a user in, you *must* call
521
:func:`~django.contrib.auth.authenticate()` before you call
522
:func:`~django.contrib.auth.login()`.
523
:func:`~django.contrib.auth.authenticate()`
524
sets an attribute on the :class:`~django.contrib.auth.models.User` noting
525
which authentication backend successfully authenticated that user (see
526
the `backends documentation`_ for details), and this information is
527
needed later during the login process.
529
.. _backends documentation: #other-authentication-sources
531
Manually checking a user's password
532
-----------------------------------
534
.. function:: check_password()
536
If you'd like to manually authenticate a user by comparing a
537
plain-text password to the hashed password in the database, use the
538
convenience function :func:`django.contrib.auth.models.check_password`. It
539
takes two arguments: the plain-text password to check, and the full
540
value of a user's ``password`` field in the database to check against,
541
and returns ``True`` if they match, ``False`` otherwise.
543
How to log a user out
544
---------------------
546
.. function:: logout()
548
To log out a user who has been logged in via
549
:func:`django.contrib.auth.login()`, use
550
:func:`django.contrib.auth.logout()` within your view. It takes an
551
:class:`~django.http.HttpRequest` object and has no return value.
554
from django.contrib.auth import logout
556
def logout_view(request):
558
# Redirect to a success page.
560
Note that :func:`~django.contrib.auth.logout()` doesn't throw any errors
561
if the user wasn't logged in.
563
.. versionchanged:: 1.0
564
Calling ``logout()`` now cleans session data.
566
When you call :func:`~django.contrib.auth.logout()`, the session
567
data for the current request is completely cleaned out. All existing data
568
is removed. This is to prevent another person from using the same web
569
browser to log in and have access to the previous user's session data.
570
If you want to put anything into the session that will be available to
571
the user immediately after logging out, do that *after* calling
572
:func:`django.contrib.auth.logout()`.
574
Limiting access to logged-in users
575
----------------------------------
580
The simple, raw way to limit access to pages is to check
581
:meth:`request.user.is_authenticated()
582
<django.contrib.auth.models.User.is_authenticated()>` and either redirect to a
585
from django.http import HttpResponseRedirect
587
def my_view(request):
588
if not request.user.is_authenticated():
589
return HttpResponseRedirect('/login/?next=%s' % request.path)
592
...or display an error message::
594
def my_view(request):
595
if not request.user.is_authenticated():
596
return render_to_response('myapp/login_error.html')
599
The login_required decorator
600
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
602
.. function:: decorators.login_required()
604
As a shortcut, you can use the convenient
605
:func:`~django.contrib.auth.decorators.login_required` decorator::
607
from django.contrib.auth.decorators import login_required
609
def my_view(request):
611
my_view = login_required(my_view)
613
Here's an equivalent example, using the more compact decorator syntax
614
introduced in Python 2.4::
616
from django.contrib.auth.decorators import login_required
619
def my_view(request):
622
In the Django development version,
623
:func:`~django.contrib.auth.decorators.login_required` also takes an
624
optional ``redirect_field_name`` parameter. Example::
626
from django.contrib.auth.decorators import login_required
628
def my_view(request):
630
my_view = login_required(redirect_field_name='redirect_to')(my_view)
632
Again, an equivalent example of the more compact decorator syntax
633
introduced in Python 2.4::
635
from django.contrib.auth.decorators import login_required
637
@login_required(redirect_field_name='redirect_to')
638
def my_view(request):
641
:func:`~django.contrib.auth.decorators.login_required` does the following:
643
* If the user isn't logged in, redirect to
644
:setting:`settings.LOGIN_URL <LOGIN_URL>` (``/accounts/login/`` by
645
default), passing the current absolute URL in the query string as
646
``next`` or the value of ``redirect_field_name``. For example:
647
``/accounts/login/?next=/polls/3/``.
649
* If the user is logged in, execute the view normally. The view code
650
is free to assume the user is logged in.
652
Note that you'll need to map the appropriate Django view to
653
:setting:`settings.LOGIN_URL <LOGIN_URL>`. For example, using the defaults, add
654
the following line to your URLconf::
656
(r'^accounts/login/$', 'django.contrib.auth.views.login'),
658
.. function:: views.login()
660
Here's what ``django.contrib.auth.views.login`` does:
662
* If called via ``GET``, it displays a login form that POSTs to the same
663
URL. More on this in a bit.
665
* If called via ``POST``, it tries to log the user in. If login is
666
successful, the view redirects to the URL specified in ``next``. If
667
``next`` isn't provided, it redirects to :setting:`settings.LOGIN_REDIRECT_URL <LOGIN_REDIRECT_URL>`
668
(which defaults to ``/accounts/profile/``). If login isn't successful,
669
it redisplays the login form.
671
It's your responsibility to provide the login form in a template called
672
``registration/login.html`` by default. This template gets passed three
673
template context variables:
675
* ``form``: A :class:`~django.forms.Form` object representing the
676
login form. See the :ref:`forms documentation <topics-forms-index>`
677
for more on ``FormWrapper`` objects.
679
* ``next``: The URL to redirect to after successful login. This may contain
682
* ``site_name``: The name of the current
683
:class:`~django.contrib.sites.models.Site``, according to the
684
:setting:`SITE_ID` setting. If you're using the Django development version
685
and you don't have the site framework installed, this will be set to the
686
value of ``request.META['SERVER_NAME']``. For more on sites, see
687
:ref:`ref-contrib-sites`.
689
If you'd prefer not to call the template :file:`registration/login.html`,
690
you can pass the ``template_name`` parameter via the extra arguments to
691
the view in your URLconf. For example, this URLconf line would use
692
:file:`myapp/login.html` instead::
694
(r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'myapp/login.html'}),
696
Here's a sample :file:`registration/login.html` template you can use as a
697
starting point. It assumes you have a :file:`base.html` template that
698
defines a ``content`` block::
700
{% extends "base.html" %}
705
<p>Your username and password didn't match. Please try again.</p>
708
<form method="post" action=".">
710
<tr><td>{{ form.username.label_tag }}</td><td>{{ form.username }}</td></tr>
711
<tr><td>{{ form.password.label_tag }}</td><td>{{ form.password }}</td></tr>
714
<input type="submit" value="login" />
715
<input type="hidden" name="next" value="{{ next }}" />
720
.. _forms documentation: ../forms/
721
.. _site framework docs: ../sites/
726
In addition to the ``login`` view, the authentication system includes a
727
few other useful built-in views:
729
.. function:: django.contrib.auth.views.logout
733
**Optional arguments:**
735
* ``template_name``: The full name of a template to display after
736
logging the user out. This will default to
737
:file:`registration/logged_out.html` if no argument is supplied.
739
**Template context:**
741
* ``title``: The string "Logged out", localized.
743
.. function:: django.contrib.auth.views.logout_then_login
745
Logs a user out, then redirects to the login page.
747
**Optional arguments:**
749
* ``login_url``: The URL of the login page to redirect to. This
750
will default to :setting:`settings.LOGIN_URL <LOGIN_URL>` if not
753
.. function:: django.contrib.auth.views.password_change
755
Allows a user to change their password.
757
**Optional arguments:**
759
* ``template_name``: The full name of a template to use for
760
displaying the password change form. This will default to
761
:file:`registration/password_change_form.html` if not supplied.
763
**Template context:**
765
* ``form``: The password change form.
767
.. function:: django.contrib.auth.views.password_change_done
769
The page shown after a user has changed their password.
771
**Optional arguments:**
773
* ``template_name``: The full name of a template to use. This will
774
default to :file:`registration/password_change_done.html` if not
777
.. function:: django.contrib.auth.views.password_reset
779
Allows a user to reset their password, and sends them the new password
782
**Optional arguments:**
784
* ``template_name``: The full name of a template to use for
785
displaying the password reset form. This will default to
786
:file:`registration/password_reset_form.html` if not supplied.
788
* ``email_template_name``: The full name of a template to use for
789
generating the e-mail with the new password. This will default to
790
:file:`registration/password_reset_email.html` if not supplied.
792
**Template context:**
794
* ``form``: The form for resetting the user's password.
796
.. function:: django.contrib.auth.views.password_reset_done
798
The page shown after a user has reset their password.
800
**Optional arguments:**
802
* ``template_name``: The full name of a template to use. This will
803
default to :file:`registration/password_reset_done.html` if not
806
.. function:: django.contrib.auth.views.redirect_to_login
808
Redirects to the login page, and then back to another URL after a
811
**Required arguments:**
813
* ``next``: The URL to redirect to after a successful login.
815
**Optional arguments:**
817
* ``login_url``: The URL of the login page to redirect to. This
818
will default to :setting:`settings.LOGIN_URL <LOGIN_URL>` if not
822
---------------------
824
If you don't want to use the built-in views, but want the convenience
825
of not having to write forms for this functionality, the authentication
826
system provides several built-in forms:
828
* :class:`django.contrib.auth.forms.AdminPasswordChangeForm`: A form used
829
in the admin interface to change a user's password.
831
* :class:`django.contrib.auth.forms.AuthenticationForm`: A form for
834
* :class:`django.contrib.auth.forms.PasswordChangeForm`: A form for
835
allowing a user to change their password.
837
* :class:`django.contrib.auth.forms.PasswordResetForm`: A form for
838
resetting a user's password and e-mailing the new password to them.
840
* :class:`django.contrib.auth.forms.UserCreationForm`: A form for creating
843
Limiting access to logged-in users that pass a test
844
---------------------------------------------------
846
To limit access based on certain permissions or some other test, you'd do
847
essentially the same thing as described in the previous section.
849
The simple way is to run your test on
850
:attr:`request.user <django.http.HttpRequest.user>` in the view directly.
851
For example, this view checks to make sure the user is logged in and has the
852
permission ``polls.can_vote``::
854
def my_view(request):
855
if not (request.user.is_authenticated() and request.user.has_perm('polls.can_vote')):
856
return HttpResponse("You can't vote in this poll.")
859
.. function:: decorators.user_passes_test()
861
As a shortcut, you can use the convenient ``user_passes_test`` decorator::
863
from django.contrib.auth.decorators import user_passes_test
865
def my_view(request):
867
my_view = user_passes_test(lambda u: u.has_perm('polls.can_vote'))(my_view)
869
We're using this particular test as a relatively simple example. However,
870
if you just want to test whether a permission is available to a user, you
871
can use the :func:`django.contrib.auth.decorators.permission_required()`
872
decorator, described later in this document.
874
Here's the same thing, using Python 2.4's decorator syntax::
876
from django.contrib.auth.decorators import user_passes_test
878
@user_passes_test(lambda u: u.has_perm('polls.can_vote'))
879
def my_view(request):
882
:func:`~django.contrib.auth.decorators.user_passes_test` takes a required
883
argument: a callable that takes a
884
:class:`~django.contrib.auth.models.User` object and returns ``True`` if
885
the user is allowed to view the page. Note that
886
:func:`~django.contrib.auth.decorators.user_passes_test` does not
887
automatically check that the :class:`~django.contrib.auth.models.User` is
890
:func:`~django.contrib.auth.decorators.user_passes_test()` takes an
891
optional ``login_url`` argument, which lets you specify the URL for your
892
login page (:setting:`settings.LOGIN_URL <LOGIN_URL>` by default).
894
Example in Python 2.3 syntax::
896
from django.contrib.auth.decorators import user_passes_test
898
def my_view(request):
900
my_view = user_passes_test(lambda u: u.has_perm('polls.can_vote'), login_url='/login/')(my_view)
902
Example in Python 2.4 syntax::
904
from django.contrib.auth.decorators import user_passes_test
906
@user_passes_test(lambda u: u.has_perm('polls.can_vote'), login_url='/login/')
907
def my_view(request):
910
The permission_required decorator
911
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
913
.. function:: decorators.permission_required()
915
It's a relatively common task to check whether a user has a particular
916
permission. For that reason, Django provides a shortcut for that case: the
917
:func:`~django.contrib.auth.decorators.permission_required()` decorator.
918
Using this decorator, the earlier example can be written as::
920
from django.contrib.auth.decorators import permission_required
922
def my_view(request):
924
my_view = permission_required('polls.can_vote')(my_view)
926
Note that :func:`~django.contrib.auth.decorators.permission_required()`
927
also takes an optional ``login_url`` parameter. Example::
929
from django.contrib.auth.decorators import permission_required
931
def my_view(request):
933
my_view = permission_required('polls.can_vote', login_url='/loginpage/')(my_view)
935
As in the ``login_required`` decorator, ``login_url`` defaults to
936
:setting:`settings.LOGIN_URL <LOGIN_URL>`.
938
Limiting access to generic views
939
--------------------------------
941
To limit access to a :ref:`generic view <ref-generic-views>`, write a thin
942
wrapper around the view, and point your URLconf to your wrapper instead of the
943
generic view itself. For example::
945
from django.views.generic.date_based import object_detail
948
def limited_object_detail(*args, **kwargs):
949
return object_detail(*args, **kwargs)
954
Django comes with a simple permissions system. It provides a way to assign
955
permissions to specific users and groups of users.
957
It's used by the Django admin site, but you're welcome to use it in your own
960
The Django admin site uses permissions as follows:
962
* Access to view the "add" form and add an object is limited to users with
963
the "add" permission for that type of object.
964
* Access to view the change list, view the "change" form and change an
965
object is limited to users with the "change" permission for that type of
967
* Access to delete an object is limited to users with the "delete"
968
permission for that type of object.
970
Permissions are set globally per type of object, not per specific object
971
instance. For example, it's possible to say "Mary may change news stories," but
972
it's not currently possible to say "Mary may change news stories, but only the
973
ones she created herself" or "Mary may only change news stories that have a
974
certain status, publication date or ID." The latter functionality is something
975
Django developers are currently discussing.
980
When ``django.contrib.auth`` is listed in your :setting:`INSTALLED_APPS`
981
setting, it will ensure that three default permissions -- add, change
982
and delete -- are created for each Django model defined in one of your
983
installed applications.
985
These permissions will be created when you run
986
:djadmin:`manage.py syncdb <syncdb>`; the first time you run ``syncdb`` after
987
adding ``django.contrib.auth`` to :setting:`INSTALLED_APPS`, the default
988
permissions will be created for all previously-installed models, as well as
989
for any new models being installed at that time. Afterward, it will create
990
default permissions for new models each time you run
991
:djadmin:`manage.py syncdb <syncdb>`.
993
.. _custom-permissions:
998
To create custom permissions for a given model object, use the ``permissions``
999
:ref:`model Meta attribute <meta-options>`.
1001
This example model creates three custom permissions::
1003
class USCitizen(models.Model):
1007
("can_drive", "Can drive"),
1008
("can_vote", "Can vote in elections"),
1009
("can_drink", "Can drink alcohol"),
1012
The only thing this does is create those extra permissions when you run
1013
:djadmin:`manage.py syncdb <syncdb>`.
1018
.. class:: models.Permission
1020
Just like users, permissions are implemented in a Django model that lives in
1021
`django/contrib/auth/models.py`_.
1023
.. _django/contrib/auth/models.py: http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/models.py
1028
:class:`~django.contrib.auth.models.Permission` objects have the following
1031
.. attribute:: models.Permission.name
1033
Required. 50 characters or fewer. Example: ``'Can vote'``.
1035
.. attribute:: models.Permission.content_type
1037
Required. A reference to the ``django_content_type`` database table,
1038
which contains a record for each installed Django model.
1040
.. attribute:: models.Permission.codename
1042
Required. 100 characters or fewer. Example: ``'can_vote'``.
1047
:class:`~django.contrib.auth.models.Permission` objects have the standard
1048
data-access methods like any other :ref:`Django model <ref-models-instances>`.
1050
Authentication data in templates
1051
================================
1053
The currently logged-in user and his/her permissions are made available in the
1054
:ref:`template context <ref-templates-api>` when you use
1055
:class:`~django.template.context.RequestContext`.
1057
.. admonition:: Technicality
1059
Technically, these variables are only made available in the template context
1060
if you use :class:`~django.template.context.RequestContext` *and* your
1061
:setting:`TEMPLATE_CONTEXT_PROCESSORS` setting contains
1062
``"django.core.context_processors.auth"``, which is default. For more, see
1063
the :ref:`RequestContext docs <subclassing-context-requestcontext>`.
1068
The currently logged-in user, either a
1069
:class:`~django.contrib.auth.models.User` instance or an
1070
:class:`~django.contrib.auth.models.AnonymousUser` instance, is stored in the
1071
template variable ``{{ user }}``::
1073
{% if user.is_authenticated %}
1074
<p>Welcome, {{ user.username }}. Thanks for logging in.</p>
1076
<p>Welcome, new user. Please log in.</p>
1082
The currently logged-in user's permissions are stored in the template variable
1083
``{{ perms }}``. This is an instance of
1084
:class:`django.core.context_processors.PermWrapper`, which is a
1085
template-friendly proxy of permissions.
1087
In the ``{{ perms }}`` object, single-attribute lookup is a proxy to
1088
:meth:`User.has_module_perms <django.contrib.auth.models.User.has_module_perms>`.
1089
This example would display ``True`` if the logged-in user had any permissions
1090
in the ``foo`` app::
1094
Two-level-attribute lookup is a proxy to
1095
:meth:`User.has_perm <django.contrib.auth.models.User.has_perm>`. This example
1096
would display ``True`` if the logged-in user had the permission
1099
{{ perms.foo.can_vote }}
1101
Thus, you can check permissions in template ``{% if %}`` statements::
1104
<p>You have permission to do something in the foo app.</p>
1105
{% if perms.foo.can_vote %}
1106
<p>You can vote!</p>
1108
{% if perms.foo.can_drive %}
1109
<p>You can drive!</p>
1112
<p>You don't have permission to do anything in the foo app.</p>
1118
Groups are a generic way of categorizing users so you can apply permissions, or
1119
some other label, to those users. A user can belong to any number of groups.
1121
A user in a group automatically has the permissions granted to that group. For
1122
example, if the group ``Site editors`` has the permission
1123
``can_edit_home_page``, any user in that group will have that permission.
1125
Beyond permissions, groups are a convenient way to categorize users to give
1126
them some label, or extended functionality. For example, you could create a
1127
group ``'Special users'``, and you could write code that could, say, give them
1128
access to a members-only portion of your site, or send them members-only e-mail
1134
The message system is a lightweight way to queue messages for given users.
1136
A message is associated with a :class:`~django.contrib.auth.models.User`.
1137
There's no concept of expiration or timestamps.
1139
Messages are used by the Django admin after successful actions. For example,
1140
``"The poll Foo was created successfully."`` is a message.
1144
.. method:: models.User.message_set.create(message)
1146
To create a new message, use
1147
``user_obj.message_set.create(message='message_text')``.
1149
To retrieve/delete messages, use
1150
:meth:`user_obj.get_and_delete_messages() <django.contrib.auth.models.User.get_and_delete_messages>`,
1151
which returns a list of ``Message`` objects in the user's queue (if any)
1152
and deletes the messages from the queue.
1154
In this example view, the system saves a message for the user after creating
1157
def create_playlist(request, songs):
1158
# Create the playlist with the given songs.
1160
request.user.message_set.create(message="Your playlist was added successfully.")
1161
return render_to_response("playlists/create.html",
1162
context_instance=RequestContext(request))
1164
When you use :class:`~django.template.context.RequestContext`, the currently
1165
logged-in user and his/her messages are made available in the
1166
:ref:`template context <ref-templates-api>` as the template variable
1167
``{{ messages }}``. Here's an example of template code that displays messages::
1171
{% for message in messages %}
1172
<li>{{ message }}</li>
1177
Note that :class:`~django.template.context.RequestContext` calls
1178
:meth:`~django.contrib.auth.models.User.get_and_delete_messages` behind the
1179
scenes, so any messages will be deleted even if you don't display them.
1181
Finally, note that this messages framework only works with users in the user
1182
database. To send messages to anonymous users, use the
1183
:ref:`session framework <topics-http-sessions>`.
1185
.. _authentication-backends:
1187
Other authentication sources
1188
============================
1190
The authentication that comes with Django is good enough for most common cases,
1191
but you may have the need to hook into another authentication source -- that
1192
is, another source of usernames and passwords or authentication methods.
1194
For example, your company may already have an LDAP setup that stores a username
1195
and password for every employee. It'd be a hassle for both the network
1196
administrator and the users themselves if users had separate accounts in LDAP
1197
and the Django-based applications.
1199
So, to handle situations like this, the Django authentication system lets you
1200
plug in another authentication sources. You can override Django's default
1201
database-based scheme, or you can use the default system in tandem with other
1204
Specifying authentication backends
1205
----------------------------------
1207
Behind the scenes, Django maintains a list of "authentication backends" that it
1208
checks for authentication. When somebody calls
1209
:func:`django.contrib.auth.authenticate()` -- as described in "How to log a
1210
user in" above -- Django tries authenticating across all of its authentication
1211
backends. If the first authentication method fails, Django tries the second
1212
one, and so on, until all backends have been attempted.
1214
The list of authentication backends to use is specified in the
1215
:setting:`AUTHENTICATION_BACKENDS` setting. This should be a tuple of Python
1216
path names that point to Python classes that know how to authenticate. These
1217
classes can be anywhere on your Python path.
1219
By default, :setting:`AUTHENTICATION_BACKENDS` is set to::
1221
('django.contrib.auth.backends.ModelBackend',)
1223
That's the basic authentication scheme that checks the Django users database.
1225
The order of :setting:`AUTHENTICATION_BACKENDS` matters, so if the same username
1226
and password is valid in multiple backends, Django will stop processing at the
1227
first positive match.
1229
Writing an authentication backend
1230
---------------------------------
1232
An authentication backend is a class that implements two methods:
1233
``get_user(user_id)`` and ``authenticate(**credentials)``.
1235
The ``get_user`` method takes a ``user_id`` -- which could be a username,
1236
database ID or whatever -- and returns a ``User`` object.
1238
The ``authenticate`` method takes credentials as keyword arguments. Most of
1239
the time, it'll just look like this::
1242
def authenticate(self, username=None, password=None):
1243
# Check the username/password and return a User.
1245
But it could also authenticate a token, like so::
1248
def authenticate(self, token=None):
1249
# Check the token and return a User.
1251
Either way, ``authenticate`` should check the credentials it gets, and it
1252
should return a ``User`` object that matches those credentials, if the
1253
credentials are valid. If they're not valid, it should return ``None``.
1255
The Django admin system is tightly coupled to the Django ``User`` object
1256
described at the beginning of this document. For now, the best way to deal with
1257
this is to create a Django ``User`` object for each user that exists for your
1258
backend (e.g., in your LDAP directory, your external SQL database, etc.) You
1259
can either write a script to do this in advance, or your ``authenticate``
1260
method can do it the first time a user logs in.
1262
Here's an example backend that authenticates against a username and password
1263
variable defined in your ``settings.py`` file and creates a Django ``User``
1264
object the first time a user authenticates::
1266
from django.conf import settings
1267
from django.contrib.auth.models import User, check_password
1269
class SettingsBackend:
1271
Authenticate against the settings ADMIN_LOGIN and ADMIN_PASSWORD.
1273
Use the login name, and a hash of the password. For example:
1275
ADMIN_LOGIN = 'admin'
1276
ADMIN_PASSWORD = 'sha1$4e987$afbcf42e21bd417fb71db8c66b321e9fc33051de'
1278
def authenticate(self, username=None, password=None):
1279
login_valid = (settings.ADMIN_LOGIN == username)
1280
pwd_valid = check_password(password, settings.ADMIN_PASSWORD)
1281
if login_valid and pwd_valid:
1283
user = User.objects.get(username=username)
1284
except User.DoesNotExist:
1285
# Create a new user. Note that we can set password
1286
# to anything, because it won't be checked; the password
1287
# from settings.py will.
1288
user = User(username=username, password='get from settings.py')
1289
user.is_staff = True
1290
user.is_superuser = True
1295
def get_user(self, user_id):
1297
return User.objects.get(pk=user_id)
1298
except User.DoesNotExist:
1301
Handling authorization in custom backends
1302
-----------------------------------------
1304
Custom auth backends can provide their own permissions.
1306
The user model will delegate permission lookup functions
1307
(:meth:`~django.contrib.auth.models.User.get_group_permissions()`,
1308
:meth:`~django.contrib.auth.models.User.get_all_permissions()`,
1309
:meth:`~django.contrib.auth.models.User.has_perm()`, and
1310
:meth:`~django.contrib.auth.models.User.has_module_perms()`) to any
1311
authentication backend that implements these functions.
1313
The permissions given to the user will be the superset of all permissions
1314
returned by all backends. That is, Django grants a permission to a user that
1315
any one backend grants.
1317
The simple backend above could implement permissions for the magic admin
1320
class SettingsBackend:
1324
def has_perm(self, user_obj, perm):
1325
if user_obj.username == settings.ADMIN_LOGIN:
1330
This gives full permissions to the user granted access in the above example.
1331
Notice that the backend auth functions all take the user object as an argument,
1332
and they also accept the same arguments given to the associated
1333
:class:`django.contrib.auth.models.User` functions.
1335
A full authorization implementation can be found in
1336
`django/contrib/auth/backends.py`_, which is the default backend and queries
1337
the ``auth_permission`` table most of the time.
1339
.. _django/contrib/auth/backends.py: http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/backends.py