~ubuntu-branches/ubuntu/quantal/python-django/quantal

« back to all changes in this revision

Viewing changes to docs/topics/auth.txt

  • Committer: Bazaar Package Importer
  • Author(s): Scott James Remnant, Eddy Mulyono
  • Date: 2008-09-16 12:18:47 UTC
  • mfrom: (1.1.5 upstream) (4.1.1 lenny)
  • Revision ID: james.westby@ubuntu.com-20080916121847-mg225rg5mnsdqzr0
Tags: 1.0-1ubuntu1
* Merge from Debian (LP: #264191), remaining changes:
  - Run test suite on build.

[Eddy Mulyono]
* Update patch to workaround network test case failures.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
.. _topics-auth:
 
2
 
 
3
=============================
 
4
User authentication in Django
 
5
=============================
 
6
 
 
7
.. module:: django.contrib.auth
 
8
   :synopsis: Django's authentication framework.
 
9
 
 
10
Django comes with a user authentication system. It handles user accounts,
 
11
groups, permissions and cookie-based user sessions. This document explains how
 
12
things work.
 
13
 
 
14
Overview
 
15
========
 
16
 
 
17
The auth system consists of:
 
18
 
 
19
    * Users
 
20
    * Permissions: Binary (yes/no) flags designating whether a user may perform
 
21
      a certain task.
 
22
    * Groups: A generic way of applying labels and permissions to more than one
 
23
      user.
 
24
    * Messages: A simple way to queue messages for given users.
 
25
 
 
26
Installation
 
27
============
 
28
 
 
29
Authentication support is bundled as a Django application in
 
30
``django.contrib.auth``. To install it, do the following:
 
31
 
 
32
    1. Put ``'django.contrib.auth'`` in your :setting:`INSTALLED_APPS` setting.
 
33
    2. Run the command ``manage.py syncdb``.
 
34
 
 
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.
 
41
 
 
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.
 
45
 
 
46
Once you've taken those steps, that's it.
 
47
 
 
48
Users
 
49
=====
 
50
 
 
51
.. class:: models.User
 
52
 
 
53
API reference
 
54
-------------
 
55
 
 
56
Fields
 
57
~~~~~~
 
58
 
 
59
.. class:: models.User
 
60
 
 
61
    :class:`~django.contrib.auth.models.User` objects have the following fields:
 
62
 
 
63
    .. attribute:: models.User.username
 
64
 
 
65
        Required. 30 characters or fewer. Alphanumeric characters only (letters,
 
66
        digits and underscores).
 
67
 
 
68
    .. attribute:: models.User.first_name
 
69
 
 
70
        Optional. 30 characters or fewer.
 
71
 
 
72
    .. attribute:: models.User.last_name
 
73
 
 
74
        Optional. 30 characters or fewer.
 
75
 
 
76
    .. attribute:: models.User.email
 
77
 
 
78
        Optional. E-mail address.
 
79
 
 
80
    .. attribute:: models.User.password
 
81
 
 
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.
 
85
 
 
86
    .. attribute:: models.User.is_staff
 
87
 
 
88
        Boolean. Designates whether this user can access the admin site.
 
89
 
 
90
    .. attribute:: models.User.is_active
 
91
 
 
92
        Boolean. Designates whether this account can be used to log in. Set this
 
93
        flag to ``False`` instead of deleting accounts.
 
94
 
 
95
    .. attribute:: models.User.is_superuser
 
96
 
 
97
        Boolean. Designates that this user has all permissions without explicitly
 
98
        assigning them.
 
99
 
 
100
    .. attribute:: models.User.last_login
 
101
 
 
102
        A datetime of the user's last login. Is set to the current date/time by
 
103
        default.
 
104
 
 
105
    .. attribute:: models.User.date_joined
 
106
 
 
107
        A datetime designating when the account was created. Is set to the current
 
108
        date/time by default when the account is created.
 
109
 
 
110
Methods
 
111
~~~~~~~
 
112
 
 
113
.. class:: models.User
 
114
 
 
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>`:
 
119
 
 
120
    .. code-block:: python
 
121
 
 
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()
 
130
 
 
131
    In addition to those automatic API methods,
 
132
    :class:`~django.contrib.auth.models.User` objects have the following custom
 
133
    methods:
 
134
 
 
135
    .. method:: models.User.is_anonymous()
 
136
 
 
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
 
142
        method.
 
143
 
 
144
    .. method:: models.User.is_authenticated()
 
145
 
 
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.
 
150
 
 
151
    .. method:: models.User.get_full_name()
 
152
 
 
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.
 
156
 
 
157
    .. method:: models.User.set_password(raw_password)
 
158
 
 
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.
 
162
 
 
163
    .. method:: models.User.check_password(raw_password)
 
164
 
 
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.)
 
167
 
 
168
    .. method:: models.User.set_unusable_password()
 
169
 
 
170
        .. versionadded:: 1.0
 
171
 
 
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.
 
177
 
 
178
        You may need this if authentication for your application takes place
 
179
        against an existing external source such as an LDAP directory.
 
180
 
 
181
    .. method:: models.User.has_usable_password()
 
182
 
 
183
        .. versionadded:: 1.0
 
184
 
 
185
        Returns ``False`` if
 
186
        :meth:`~django.contrib.auth.models.User.set_unusable_password()` has
 
187
        been called for this user.
 
188
 
 
189
    .. method:: models.User.get_group_permissions()
 
190
 
 
191
        Returns a list of permission strings that the user has, through his/her
 
192
        groups.
 
193
 
 
194
    .. method:: models.User.get_all_permissions()
 
195
 
 
196
        Returns a list of permission strings that the user has, both through group
 
197
        and user permissions.
 
198
 
 
199
    .. method:: models.User.has_perm(perm)
 
200
 
 
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``.
 
204
 
 
205
    .. method:: models.User.has_perms(perm_list)
 
206
 
 
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``.
 
210
 
 
211
    .. method:: models.User.has_module_perms(package_name)
 
212
 
 
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
 
215
        ``False``.
 
216
 
 
217
    .. method:: models.User.get_and_delete_messages()
 
218
 
 
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.
 
221
 
 
222
    .. method:: models.User.email_user(subject, message, from_email=None)
 
223
 
 
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`.
 
227
 
 
228
    .. method:: models.User.get_profile()
 
229
 
 
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.
 
235
 
 
236
.. _storing additional user information: #storing-additional-information-about-users
 
237
 
 
238
Manager functions
 
239
~~~~~~~~~~~~~~~~~
 
240
 
 
241
.. class:: models.UserManager
 
242
 
 
243
    The :class:`~django.contrib.auth.models.User` model has a custom manager
 
244
    that has the following helper functions:
 
245
 
 
246
    .. method:: models.UserManager.create_user(username, email, password=None)
 
247
 
 
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``.
 
253
 
 
254
        If no password is provided,
 
255
        :meth:`~django.contrib.auth.models.User.set_unusable_password()` will be
 
256
        called.
 
257
 
 
258
        See `Creating users`_ for example usage.
 
259
 
 
260
    .. method:: models.UserManager.make_random_password(length=10, allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789')
 
261
 
 
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``,
 
265
        ``I`` and ``0``).
 
266
 
 
267
Basic usage
 
268
-----------
 
269
 
 
270
.. _topics-auth-creating-users:
 
271
 
 
272
Creating users
 
273
~~~~~~~~~~~~~~
 
274
 
 
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::
 
278
 
 
279
    >>> from django.contrib.auth.models import User
 
280
    >>> user = User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword')
 
281
 
 
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
 
286
    >>> user.save()
 
287
 
 
288
Changing passwords
 
289
~~~~~~~~~~~~~~~~~~
 
290
 
 
291
Change a password with :meth:`~django.contrib.auth.models.User.set_password()`::
 
292
 
 
293
    >>> from django.contrib.auth.models import User
 
294
    >>> u = User.objects.get(username__exact='john')
 
295
    >>> u.set_password('new password')
 
296
    >>> u.save()
 
297
 
 
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
 
300
section.
 
301
 
 
302
Passwords
 
303
---------
 
304
 
 
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::
 
307
 
 
308
    hashtype$salt$hash
 
309
 
 
310
That's hashtype, salt and hash, separated by the dollar-sign character.
 
311
 
 
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
 
317
version.
 
318
 
 
319
For example::
 
320
 
 
321
    sha1$a1976$a36cc8cbf81742a8fb52e221aaeab48ed7f58ab4
 
322
 
 
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.
 
326
 
 
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
 
331
a given user.
 
332
 
 
333
Anonymous users
 
334
---------------
 
335
 
 
336
.. class:: models.AnonymousUser
 
337
 
 
338
    :class:`django.contrib.auth.models.AnonymousUser` is a class that
 
339
    implements the :class:`django.contrib.auth.models.User` interface, with
 
340
    these differences:
 
341
 
 
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`.
 
360
 
 
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.
 
364
 
 
365
Creating superusers
 
366
-------------------
 
367
 
 
368
.. versionadded:: 1.0
 
369
   The ``manage.py createsuperuser`` command is new.
 
370
 
 
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.
 
375
 
 
376
    manage.py createsuperuser --username=joe --email=joe@example.com
 
377
 
 
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.
 
381
 
 
382
If you're using an older release of Django, the old way of creating a superuser
 
383
on the command line still works::
 
384
 
 
385
    python /path/to/django/contrib/auth/create_superuser.py
 
386
 
 
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.
 
390
 
 
391
.. _auth-profiles:
 
392
 
 
393
Storing additional information about users
 
394
------------------------------------------
 
395
 
 
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.
 
399
 
 
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`.
 
407
 
 
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:
 
411
 
 
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).
 
