Django

Code

root/django/tags/releases/0.95/docs/authentication.txt

Revision 3360, 31.0 kB (checked in by mtredinnick, 2 years ago)

Fixed #2332 -- Introduced is_authenticated() method on User and AnonymousUser? classes. Recommended its use over is_anonymous in the docs. Changed internal Django use to match this recommendation. Thanks to SmileyChris? and Gary Wilson for the patch.

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