416
 
 
417
2. The (normalized to lower-case) name of the model class.
 
418
 
 
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::
 
422
 
 
423
    AUTH_PROFILE_MODULE = 'accounts.userprofile'
 
424
 
 
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`.
 
430
 
 
431
For more information, see `Chapter 12 of the Django book`_.
 
432
 
 
433
.. _Chapter 12 of the Django book: http://www.djangobook.com/en/1.0/chapter12/#cn222
 
434
 
 
435
Authentication in Web requests
 
436
==============================
 
437
 
 
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>`.
 
442
 
 
443
First, install the
 
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.
 
448
 
 
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::
 
458
 
 
459
    if request.user.is_authenticated():
 
460
        # Do something for authenticated users.
 
461
    else:
 
462
        # Do something for anonymous users.
 
463
 
 
464
How to log a user in
 
465
--------------------
 
466
 
 
467
Django provides two functions in :mod:`django.contrib.auth`:
 
468
:func:`~django.contrib.auth.authenticate()` and
 
469
:func:`~django.contrib.auth.login()`.
 
470
 
 
471
.. function:: authenticate()
 
472
 
 
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::
 
479
 
 
480
        from django.contrib.auth import authenticate
 
481
        user = authenticate(username='john', password='secret')
 
482
        if user is not None:
 
483
            if user.is_active:
 
484
                print "You provided a correct username and password!"
 
485
            else:
 
486
                print "Your account has been disabled!"
 
487
        else:
 
488
            print "Your username and password were incorrect."
 
489
 
 
490
.. function:: login()
 
491
 
 
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.
 
498
 
 
499
    This example shows how you might use both
 
500
    :func:`~django.contrib.auth.authenticate()` and
 
501
    :func:`~django.contrib.auth.login()`::
 
502
 
 
503
        from django.contrib.auth import authenticate, login
 
504
 
 
505
        def my_view(request):
 
506
            username = request.POST['username']
 
507
            password = request.POST['password']
 
508
            user = authenticate(username=username, password=password)
 
509
            if user is not None:
 
510
                if user.is_active:
 
511
                    login(request, user)
 
512
                    # Redirect to a success page.
 
513
                else:
 
514
                    # Return a 'disabled account' error message
 
515
            else:
 
516
                # Return an 'invalid login' error message.
 
517
 
 
518
.. admonition:: Calling ``authenticate()`` first
 
519
 
 
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.
 
528
 
 
529
.. _backends documentation: #other-authentication-sources
 
530
 
 
531
Manually checking a user's password
 
532
-----------------------------------
 
533
 
 
534
.. function:: check_password()
 
535
 
 
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.
 
542
 
 
543
How to log a user out
 
544
---------------------
 
545
 
 
546
.. function:: logout()
 
547
 
 
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.
 
552
    Example::
 
553
 
 
554
        from django.contrib.auth import logout
 
555
 
 
556
        def logout_view(request):
 
557
            logout(request)
 
558
            # Redirect to a success page.
 
559
 
 
560
    Note that :func:`~django.contrib.auth.logout()` doesn't throw any errors
 
561
    if the user wasn't logged in.
 
562
 
 
563
    .. versionchanged:: 1.0
 
564
       Calling ``logout()`` now cleans session data.
 
565
 
 
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()`.
 
573
 
 
574
Limiting access to logged-in users
 
575
----------------------------------
 
576
 
 
577
The raw way
 
578
~~~~~~~~~~~
 
579
 
 
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
 
583
login page::
 
584
 
 
585
    from django.http import HttpResponseRedirect
 
586
 
 
587
    def my_view(request):
 
588
        if not request.user.is_authenticated():
 
589
            return HttpResponseRedirect('/login/?next=%s' % request.path)
 
590
        # ...
 
591
 
 
592
...or display an error message::
 
593
 
 
594
    def my_view(request):
 
595
        if not request.user.is_authenticated():
 
596
            return render_to_response('myapp/login_error.html')
 
597
        # ...
 
598
 
 
599
The login_required decorator
 
600
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 
601
 
 
602
.. function:: decorators.login_required()
 
603
 
 
604
    As a shortcut, you can use the convenient
 
605
    :func:`~django.contrib.auth.decorators.login_required` decorator::
 
606
 
 
607
        from django.contrib.auth.decorators import login_required
 
608
 
 
609
        def my_view(request):
 
610
            # ...
 
611
        my_view = login_required(my_view)
 
612
 
 
613
    Here's an equivalent example, using the more compact decorator syntax
 
614
    introduced in Python 2.4::
 
615
 
 
616
        from django.contrib.auth.decorators import login_required
 
617
 
 
618
        @login_required
 
619
        def my_view(request):
 
620
            # ...
 
621
 
 
622
    In the Django development version,
 
623
    :func:`~django.contrib.auth.decorators.login_required` also takes an
 
624
    optional ``redirect_field_name`` parameter. Example::
 
625
 
 
626
        from django.contrib.auth.decorators import login_required
 
627
 
 
628
        def my_view(request):
 
629
            # ...
 
630
        my_view = login_required(redirect_field_name='redirect_to')(my_view)
 
631
 
 
632
    Again, an equivalent example of the more compact decorator syntax
 
633
    introduced in Python 2.4::
 
634
 
 
635
        from django.contrib.auth.decorators import login_required
 
636
 
 
637
        @login_required(redirect_field_name='redirect_to')
 
638
        def my_view(request):
 
639
            # ...
 
640
 
 
641
    :func:`~django.contrib.auth.decorators.login_required` does the following:
 
642
 
 
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/``.
 
648
 
 
649
        * If the user is logged in, execute the view normally. The view code
 
650
          is free to assume the user is logged in.
 
651
 
 
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::
 
655
 
 
656
    (r'^accounts/login/$', 'django.contrib.auth.views.login'),
 
657
 
 
658
.. function:: views.login()
 
659
 
 
660
    Here's what ``django.contrib.auth.views.login`` does:
 
661
 
 
662
        * If called via ``GET``, it displays a login form that POSTs to the same
 
663
          URL. More on this in a bit.
 
664
 
 
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.
 
670
 
 
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:
 
674
 
 
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.
 
678
 
 
679
        * ``next``: The URL to redirect to after successful login. This may contain
 
680
          a query string, too.
 
681
 
 
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`.
 
688
 
 
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::
 
693
 
 
694
        (r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'myapp/login.html'}),
 
695
 
 
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::
 
699
 
 
700
        {% extends "base.html" %}
 
701
 
 
702
        {% block content %}
 
703
 
 
704
        {% if form.errors %}
 
705
        <p>Your username and password didn't match. Please try again.</p>
 
706
        {% endif %}
 
707
 
 
708
        <form method="post" action=".">
 
709
        <table>
 
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>
 
712
        </table>
 
713
 
 
714
        <input type="submit" value="login" />
 
715
        <input type="hidden" name="next" value="{{ next }}" />
 
716
        </form>
 
717
 
 
718
        {% endblock %}
 
719
 
 
720
    .. _forms documentation: ../forms/
 
721
    .. _site framework docs: ../sites/
 
722
 
 
723
Other built-in views
 
724
--------------------
 
725
 
 
726
In addition to the ``login`` view, the authentication system includes a
 
727
few other useful built-in views:
 
728
 
 
729
.. function:: django.contrib.auth.views.logout
 
730
 
 
731
    Logs a user out.
 
732
 
 
733
    **Optional arguments:**
 
734
 
 
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.
 
738
 
 
739
    **Template context:**
 
740
 
 
741
        * ``title``: The string "Logged out", localized.
 
742
 
 
743
.. function:: django.contrib.auth.views.logout_then_login
 
744
 
 
745
    Logs a user out, then redirects to the login page.
 
746
 
 
747
    **Optional arguments:**
 
748
 
 
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
 
751
          supplied.
 
752
 
 
753
.. function:: django.contrib.auth.views.password_change
 
754
 
 
755
    Allows a user to change their password.
 
756
 
 
757
    **Optional arguments:**
 
758
 
 
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.
 
762
 
 
763
    **Template context:**
 
764
 
 
765
        * ``form``: The password change form.
 
766
 
 
767
.. function:: django.contrib.auth.views.password_change_done
 
768
 
 
769
    The page shown after a user has changed their password.
 
770
 
 
771
    **Optional arguments:**
 
772
 
 
773
        * ``template_name``: The full name of a template to use. This will
 
774
          default to :file:`registration/password_change_done.html` if not
 
775
          supplied.
 
776
 
 
777
.. function:: django.contrib.auth.views.password_reset
 
778
 
 
779
    Allows a user to reset their password, and sends them the new password
 
780
    in an e-mail.
 
781
 
 
782
    **Optional arguments:**
 
783
 
 
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.
 
787
 
 
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.
 
791
 
 
792
    **Template context:**
 
793
 
 
794
        * ``form``: The form for resetting the user's password.
 
795
 
 
796
.. function:: django.contrib.auth.views.password_reset_done
 
797
 
 
798
    The page shown after a user has reset their password.
 
799
 
 
800
    **Optional arguments:**
 
801
 
 
802
        * ``template_name``: The full name of a template to use. This will
 
803
          default to :file:`registration/password_reset_done.html` if not
 
804
          supplied.
 
805
 
 
806
.. function:: django.contrib.auth.views.redirect_to_login
 
807
 
 
808
    Redirects to the login page, and then back to another URL after a
 
809
    successful login.
 
810
 
 
811
    **Required arguments:**
 
812
 
 
813
        * ``next``: The URL to redirect to after a successful login.
 
814
 
 
815
    **Optional arguments:**
 
816
 
 
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
 
819
          supplied.
 
820
 
 
821
Built-in forms
 
822
---------------------
 
823
 
 
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:
 
827
 
 
828
    * :class:`django.contrib.auth.forms.AdminPasswordChangeForm`: A form used
 
829
      in the admin interface to change a user's password.
 
830
 
 
831
    * :class:`django.contrib.auth.forms.AuthenticationForm`: A form for
 
832
      logging a user in.
 
833
 
 
834
    * :class:`django.contrib.auth.forms.PasswordChangeForm`: A form for
 
835
      allowing a user to change their password.
 
836
 
 
837
    * :class:`django.contrib.auth.forms.PasswordResetForm`: A form for
 
838
      resetting a user's password and e-mailing the new password to them.
 
839
 
 
840
    * :class:`django.contrib.auth.forms.UserCreationForm`: A form for creating
 
841
      a new user.
 
842
 
 
843
Limiting access to logged-in users that pass a test
 
844
---------------------------------------------------
 
845
 
 
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.
 
848
 
 
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``::
 
853
 
 
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.")
 
857
        # ...
 
858
 
 
859
.. function:: decorators.user_passes_test()
 
860
 
 
861
    As a shortcut, you can use the convenient ``user_passes_test`` decorator::
 
862
 
 
863
        from django.contrib.auth.decorators import user_passes_test
 
864
 
 
865
        def my_view(request):
 
866
            # ...
 
867
        my_view = user_passes_test(lambda u: u.has_perm('polls.can_vote'))(my_view)
 
868
 
 
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.
 
873
 
 
874
    Here's the same thing, using Python 2.4's decorator syntax::
 
875
 
 
876
        from django.contrib.auth.decorators import user_passes_test
 
877
 
 
878
        @user_passes_test(lambda u: u.has_perm('polls.can_vote'))
 
879
        def my_view(request):
 
880
            # ...
 
881
 
 
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
 
888
    not anonymous.
 
889
 
 
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).
 
893
 
 
894
    Example in Python 2.3 syntax::
 
895
 
 
896
        from django.contrib.auth.decorators import user_passes_test
 
897
 
 
898
        def my_view(request):
 
899
            # ...
 
900
        my_view = user_passes_test(lambda u: u.has_perm('polls.can_vote'), login_url='/login/')(my_view)
 
901
 
 
902
    Example in Python 2.4 syntax::
 
903
 
 
904
        from django.contrib.auth.decorators import user_passes_test
 
905
 
 
906
        @user_passes_test(lambda u: u.has_perm('polls.can_vote'), login_url='/login/')
 
907
        def my_view(request):
 
908
            # ...
 
909
 
 
910
The permission_required decorator
 
911
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 
912
 
 
913
.. function:: decorators.permission_required()
 
914
 
 
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::
 
919
 
 
920
        from django.contrib.auth.decorators import permission_required
 
921
 
 
922
        def my_view(request):
 
923
            # ...
 
924
        my_view = permission_required('polls.can_vote')(my_view)
 
925
 
 
926
    Note that :func:`~django.contrib.auth.decorators.permission_required()`
 
927
    also takes an optional ``login_url`` parameter. Example::
 
928
 
 
929
        from django.contrib.auth.decorators import permission_required
 
930
 
 
931
        def my_view(request):
 
932
            # ...
 
933
        my_view = permission_required('polls.can_vote', login_url='/loginpage/')(my_view)
 
934
 
 
935
    As in the ``login_required`` decorator, ``login_url`` defaults to
 
936
    :setting:`settings.LOGIN_URL <LOGIN_URL>`.
 
937
 
 
938
Limiting access to generic views
 
939
--------------------------------
 
940
 
 
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::
 
944
 
 
945
    from django.views.generic.date_based import object_detail
 
946
 
 
947
    @login_required
 
948
    def limited_object_detail(*args, **kwargs):
 
949
        return object_detail(*args, **kwargs)
 
950
 
 
951
Permissions
 
952
===========
 
953
 
 
954
Django comes with a simple permissions system. It provides a way to assign
 
955
permissions to specific users and groups of users.
 
956
 
 
957
It's used by the Django admin site, but you're welcome to use it in your own
 
958
code.
 
959
 
 
960
The Django admin site uses permissions as follows:
 
961
 
 
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
 
966
      object.
 
967
    * Access to delete an object is limited to users with the "delete"
 
968
      permission for that type of object.
 
969
 
 
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.
 
976
 
 
977
Default permissions
 
978
-------------------
 
979
 
 
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.
 
984
 
 
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>`.
 
992
 
 
993
.. _custom-permissions:
 
994
 
 
995
Custom permissions
 
996
------------------
 
997
 
 
998
To create custom permissions for a given model object, use the ``permissions``
 
999
:ref:`model Meta attribute <meta-options>`.
 
1000
 
 
1001
This example model creates three custom permissions::
 
1002
 
 
1003
    class USCitizen(models.Model):
 
1004
        # ...
 
1005
        class Meta:
 
1006
            permissions = (
 
1007
                ("can_drive", "Can drive"),
 
1008
                ("can_vote", "Can vote in elections"),
 
1009
                ("can_drink", "Can drink alcohol"),
 
1010
            )
 
1011
 
 
1012
The only thing this does is create those extra permissions when you run
 
1013
:djadmin:`manage.py syncdb <syncdb>`.
 
1014
 
 
1015
API reference
 
1016
-------------
 
1017
 
 
1018
.. class:: models.Permission
 
1019
 
 
1020
    Just like users, permissions are implemented in a Django model that lives in
 
1021
    `django/contrib/auth/models.py`_.
 
1022
 
 
1023
.. _django/contrib/auth/models.py: http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/models.py
 
1024
 
 
1025
Fields
 
1026
~~~~~~
 
1027
 
 
1028
:class:`~django.contrib.auth.models.Permission` objects have the following
 
1029
fields:
 
1030
 
 
1031
.. attribute:: models.Permission.name
 
1032
    
 
1033
    Required. 50 characters or fewer. Example: ``'Can vote'``.
 
1034
 
 
1035
.. attribute:: models.Permission.content_type
 
1036
 
 
1037
    Required. A reference to the ``django_content_type`` database table,
 
1038
    which contains a record for each installed Django model.
 
1039
 
 
1040
.. attribute:: models.Permission.codename
 
1041
    
 
1042
    Required. 100 characters or fewer. Example: ``'can_vote'``.
 
1043
 
 
1044
Methods
 
1045
~~~~~~~
 
1046
 
 
1047
:class:`~django.contrib.auth.models.Permission` objects have the standard
 
1048
data-access methods like any other :ref:`Django model <ref-models-instances>`.
 
1049
 
 
1050
Authentication data in templates
 
1051
================================
 
1052
 
 
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`.
 
1056
 
 
1057
.. admonition:: Technicality
 
1058
 
 
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>`.
 
1064
   
 
1065
Users
 
1066
-----
 
1067
 
 
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 }}``::
 
1072
 
 
1073
    {% if user.is_authenticated %}
 
1074
        <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
 
1075
    {% else %}
 
1076
        <p>Welcome, new user. Please log in.</p>
 
1077
    {% endif %}
 
1078
 
 
1079
Permissions
 
1080
-----------
 
1081
 
 
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.
 
1086
 
 
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::
 
1091
 
 
1092
    {{ perms.foo }}
 
1093
 
 
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
 
1097
``foo.can_vote``::
 
1098
 
 
1099
    {{ perms.foo.can_vote }}
 
1100
 
 
1101
Thus, you can check permissions in template ``{% if %}`` statements::
 
1102
 
 
1103
    {% if perms.foo %}
 
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>
 
1107
        {% endif %}
 
1108
        {% if perms.foo.can_drive %}
 
1109
            <p>You can drive!</p>
 
1110
        {% endif %}
 
1111
    {% else %}
 
1112
        <p>You don't have permission to do anything in the foo app.</p>
 
1113
    {% endif %}
 
1114
 
 
1115
Groups
 
1116
======
 
1117
 
 
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.
 
1120
 
 
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.
 
1124
 
 
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
 
1129
messages.
 
1130
 
 
1131
Messages
 
1132
========
 
1133
 
 
1134
The message system is a lightweight way to queue messages for given users.
 
1135
 
 
1136
A message is associated with a :class:`~django.contrib.auth.models.User`.
 
1137
There's no concept of expiration or timestamps.
 
1138
 
 
1139
Messages are used by the Django admin after successful actions. For example,
 
1140
``"The poll Foo was created successfully."`` is a message.
 
1141
 
 
1142
The API is simple:
 
1143
 
 
1144
.. method:: models.User.message_set.create(message)
 
1145
 
 
1146
    To create a new message, use
 
1147
    ``user_obj.message_set.create(message='message_text')``.
 
1148
    
 
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.
 
1153
 
 
1154
In this example view, the system saves a message for the user after creating
 
1155
a playlist::
 
1156
 
 
1157
    def create_playlist(request, songs):
 
1158
        # Create the playlist with the given songs.
 
1159
        # ...
 
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))
 
1163
 
 
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::
 
1168
 
 
1169
    {% if messages %}
 
1170
    <ul>
 
1171
        {% for message in messages %}
 
1172
        <li>{{ message }}</li>
 
1173
        {% endfor %}
 
1174
    </ul>
 
1175
    {% endif %}
 
1176
 
 
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.
 
1180
 
 
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>`.
 
1184
 
 
1185
.. _authentication-backends:
 
1186
 
 
1187
Other authentication sources
 
1188
============================
 
1189
 
 
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.
 
1193
 
 
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.
 
1198
 
 
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
 
1202
systems.
 
1203
 
 
1204
Specifying authentication backends
 
1205
----------------------------------
 
1206
 
 
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.
 
1213
 
 
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.
 
1218
 
 
1219
By default, :setting:`AUTHENTICATION_BACKENDS` is set to::
 
1220
 
 
1221
    ('django.contrib.auth.backends.ModelBackend',)
 
1222
 
 
1223
That's the basic authentication scheme that checks the Django users database.
 
1224
 
 
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.
 
1228
 
 
1229
Writing an authentication backend
 
1230
---------------------------------
 
1231
 
 
1232
An authentication backend is a class that implements two methods:
 
1233
``get_user(user_id)`` and ``authenticate(**credentials)``.
 
1234
 
 
1235
The ``get_user`` method takes a ``user_id`` -- which could be a username,
 
1236
database ID or whatever -- and returns a ``User`` object.
 
1237
 
 
1238
The ``authenticate`` method takes credentials as keyword arguments. Most of
 
1239
the time, it'll just look like this::
 
1240
 
 
1241
    class MyBackend:
 
1242
        def authenticate(self, username=None, password=None):
 
1243
            # Check the username/password and return a User.
 
1244
 
 
1245
But it could also authenticate a token, like so::
 
1246
 
 
1247
    class MyBackend:
 
1248
        def authenticate(self, token=None):
 
1249
            # Check the token and return a User.
 
1250
 
 
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``.
 
1254
 
 
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.
 
1261
 
 
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::
 
1265
 
 
1266
    from django.conf import settings
 
1267
    from django.contrib.auth.models import User, check_password
 
1268
 
 
1269
    class SettingsBackend:
 
1270
        """
 
1271
        Authenticate against the settings ADMIN_LOGIN and ADMIN_PASSWORD.
 
1272
 
 
1273
        Use the login name, and a hash of the password. For example:
 
1274
 
 
1275
        ADMIN_LOGIN = 'admin'
 
1276
        ADMIN_PASSWORD = 'sha1$4e987$afbcf42e21bd417fb71db8c66b321e9fc33051de'
 
1277
        """
 
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:
 
1282
                try:
 
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
 
1291
                    user.save()
 
1292
                return user
 
1293
            return None
 
1294
 
 
1295
        def get_user(self, user_id):
 
1296
            try:
 
1297
                return User.objects.get(pk=user_id)
 
1298
            except User.DoesNotExist:
 
1299
                return None
 
1300
 
 
1301
Handling authorization in custom backends
 
1302
-----------------------------------------
 
1303
 
 
1304
Custom auth backends can provide their own permissions.
 
1305
 
 
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.
 
1312
 
 
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.
 
1316
 
 
1317
The simple backend above could implement permissions for the magic admin
 
1318
fairly simply::
 
1319
 
 
1320
    class SettingsBackend:
 
1321
 
 
1322
        # ...
 
1323
 
 
1324
        def has_perm(self, user_obj, perm):
 
1325
            if user_obj.username == settings.ADMIN_LOGIN:
 
1326
                return True
 
1327
            else:
 
1328
                return False
 
1329
 
 
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.
 
1334
 
 
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.
 
1338
 
 
1339
.. _django/contrib/auth/backends.py: http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/backends.py