PageRenderTime 24ms CodeModel.GetById 2ms app.highlight 9ms RepoModel.GetById 1ms app.codeStats 0ms

/docs/topics/auth.txt

https://code.google.com/p/mango-py/
Plain Text | 1710 lines | 1227 code | 483 blank | 0 comment | 0 complexity | 30929ad91513a4b0967ec7f66eb7cdc5 MD5 | raw file
   1=============================
   2User authentication in Django
   3=============================
   4
   5.. module:: django.contrib.auth
   6   :synopsis: Django's authentication framework.
   7
   8Django comes with a user authentication system. It handles user accounts,
   9groups, permissions and cookie-based user sessions. This document explains how
  10things work.
  11
  12Overview
  13========
  14
  15The auth system consists of:
  16
  17    * Users
  18    * Permissions: Binary (yes/no) flags designating whether a user may perform
  19      a certain task.
  20    * Groups: A generic way of applying labels and permissions to more than one
  21      user.
  22    * Messages: A simple way to queue messages for given users.
  23
  24.. deprecated:: 1.2
  25   The Messages component of the auth system will be removed in Django 1.4.
  26
  27Installation
  28============
  29
  30Authentication support is bundled as a Django application in
  31``django.contrib.auth``. To install it, do the following:
  32
  33    1. Put ``'django.contrib.auth'`` and ``'django.contrib.contenttypes'`` in
  34       your :setting:`INSTALLED_APPS` setting.
  35       (The :class:`~django.contrib.auth.models.Permission` model in
  36       :mod:`django.contrib.auth` depends on :mod:`django.contrib.contenttypes`.)
  37    2. Run the command ``manage.py syncdb``.
  38
  39Note that the default :file:`settings.py` file created by
  40:djadmin:`django-admin.py startproject <startproject>` includes
  41``'django.contrib.auth'`` and ``'django.contrib.contenttypes'`` in
  42:setting:`INSTALLED_APPS` for convenience.  If your :setting:`INSTALLED_APPS`
  43already contains these apps, feel free to run :djadmin:`manage.py syncdb
  44<syncdb>` again; you can run that command as many times as you'd like, and each
  45time it'll only install what's needed.
  46
  47The :djadmin:`syncdb` command creates the necessary database tables, creates
  48permission objects for all installed apps that need 'em, and prompts you to
  49create a superuser account the first time you run it.
  50
  51Once you've taken those steps, that's it.
  52
  53Users
  54=====
  55
  56.. class:: models.User
  57
  58API reference
  59-------------
  60
  61Fields
  62~~~~~~
  63
  64.. class:: models.User
  65
  66    :class:`~django.contrib.auth.models.User` objects have the following
  67    fields:
  68
  69    .. attribute:: models.User.username
  70
  71        Required. 30 characters or fewer. Alphanumeric characters only
  72        (letters, digits and underscores).
  73
  74        .. versionchanged:: 1.2
  75           Usernames may now contain ``@``, ``+``, ``.`` and ``-`` characters.
  76
  77    .. attribute:: models.User.first_name
  78
  79        Optional. 30 characters or fewer.
  80
  81    .. attribute:: models.User.last_name
  82
  83        Optional. 30 characters or fewer.
  84
  85    .. attribute:: models.User.email
  86
  87        Optional. E-mail address.
  88
  89    .. attribute:: models.User.password
  90
  91        Required. A hash of, and metadata about, the password. (Django doesn't
  92        store the raw password.) Raw passwords can be arbitrarily long and can
  93        contain any character. See the "Passwords" section below.
  94
  95    .. attribute:: models.User.is_staff
  96
  97        Boolean. Designates whether this user can access the admin site.
  98
  99    .. attribute:: models.User.is_active
 100
 101        Boolean. Designates whether this user account should be considered
 102        active. We recommend that you set this flag to ``False`` instead of
 103        deleting accounts; that way, if your applications have any foreign keys
 104        to users, the foreign keys won't break.
 105
 106        This doesn't necessarily control whether or not the user can log in.
 107        Authentication backends aren't required to check for the ``is_active``
 108        flag, so if you want to reject a login based on ``is_active`` being
 109        ``False``, it's up to you to check that in your own login view.
 110        However, the :class:`~django.contrib.auth.forms.AuthenticationForm`
 111        used by the :func:`~django.contrib.auth.views.login` view *does*
 112        perform this check, as do the permission-checking methods such as
 113        :meth:`~models.User.has_perm` and the authentication in the Django
 114        admin. All of those functions/methods will return ``False`` for
 115        inactive users.
 116
 117    .. attribute:: models.User.is_superuser
 118
 119        Boolean. Designates that this user has all permissions without
 120        explicitly assigning them.
 121
 122    .. attribute:: models.User.last_login
 123
 124        A datetime of the user's last login. Is set to the current date/time by
 125        default.
 126
 127    .. attribute:: models.User.date_joined
 128
 129        A datetime designating when the account was created. Is set to the
 130        current date/time by default when the account is created.
 131
 132Methods
 133~~~~~~~
 134
 135.. class:: models.User
 136
 137    :class:`~django.contrib.auth.models.User` objects have two many-to-many
 138    fields: models.User. ``groups`` and ``user_permissions``.
 139    :class:`~django.contrib.auth.models.User` objects can access their related
 140    objects in the same way as any other :doc:`Django model
 141    </topics/db/models>`:
 142
 143    .. code-block:: python
 144
 145        myuser.groups = [group_list]
 146        myuser.groups.add(group, group, ...)
 147        myuser.groups.remove(group, group, ...)
 148        myuser.groups.clear()
 149        myuser.user_permissions = [permission_list]
 150        myuser.user_permissions.add(permission, permission, ...)
 151        myuser.user_permissions.remove(permission, permission, ...)
 152        myuser.user_permissions.clear()
 153
 154    In addition to those automatic API methods,
 155    :class:`~django.contrib.auth.models.User` objects have the following custom
 156    methods:
 157
 158    .. method:: models.User.is_anonymous()
 159
 160        Always returns ``False``. This is a way of differentiating
 161        :class:`~django.contrib.auth.models.User` and
 162        :class:`~django.contrib.auth.models.AnonymousUser` objects.
 163        Generally, you should prefer using
 164        :meth:`~django.contrib.auth.models.User.is_authenticated()` to this
 165        method.
 166
 167    .. method:: models.User.is_authenticated()
 168
 169        Always returns ``True``. This is a way to tell if the user has been
 170        authenticated. This does not imply any permissions, and doesn't check
 171        if the user is active - it only indicates that the user has provided a
 172        valid username and password.
 173
 174    .. method:: models.User.get_full_name()
 175
 176        Returns the :attr:`~django.contrib.auth.models.User.first_name` plus
 177        the :attr:`~django.contrib.auth.models.User.last_name`, with a space in
 178        between.
 179
 180    .. method:: models.User.set_password(raw_password)
 181
 182        Sets the user's password to the given raw string, taking care of the
 183        password hashing. Doesn't save the
 184        :class:`~django.contrib.auth.models.User` object.
 185
 186    .. method:: models.User.check_password(raw_password)
 187
 188        Returns ``True`` if the given raw string is the correct password for
 189        the user. (This takes care of the password hashing in making the
 190        comparison.)
 191
 192    .. method:: models.User.set_unusable_password()
 193
 194        Marks the user as having no password set.  This isn't the same as
 195        having a blank string for a password.
 196        :meth:`~django.contrib.auth.models.User.check_password()` for this user
 197        will never return ``True``. Doesn't save the
 198        :class:`~django.contrib.auth.models.User` object.
 199
 200        You may need this if authentication for your application takes place
 201        against an existing external source such as an LDAP directory.
 202
 203    .. method:: models.User.has_usable_password()
 204
 205        Returns ``False`` if
 206        :meth:`~django.contrib.auth.models.User.set_unusable_password()` has
 207        been called for this user.
 208
 209    .. method:: models.User.get_group_permissions(obj=None)
 210
 211        Returns a set of permission strings that the user has, through his/her
 212        groups.
 213
 214        .. versionadded:: 1.2
 215
 216        If ``obj`` is passed in, only returns the group permissions for
 217        this specific object.
 218
 219    .. method:: models.User.get_all_permissions(obj=None)
 220
 221        Returns a set of permission strings that the user has, both through
 222        group and user permissions.
 223
 224        .. versionadded:: 1.2
 225
 226        If ``obj`` is passed in, only returns the permissions for this
 227        specific object.
 228
 229    .. method:: models.User.has_perm(perm, obj=None)
 230
 231        Returns ``True`` if the user has the specified permission, where perm is
 232        in the format ``"<app label>.<permission codename>"``. (see
 233        `permissions`_ section below). If the user is inactive, this method will
 234        always return ``False``.
 235
 236        .. versionadded:: 1.2
 237
 238        If ``obj`` is passed in, this method won't check for a permission for
 239        the model, but for this specific object.
 240
 241    .. method:: models.User.has_perms(perm_list, obj=None)
 242
 243        Returns ``True`` if the user has each of the specified permissions,
 244        where each perm is in the format
 245        ``"<app label>.<permission codename>"``. If the user is inactive,
 246        this method will always return ``False``.
 247
 248        .. versionadded:: 1.2
 249
 250        If ``obj`` is passed in, this method won't check for permissions for
 251        the model, but for the specific object.
 252
 253    .. method:: models.User.has_module_perms(package_name)
 254
 255        Returns ``True`` if the user has any permissions in the given package
 256        (the Django app label). If the user is inactive, this method will
 257        always return ``False``.
 258
 259    .. method:: models.User.get_and_delete_messages()
 260
 261        Returns a list of :class:`~django.contrib.auth.models.Message` objects
 262        in the user's queue and deletes the messages from the queue.
 263
 264    .. method:: models.User.email_user(subject, message, from_email=None)
 265
 266        Sends an e-mail to the user. If
 267        :attr:`~django.contrib.auth.models.User.from_email` is ``None``, Django
 268        uses the :setting:`DEFAULT_FROM_EMAIL`.
 269
 270    .. method:: models.User.get_profile()
 271
 272        Returns a site-specific profile for this user. Raises
 273        :exc:`django.contrib.auth.models.SiteProfileNotAvailable` if the
 274        current site doesn't allow profiles. For information on how to define a
 275        site-specific user profile, see the section on `storing additional user
 276        information`_ below.
 277
 278.. _storing additional user information: #storing-additional-information-about-users
 279
 280Manager functions
 281~~~~~~~~~~~~~~~~~
 282
 283.. class:: models.UserManager
 284
 285    The :class:`~django.contrib.auth.models.User` model has a custom manager
 286    that has the following helper functions:
 287
 288    .. method:: models.UserManager.create_user(username, email, password=None)
 289
 290        Creates, saves and returns a :class:`~django.contrib.auth.models.User`.
 291
 292        The :attr:`~django.contrib.auth.models.User.username` and
 293        :attr:`~django.contrib.auth.models.User.password` are set as given. The
 294        domain portion of :attr:`~django.contrib.auth.models.User.email` is
 295        automatically converted to lowercase, and the returned
 296        :class:`~django.contrib.auth.models.User` object will have
 297        :attr:`~models.User.is_active` set to ``True``.
 298
 299        If no password is provided,
 300        :meth:`~django.contrib.auth.models.User.set_unusable_password()` will
 301        be called.
 302
 303        See `Creating users`_ for example usage.
 304
 305    .. method:: models.UserManager.make_random_password(length=10, allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789')
 306
 307        Returns a random password with the given length and given string of
 308        allowed characters. (Note that the default value of ``allowed_chars``
 309        doesn't contain letters that can cause user confusion, including:
 310
 311            * ``i``, ``l``, ``I``, and ``1`` (lowercase letter i, lowercase
 312              letter L, uppercase letter i, and the number one)
 313            * ``o``, ``O``, and ``0`` (uppercase letter o, lowercase letter o,
 314              and zero)
 315
 316Basic usage
 317-----------
 318
 319.. _topics-auth-creating-users:
 320
 321Creating users
 322~~~~~~~~~~~~~~
 323
 324The most basic way to create users is to use the
 325:meth:`~django.contrib.auth.models.UserManager.create_user` helper function
 326that comes with Django::
 327
 328    >>> from django.contrib.auth.models import User
 329    >>> user = User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword')
 330
 331    # At this point, user is a User object that has already been saved
 332    # to the database. You can continue to change its attributes
 333    # if you want to change other fields.
 334    >>> user.is_staff = True
 335    >>> user.save()
 336
 337You can also create users using the Django admin site. Assuming you've enabled
 338the admin site and hooked it to the URL ``/admin/``, the "Add user" page is at
 339``/admin/auth/user/add/``. You should also see a link to "Users" in the "Auth"
 340section of the main admin index page. The "Add user" admin page is different
 341than standard admin pages in that it requires you to choose a username and
 342password before allowing you to edit the rest of the user's fields.
 343
 344Also note: if you want your own user account to be able to create users using
 345the Django admin site, you'll need to give yourself permission to add users
 346*and* change users (i.e., the "Add user" and "Change user" permissions). If
 347your account has permission to add users but not to change them, you won't be
 348able to add users. Why? Because if you have permission to add users, you have
 349the power to create superusers, which can then, in turn, change other users. So
 350Django requires add *and* change permissions as a slight security measure.
 351
 352Changing passwords
 353~~~~~~~~~~~~~~~~~~
 354
 355.. versionadded:: 1.2
 356   The ``manage.py changepassword`` command was added.
 357
 358:djadmin:`manage.py changepassword *username* <changepassword>` offers a method
 359of changing a User's password from the command line. It prompts you to
 360change the password of a given user which you must enter twice. If
 361they both match, the new password will be changed immediately. If you
 362do not supply a user, the command will attempt to change the password
 363whose username matches the current user.
 364
 365You can also change a password programmatically, using
 366:meth:`~django.contrib.auth.models.User.set_password()`:
 367
 368.. code-block:: python
 369
 370    >>> from django.contrib.auth.models import User
 371    >>> u = User.objects.get(username__exact='john')
 372    >>> u.set_password('new password')
 373    >>> u.save()
 374
 375Don't set the :attr:`~django.contrib.auth.models.User.password` attribute
 376directly unless you know what you're doing. This is explained in the next
 377section.
 378
 379Passwords
 380---------
 381
 382The :attr:`~django.contrib.auth.models.User.password` attribute of a
 383:class:`~django.contrib.auth.models.User` object is a string in this format::
 384
 385    hashtype$salt$hash
 386
 387That's hashtype, salt and hash, separated by the dollar-sign character.
 388
 389Hashtype is either ``sha1`` (default), ``md5`` or ``crypt`` -- the algorithm
 390used to perform a one-way hash of the password. Salt is a random string used
 391to salt the raw password to create the hash. Note that the ``crypt`` method is
 392only supported on platforms that have the standard Python ``crypt`` module
 393available.
 394
 395For example::
 396
 397    sha1$a1976$a36cc8cbf81742a8fb52e221aaeab48ed7f58ab4
 398
 399The :meth:`~django.contrib.auth.models.User.set_password` and
 400:meth:`~django.contrib.auth.models.User.check_password` functions handle the
 401setting and checking of these values behind the scenes.
 402
 403Previous Django versions, such as 0.90, used simple MD5 hashes without password
 404salts. For backwards compatibility, those are still supported; they'll be
 405converted automatically to the new style the first time
 406:meth:`~django.contrib.auth.models.User.check_password()` works correctly for
 407a given user.
 408
 409Anonymous users
 410---------------
 411
 412.. class:: models.AnonymousUser
 413
 414    :class:`django.contrib.auth.models.AnonymousUser` is a class that
 415    implements the :class:`django.contrib.auth.models.User` interface, with
 416    these differences:
 417
 418    * :attr:`~django.contrib.auth.models.User.id` is always ``None``.
 419    * :attr:`~django.contrib.auth.models.User.is_staff` and
 420      :attr:`~django.contrib.auth.models.User.is_superuser` are always
 421      ``False``.
 422    * :attr:`~django.contrib.auth.models.User.is_active` is always ``False``.
 423    * :attr:`~django.contrib.auth.models.User.groups` and
 424      :attr:`~django.contrib.auth.models.User.user_permissions` are always
 425      empty.
 426    * :meth:`~django.contrib.auth.models.User.is_anonymous()` returns ``True``
 427      instead of ``False``.
 428    * :meth:`~django.contrib.auth.models.User.is_authenticated()` returns
 429      ``False`` instead of ``True``.
 430    * :meth:`~django.contrib.auth.models.User.set_password()`,
 431      :meth:`~django.contrib.auth.models.User.check_password()`,
 432      :meth:`~django.contrib.auth.models.User.save()`,
 433      :meth:`~django.contrib.auth.models.User.delete()`,
 434      :meth:`~django.contrib.auth.models.User.set_groups()` and
 435      :meth:`~django.contrib.auth.models.User.set_permissions()` raise
 436      :exc:`NotImplementedError`.
 437
 438In practice, you probably won't need to use
 439:class:`~django.contrib.auth.models.AnonymousUser` objects on your own, but
 440they're used by Web requests, as explained in the next section.
 441
 442.. _topics-auth-creating-superusers:
 443
 444Creating superusers
 445-------------------
 446
 447:djadmin:`manage.py syncdb <syncdb>` prompts you to create a superuser the
 448first time you run it after adding ``'django.contrib.auth'`` to your
 449:setting:`INSTALLED_APPS`. If you need to create a superuser at a later date,
 450you can use a command line utility::
 451
 452    manage.py createsuperuser --username=joe --email=joe@example.com
 453
 454You will be prompted for a password. After you enter one, the user will be
 455created immediately. If you leave off the :djadminopt:`--username` or the
 456:djadminopt:`--email` options, it will prompt you for those values.
 457
 458If you're using an older release of Django, the old way of creating a superuser
 459on the command line still works::
 460
 461    python /path/to/django/contrib/auth/create_superuser.py
 462
 463...where :file:`/path/to` is the path to the Django codebase on your
 464filesystem. The ``manage.py`` command is preferred because it figures out the
 465correct path and environment for you.
 466
 467.. _auth-profiles:
 468
 469Storing additional information about users
 470------------------------------------------
 471
 472If you'd like to store additional information related to your users, Django
 473provides a method to specify a site-specific related model -- termed a "user
 474profile" -- for this purpose.
 475
 476To make use of this feature, define a model with fields for the
 477additional information you'd like to store, or additional methods
 478you'd like to have available, and also add a
 479:class:`~django.db.models.Field.OneToOneField` named ``user`` from your model
 480to the :class:`~django.contrib.auth.models.User` model. This will ensure only
 481one instance of your model can be created for each
 482:class:`~django.contrib.auth.models.User`.
 483
 484To indicate that this model is the user profile model for a given site, fill in
 485the setting :setting:`AUTH_PROFILE_MODULE` with a string consisting of the
 486following items, separated by a dot:
 487
 4881. The name of the application (case sensitive) in which the user
 489   profile model is defined (in other words, the
 490   name which was passed to :djadmin:`manage.py startapp <startapp>` to create
 491   the application).
 492
 4932. The name of the model (not case sensitive) class.
 494
 495For example, if the profile model was a class named ``UserProfile`` and was
 496defined inside an application named ``accounts``, the appropriate setting would
 497be::
 498
 499    AUTH_PROFILE_MODULE = 'accounts.UserProfile'
 500
 501When a user profile model has been defined and specified in this manner, each
 502:class:`~django.contrib.auth.models.User` object will have a method --
 503:class:`~django.contrib.auth.models.User.get_profile()` -- which returns the
 504instance of the user profile model associated with that
 505:class:`~django.contrib.auth.models.User`.
 506
 507The method :class:`~django.contrib.auth.models.User.get_profile()`
 508does not create the profile, if it does not exist. You need to
 509register a handler for the signal
 510:attr:`django.db.models.signals.post_save` on the User model, and, in
 511the handler, if created=True, create the associated user profile.
 512
 513For more information, see `Chapter 12 of the Django book`_.
 514
 515.. _Chapter 12 of the Django book: http://www.djangobook.com/en/1.0/chapter12/#cn222
 516
 517Authentication in Web requests
 518==============================
 519
 520Until now, this document has dealt with the low-level APIs for manipulating
 521authentication-related objects. On a higher level, Django can hook this
 522authentication framework into its system of
 523:class:`request objects <django.http.HttpRequest>`.
 524
 525First, install the
 526:class:`~django.contrib.sessions.middleware.SessionMiddleware` and
 527:class:`~django.contrib.auth.middleware.AuthenticationMiddleware`
 528middlewares by adding them to your :setting:`MIDDLEWARE_CLASSES` setting. See
 529the :doc:`session documentation </topics/http/sessions>` for more information.
 530
 531Once you have those middlewares installed, you'll be able to access
 532:attr:`request.user <django.http.HttpRequest.user>` in views.
 533:attr:`request.user <django.http.HttpRequest.user>` will give you a
 534:class:`~django.contrib.auth.models.User` object representing the currently
 535logged-in user. If a user isn't currently logged in,
 536:attr:`request.user <django.http.HttpRequest.user>` will be set to an instance
 537of :class:`~django.contrib.auth.models.AnonymousUser` (see the previous
 538section). You can tell them apart with
 539:meth:`~django.contrib.auth.models.User.is_authenticated()`, like so::
 540
 541    if request.user.is_authenticated():
 542        # Do something for authenticated users.
 543    else:
 544        # Do something for anonymous users.
 545
 546.. _how-to-log-a-user-in:
 547
 548How to log a user in
 549--------------------
 550
 551Django provides two functions in :mod:`django.contrib.auth`:
 552:func:`~django.contrib.auth.authenticate()` and
 553:func:`~django.contrib.auth.login()`.
 554
 555.. function:: authenticate()
 556
 557    To authenticate a given username and password, use
 558    :func:`~django.contrib.auth.authenticate()`. It takes two keyword
 559    arguments, ``username`` and ``password``, and it returns a
 560    :class:`~django.contrib.auth.models.User` object if the password is valid
 561    for the given username. If the password is invalid,
 562    :func:`~django.contrib.auth.authenticate()` returns ``None``. Example::
 563
 564        from django.contrib.auth import authenticate
 565        user = authenticate(username='john', password='secret')
 566        if user is not None:
 567            if user.is_active:
 568                print "You provided a correct username and password!"
 569            else:
 570                print "Your account has been disabled!"
 571        else:
 572            print "Your username and password were incorrect."
 573
 574.. function:: login()
 575
 576    To log a user in, in a view, use :func:`~django.contrib.auth.login()`. It
 577    takes an :class:`~django.http.HttpRequest` object and a
 578    :class:`~django.contrib.auth.models.User` object.
 579    :func:`~django.contrib.auth.login()` saves the user's ID in the session,
 580    using Django's session framework, so, as mentioned above, you'll need to
 581    make sure to have the session middleware installed.
 582
 583    This example shows how you might use both
 584    :func:`~django.contrib.auth.authenticate()` and
 585    :func:`~django.contrib.auth.login()`::
 586
 587        from django.contrib.auth import authenticate, login
 588
 589        def my_view(request):
 590            username = request.POST['username']
 591            password = request.POST['password']
 592            user = authenticate(username=username, password=password)
 593            if user is not None:
 594                if user.is_active:
 595                    login(request, user)
 596                    # Redirect to a success page.
 597                else:
 598                    # Return a 'disabled account' error message
 599            else:
 600                # Return an 'invalid login' error message.
 601
 602.. admonition:: Calling ``authenticate()`` first
 603
 604    When you're manually logging a user in, you *must* call
 605    :func:`~django.contrib.auth.authenticate()` before you call
 606    :func:`~django.contrib.auth.login()`.
 607    :func:`~django.contrib.auth.authenticate()`
 608    sets an attribute on the :class:`~django.contrib.auth.models.User` noting
 609    which authentication backend successfully authenticated that user (see the
 610    `backends documentation`_ for details), and this information is needed
 611    later during the login process.
 612
 613.. _backends documentation: #other-authentication-sources
 614
 615Manually checking a user's password
 616-----------------------------------
 617
 618.. currentmodule:: django.contrib.auth.models
 619
 620.. function:: check_password()
 621
 622    If you'd like to manually authenticate a user by comparing a plain-text
 623    password to the hashed password in the database, use the convenience
 624    function :func:`django.contrib.auth.models.check_password`. It takes two
 625    arguments: the plain-text password to check, and the full value of a user's
 626    ``password`` field in the database to check against, and returns ``True``
 627    if they match, ``False`` otherwise.
 628
 629How to log a user out
 630---------------------
 631
 632.. currentmodule:: django.contrib.auth
 633
 634.. function:: logout()
 635
 636    To log out a user who has been logged in via
 637    :func:`django.contrib.auth.login()`, use
 638    :func:`django.contrib.auth.logout()` within your view. It takes an
 639    :class:`~django.http.HttpRequest` object and has no return value.
 640    Example::
 641
 642        from django.contrib.auth import logout
 643
 644        def logout_view(request):
 645            logout(request)
 646            # Redirect to a success page.
 647
 648    Note that :func:`~django.contrib.auth.logout()` doesn't throw any errors if
 649    the user wasn't logged in.
 650
 651    When you call :func:`~django.contrib.auth.logout()`, the session data for
 652    the current request is completely cleaned out. All existing data is
 653    removed. This is to prevent another person from using the same Web browser
 654    to log in and have access to the previous user's session data. If you want
 655    to put anything into the session that will be available to the user
 656    immediately after logging out, do that *after* calling
 657    :func:`django.contrib.auth.logout()`.
 658
 659.. _topics-auth-signals:
 660
 661Login and logout signals
 662------------------------
 663
 664.. versionadded:: 1.3
 665
 666The auth framework uses two :doc:`signals </topics/signals>` that can be used
 667for notification when a user logs in or out.
 668
 669.. data:: django.contrib.auth.signals.user_logged_in
 670
 671Sent when a user logs in successfully.
 672
 673Arguments sent with this signal:
 674
 675    ``sender``
 676        As above: the class of the user that just logged in.
 677
 678    ``request``
 679        The current :class:`~django.http.HttpRequest` instance.
 680
 681    ``user``
 682        The user instance that just logged in.
 683
 684.. data:: django.contrib.auth.signals.user_logged_out
 685
 686Sent when the logout method is called.
 687
 688    ``sender``
 689        As above: the class of the user that just logged out or ``None``
 690        if the user was not authenticated.
 691
 692    ``request``
 693        The current :class:`~django.http.HttpRequest` instance.
 694
 695    ``user``
 696        The user instance that just logged out or ``None`` if the
 697        user was not authenticated.
 698
 699Limiting access to logged-in users
 700----------------------------------
 701
 702The raw way
 703~~~~~~~~~~~
 704
 705The simple, raw way to limit access to pages is to check
 706:meth:`request.user.is_authenticated()
 707<django.contrib.auth.models.User.is_authenticated()>` and either redirect to a
 708login page::
 709
 710    from django.http import HttpResponseRedirect
 711
 712    def my_view(request):
 713        if not request.user.is_authenticated():
 714            return HttpResponseRedirect('/login/?next=%s' % request.path)
 715        # ...
 716
 717...or display an error message::
 718
 719    def my_view(request):
 720        if not request.user.is_authenticated():
 721            return render_to_response('myapp/login_error.html')
 722        # ...
 723
 724The login_required decorator
 725~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 726
 727.. function:: decorators.login_required([redirect_field_name=REDIRECT_FIELD_NAME, login_url=None])
 728
 729    As a shortcut, you can use the convenient
 730    :func:`~django.contrib.auth.decorators.login_required` decorator::
 731
 732        from django.contrib.auth.decorators import login_required
 733
 734        @login_required
 735        def my_view(request):
 736            ...
 737
 738    :func:`~django.contrib.auth.decorators.login_required` does the following:
 739
 740    * If the user isn't logged in, redirect to
 741      :setting:`settings.LOGIN_URL <LOGIN_URL>`, passing the current absolute
 742      path in the query string. Example: ``/accounts/login/?next=/polls/3/``.
 743
 744    * If the user is logged in, execute the view normally. The view code is
 745      free to assume the user is logged in.
 746
 747    By default, the path that the user should be redirected to upon
 748    successful authentication is stored in a query string parameter called
 749    ``"next"``. If you would prefer to use a different name for this parameter,
 750    :func:`~django.contrib.auth.decorators.login_required` takes an
 751    optional ``redirect_field_name`` parameter::
 752
 753        from django.contrib.auth.decorators import login_required
 754
 755        @login_required(redirect_field_name='my_redirect_field')
 756        def my_view(request):
 757            ...
 758
 759    Note that if you provide a value to ``redirect_field_name``, you will most
 760    likely need to customize your login template as well, since the template
 761    context variable which stores the redirect path will use the value of
 762    ``redirect_field_name`` as it's key rather than ``"next"`` (the default).
 763
 764    .. versionadded:: 1.3
 765
 766    :func:`~django.contrib.auth.decorators.login_required` also takes an
 767    optional ``login_url`` parameter. Example::
 768
 769        from django.contrib.auth.decorators import login_required
 770
 771        @login_required(login_url='/accounts/login/')
 772        def my_view(request):
 773            ...
 774
 775    Note that if you don't specify the ``login_url`` parameter, you'll need to map
 776    the appropriate Django view to :setting:`settings.LOGIN_URL <LOGIN_URL>`. For
 777    example, using the defaults, add the following line to your URLconf::
 778
 779        (r'^accounts/login/$', 'django.contrib.auth.views.login'),
 780
 781.. function:: views.login(request, [template_name, redirect_field_name, authentication_form])
 782
 783    Here's what ``django.contrib.auth.views.login`` does:
 784
 785        * If called via ``GET``, it displays a login form that POSTs to the
 786          same URL. More on this in a bit.
 787
 788        * If called via ``POST``, it tries to log the user in. If login is
 789          successful, the view redirects to the URL specified in ``next``. If
 790          ``next`` isn't provided, it redirects to
 791          :setting:`settings.LOGIN_REDIRECT_URL <LOGIN_REDIRECT_URL>` (which
 792          defaults to ``/accounts/profile/``). If login isn't successful, it
 793          redisplays the login form.
 794
 795    It's your responsibility to provide the login form in a template called
 796    ``registration/login.html`` by default. This template gets passed four
 797    template context variables:
 798
 799        * ``form``: A :class:`~django.forms.Form` object representing the login
 800          form. See the :doc:`forms documentation </topics/forms/index>` for
 801          more on ``Form`` objects.
 802
 803        * ``next``: The URL to redirect to after successful login. This may
 804          contain a query string, too.
 805
 806        * ``site``: The current :class:`~django.contrib.sites.models.Site`,
 807          according to the :setting:`SITE_ID` setting. If you don't have the
 808          site framework installed, this will be set to an instance of
 809          :class:`~django.contrib.sites.models.RequestSite`, which derives the
 810          site name and domain from the current
 811          :class:`~django.http.HttpRequest`.
 812
 813        * ``site_name``: An alias for ``site.name``. If you don't have the site
 814          framework installed, this will be set to the value of
 815          :attr:`request.META['SERVER_NAME'] <django.http.HttpRequest.META>`.
 816          For more on sites, see :doc:`/ref/contrib/sites`.
 817
 818    If you'd prefer not to call the template :file:`registration/login.html`,
 819    you can pass the ``template_name`` parameter via the extra arguments to
 820    the view in your URLconf. For example, this URLconf line would use
 821    :file:`myapp/login.html` instead::
 822
 823        (r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'myapp/login.html'}),
 824
 825    You can also specify the name of the ``GET`` field which contains the URL
 826    to redirect to after login by passing ``redirect_field_name`` to the view.
 827    By default, the field is called ``next``.
 828
 829    Here's a sample :file:`registration/login.html` template you can use as a
 830    starting point. It assumes you have a :file:`base.html` template that
 831    defines a ``content`` block:
 832
 833    .. code-block:: html+django
 834
 835        {% extends "base.html" %}
 836        {% load url from future %}
 837
 838        {% block content %}
 839
 840        {% if form.errors %}
 841        <p>Your username and password didn't match. Please try again.</p>
 842        {% endif %}
 843
 844        <form method="post" action="{% url 'django.contrib.auth.views.login' %}">
 845        {% csrf_token %}
 846        <table>
 847        <tr>
 848            <td>{{ form.username.label_tag }}</td>
 849            <td>{{ form.username }}</td>
 850        </tr>
 851        <tr>
 852            <td>{{ form.password.label_tag }}</td>
 853            <td>{{ form.password }}</td>
 854        </tr>
 855        </table>
 856
 857        <input type="submit" value="login" />
 858        <input type="hidden" name="next" value="{{ next }}" />
 859        </form>
 860
 861        {% endblock %}
 862
 863    .. versionadded:: 1.2
 864
 865    If you are using alternate authentication (see
 866    :ref:`authentication-backends`) you can pass a custom authentication form
 867    to the login view via the ``authentication_form`` parameter. This form must
 868    accept a ``request`` keyword argument in its ``__init__`` method, and
 869    provide a ``get_user`` method which returns the authenticated user object
 870    (this method is only ever called after successful form validation).
 871
 872    .. _forms documentation: ../forms/
 873    .. _site framework docs: ../sites/
 874
 875Other built-in views
 876--------------------
 877
 878.. module:: django.contrib.auth.views
 879
 880In addition to the :func:`~views.login` view, the authentication system
 881includes a few other useful built-in views located in
 882:mod:`django.contrib.auth.views`:
 883
 884.. function:: logout(request, [next_page, template_name, redirect_field_name])
 885
 886    Logs a user out.
 887
 888    **Optional arguments:**
 889
 890        * ``next_page``: The URL to redirect to after logout.
 891
 892        * ``template_name``: The full name of a template to display after
 893          logging the user out. This will default to
 894          :file:`registration/logged_out.html` if no argument is supplied.
 895
 896        * ``redirect_field_name``: The name of a ``GET`` field containing the
 897          URL to redirect to after log out. Overrides ``next_page`` if the given
 898          ``GET`` parameter is passed.
 899
 900    **Template context:**
 901
 902        * ``title``: The string "Logged out", localized.
 903
 904.. function:: logout_then_login(request[, login_url])
 905
 906    Logs a user out, then redirects to the login page.
 907
 908    **Optional arguments:**
 909
 910        * ``login_url``: The URL of the login page to redirect to. This will
 911          default to :setting:`settings.LOGIN_URL <LOGIN_URL>` if not supplied.
 912
 913.. function:: password_change(request[, template_name, post_change_redirect, password_change_form])
 914
 915    Allows a user to change their password.
 916
 917    **Optional arguments:**
 918
 919        * ``template_name``: The full name of a template to use for
 920          displaying the password change form. This will default to
 921          :file:`registration/password_change_form.html` if not supplied.
 922
 923        * ``post_change_redirect``: The URL to redirect to after a successful
 924          password change.
 925
 926        * .. versionadded:: 1.2
 927
 928          ``password_change_form``: A custom "change password" form which must
 929          accept a ``user`` keyword argument. The form is responsible for
 930          actually changing the user's password.
 931
 932
 933    **Template context:**
 934
 935        * ``form``: The password change form.
 936
 937.. function:: password_change_done(request[, template_name])
 938
 939    The page shown after a user has changed their password.
 940
 941    **Optional arguments:**
 942
 943        * ``template_name``: The full name of a template to use. This will
 944          default to :file:`registration/password_change_done.html` if not
 945          supplied.
 946
 947.. function:: password_reset(request[, is_admin_site, template_name, email_template_name, password_reset_form, token_generator, post_reset_redirect, from_email])
 948
 949    Allows a user to reset their password by generating a one-time use link
 950    that can be used to reset the password, and sending that link to the
 951    user's registered e-mail address.
 952
 953    .. versionchanged:: 1.3
 954        The ``from_email`` argument was added.
 955
 956    **Optional arguments:**
 957
 958        * ``template_name``: The full name of a template to use for
 959          displaying the password reset form. This will default to
 960          :file:`registration/password_reset_form.html` if not supplied.
 961
 962        * ``email_template_name``: The full name of a template to use for
 963          generating the e-mail with the new password. This will default to
 964          :file:`registration/password_reset_email.html` if not supplied.
 965
 966        * ``password_reset_form``: Form that will be used to set the password.
 967          Defaults to :class:`~django.contrib.auth.forms.PasswordResetForm`.
 968
 969        * ``token_generator``: Instance of the class to check the password. This
 970          will default to ``default_token_generator``, it's an instance of
 971          ``django.contrib.auth.tokens.PasswordResetTokenGenerator``.
 972
 973        * ``post_reset_redirect``: The URL to redirect to after a successful
 974          password change.
 975
 976        * ``from_email``: A valid e-mail address. By default Django uses
 977          the :setting:`DEFAULT_FROM_EMAIL`.
 978
 979    **Template context:**
 980
 981        * ``form``: The form for resetting the user's password.
 982
 983.. function:: password_reset_done(request[, template_name])
 984
 985    The page shown after a user has been emailed a link to reset their
 986    password. This view is called by default if the :func:`password_reset` view
 987    doesn't have an explicit ``post_reset_redirect`` URL set.
 988
 989    **Optional arguments:**
 990
 991        * ``template_name``: The full name of a template to use. This will
 992          default to :file:`registration/password_reset_done.html` if not
 993          supplied.
 994
 995.. function:: password_reset_confirm(request[, uidb36, token, template_name, token_generator, set_password_form, post_reset_redirect])
 996
 997    Presents a form for entering a new password.
 998
 999    **Optional arguments:**
1000
1001        * ``uidb36``: The user's id encoded in base 36. This will default to
1002          ``None``.
1003        * ``token``: Token to check that the password is valid. This will default to ``None``.
1004        * ``template_name``: The full name of a template to display the confirm
1005          password view. Default value is :file:`registration/password_reset_confirm.html`.
1006        * ``token_generator``: Instance of the class to check the password. This
1007          will default to ``default_token_generator``, it's an instance of
1008          ``django.contrib.auth.tokens.PasswordResetTokenGenerator``.
1009        * ``set_password_form``: Form that will be used to set the password.
1010          This will default to ``SetPasswordForm``.
1011        * ``post_reset_redirect``: URL to redirect after the password reset
1012          done. This will default to ``None``.
1013
1014.. function:: password_reset_complete(request[,template_name])
1015
1016   Presents a view which informs the user that the password has been
1017   successfully changed.
1018
1019   **Optional arguments:**
1020
1021       * ``template_name``: The full name of a template to display the view.
1022         This will default to :file:`registration/password_reset_complete.html`.
1023
1024Helper functions
1025----------------
1026
1027.. currentmodule:: django.contrib.auth.views
1028
1029.. function:: redirect_to_login(next[, login_url, redirect_field_name])
1030
1031    Redirects to the login page, and then back to another URL after a
1032    successful login.
1033
1034    **Required arguments:**
1035
1036        * ``next``: The URL to redirect to after a successful login.
1037
1038    **Optional arguments:**
1039
1040        * ``login_url``: The URL of the login page to redirect to. This will
1041          default to :setting:`settings.LOGIN_URL <LOGIN_URL>` if not supplied.
1042
1043        * ``redirect_field_name``: The name of a ``GET`` field containing the
1044          URL to redirect to after log out. Overrides ``next`` if the given
1045          ``GET`` parameter is passed.
1046
1047Built-in forms
1048--------------
1049
1050.. module:: django.contrib.auth.forms
1051
1052If you don't want to use the built-in views, but want the convenience of not
1053having to write forms for this functionality, the authentication system
1054provides several built-in forms located in :mod:`django.contrib.auth.forms`:
1055
1056.. class:: AdminPasswordChangeForm
1057
1058    A form used in the admin interface to change a user's password.
1059
1060.. class:: AuthenticationForm
1061
1062    A form for logging a user in.
1063
1064.. class:: PasswordChangeForm
1065
1066    A form for allowing a user to change their password.
1067
1068.. class:: PasswordResetForm
1069
1070    A form for generating and e-mailing a one-time use link to reset a
1071    user's password.
1072
1073.. class:: SetPasswordForm
1074
1075    A form that lets a user change his/her password without entering the old
1076    password.
1077
1078.. class:: UserChangeForm
1079
1080    A form used in the admin interface to change a user's information and
1081    permissions.
1082
1083.. class:: UserCreationForm
1084
1085    A form for creating a new user.
1086
1087Limiting access to logged-in users that pass a test
1088---------------------------------------------------
1089
1090.. currentmodule:: django.contrib.auth.decorators
1091
1092To limit access based on certain permissions or some other test, you'd do
1093essentially the same thing as described in the previous section.
1094
1095The simple way is to run your test on :attr:`request.user
1096<django.http.HttpRequest.user>` in the view directly. For example, this view
1097checks to make sure the user is logged in and has the permission
1098``polls.can_vote``::
1099
1100    def my_view(request):
1101        if not request.user.has_perm('polls.can_vote'):
1102            return HttpResponse("You can't vote in this poll.")
1103        # ...
1104
1105.. function:: user_passes_test()
1106
1107    As a shortcut, you can use the convenient ``user_passes_test`` decorator::
1108
1109        from django.contrib.auth.decorators import user_passes_test
1110
1111        @user_passes_test(lambda u: u.has_perm('polls.can_vote'))
1112        def my_view(request):
1113            ...
1114
1115    We're using this particular test as a relatively simple example. However,
1116    if you just want to test whether a permission is available to a user, you
1117    can use the :func:`~django.contrib.auth.decorators.permission_required()`
1118    decorator, described later in this document.
1119
1120    :func:`~django.contrib.auth.decorators.user_passes_test` takes a required
1121    argument: a callable that takes a
1122    :class:`~django.contrib.auth.models.User` object and returns ``True`` if
1123    the user is allowed to view the page. Note that
1124    :func:`~django.contrib.auth.decorators.user_passes_test` does not
1125    automatically check that the :class:`~django.contrib.auth.models.User` is
1126    not anonymous.
1127
1128    :func:`~django.contrib.auth.decorators.user_passes_test()` takes an
1129    optional ``login_url`` argument, which lets you specify the URL for your
1130    login page (:setting:`settings.LOGIN_URL <LOGIN_URL>` by default).
1131
1132    For example::
1133
1134        from django.contrib.auth.decorators import user_passes_test
1135
1136        @user_passes_test(lambda u: u.has_perm('polls.can_vote'), login_url='/login/')
1137        def my_view(request):
1138            ...
1139
1140The permission_required decorator
1141~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1142
1143.. function:: permission_required()
1144
1145    It's a relatively common task to check whether a user has a particular
1146    permission. For that reason, Django provides a shortcut for that case: the
1147    :func:`~django.contrib.auth.decorators.permission_required()` decorator.
1148    Using this decorator, the earlier example can be written as::
1149
1150        from django.contrib.auth.decorators import permission_required
1151
1152        @permission_required('polls.can_vote')
1153        def my_view(request):
1154            ...
1155
1156    As for the :meth:`User.has_perm` method, permission names take the form
1157    ``"<app label>.<permission codename>"`` (i.e. ``polls.can_vote`` for a
1158    permission on a model in the ``polls`` application).
1159
1160    Note that :func:`~django.contrib.auth.decorators.permission_required()`
1161    also takes an optional ``login_url`` parameter. Example::
1162
1163        from django.contrib.auth.decorators import permission_required
1164
1165        @permission_required('polls.can_vote', login_url='/loginpage/')
1166        def my_view(request):
1167            ...
1168
1169    As in the :func:`~decorators.login_required` decorator, ``login_url``
1170    defaults to :setting:`settings.LOGIN_URL <LOGIN_URL>`.
1171
1172.. currentmodule:: django.contrib.auth
1173
1174Limiting access to generic views
1175--------------------------------
1176
1177To limit access to a :doc:`generic view </ref/generic-views>`, write a thin
1178wrapper around the view, and point your URLconf to your wrapper instead of the
1179generic view itself. For example::
1180
1181    from django.views.generic.date_based import object_detail
1182
1183    @login_required
1184    def limited_object_detail(*args, **kwargs):
1185        return object_detail(*args, **kwargs)
1186
1187.. _permissions:
1188
1189Permissions
1190===========
1191
1192Django comes with a simple permissions system. It provides a way to assign
1193permissions to specific users and groups of users.
1194
1195It's used by the Django admin site, but you're welcome to use it in your own
1196code.
1197
1198The Django admin site uses permissions as follows:
1199
1200    * Access to view the "add" form and add an object is limited to users with
1201      the "add" permission for that type of object.
1202    * Access to view the change list, view the "change" form and change an
1203      object is limited to users with the "change" permission for that type of
1204      object.
1205    * Access to delete an object is limited to users with the "delete"
1206      permission for that type of object.
1207
1208Permissions are set globally per type of object, not per specific object
1209instance. For example, it's possible to say "Mary may change news stories," but
1210it's not currently possible to say "Mary may change news stories, but only the
1211ones she created herself" or "Mary may only change news stories that have a
1212certain status, publication date or ID." The latter functionality is something
1213Django developers are currently discussing.
1214
1215Default permissions
1216-------------------
1217
1218When ``django.contrib.auth`` is listed in your :setting:`INSTALLED_APPS`
1219setting, it will ensure that three default permissions -- add, change and
1220delete -- are created for each Django model defined in one of your installed
1221applications.
1222
1223These permissions will be created when you run :djadmin:`manage.py syncdb
1224<syncdb>`; the first time you run ``syncdb`` after adding
1225``django.contrib.auth`` to :setting:`INSTALLED_APPS`, the default permissions
1226will be created for all previously-installed models, as well as for any new
1227models being installed at that time. Afterward, it will create default
1228permissions for new models each time you run :djadmin:`manage.py syncdb
1229<syncdb>`.
1230
1231Assuming you have an application with an
1232:attr:`~django.db.models.Options.app_label` ``foo`` and a model named ``Bar``,
1233to test for basic permissions you should use:
1234
1235    * add: ``user.has_perm('foo.add_bar')``
1236    * change: ``user.has_perm('foo.change_bar')``
1237    * delete: ``user.has_perm('foo.delete_bar')``
1238
1239.. _custom-permissions:
1240
1241Custom permissions
1242------------------
1243
1244To create custom permissions for a given model object, use the ``permissions``
1245:ref:`model Meta attribute <meta-options>`.
1246
1247This example Task model creates three custom permissions, i.e., actions users
1248can or cannot do with Task instances, specific to your application::
1249
1250    class Task(models.Model):
1251        ...
1252        class Meta:
1253            permissions = (
1254                ("can_view", "Can see available tasks"),
1255                ("can_change_status", "Can change the status of tasks"),
1256                ("can_close", "Can remove a task by setting its status as closed"),
1257            )
1258
1259The only thing this does is create those extra permissions when you run
1260:djadmin:`manage.py syncdb <syncdb>`. Your code is in charge of checking the
1261value of these permissions when an user is trying to access the functionality
1262provided by the application (viewing tasks, changing the status of tasks,
1263closing tasks.)
1264
1265API reference
1266-------------
1267
1268.. currentmodule:: django.contrib.auth.models
1269
1270.. class:: Permission
1271
1272    Just like users, permissions are implemented in a Django model that lives
1273    in `django/contrib/auth/models.py`_.
1274
1275.. _django/contrib/auth/models.py: http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/models.py
1276
1277Fields
1278~~~~~~
1279
1280:class:`~django.contrib.auth.models.Permission` objects have the following
1281fields:
1282
1283.. attribute:: Permission.name
1284
1285    Required. 50 characters or fewer. Example: ``'Can vote'``.
1286
1287.. attribute:: Permission.content_type
1288
1289    Required. A reference to the ``django_content_type`` database table, which
1290    contains a record for each installed Django model.
1291
1292.. attribute:: Permission.codename
1293
1294    Required. 100 characters or fewer. Example: ``'can_vote'``.
1295
1296Methods
1297~~~~~~~
1298
1299:class:`~django.contrib.auth.models.Permission` objects have the standard
1300data-access methods like any other :doc:`Django model </ref/models/instances>`.
1301
1302.. currentmodule:: django.contrib.auth
1303
1304Authentication data in templates
1305================================
1306
1307The currently logged-in user and his/her permissions are made available in the
1308:doc:`template context </ref/templates/api>` when you use
1309:class:`~django.template.context.RequestContext`.
1310
1311.. admonition:: Technicality
1312
1313   Technically, these variables are only made available in the template context
1314   if you use :class:`~django.template.context.RequestContext` *and* your
1315   :setting:`TEMPLATE_CONTEXT_PROCESSORS` setting contains
1316   ``"django.contrib.auth.context_processors.auth"``, which is default. For
1317   more, see the :ref:`RequestContext docs <subclassing-context-requestcontext>`.
1318
1319Users
1320-----
1321
1322When rendering a template :class:`~django.template.context.RequestContext`, the
1323currently logged-in user, either a  :class:`~django.contrib.auth.models.User`
1324instance or an :class:`~django.contrib.auth.models.AnonymousUser` instance, is
1325stored in the template variable ``{{ user }}``:
1326
1327.. code-block:: html+django
1328
1329    {% if user.is_authenticated %}
1330        <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
1331    {% else %}
1332        <p>Welcome, new user. Please log in.</p>
1333    {% endif %}
1334
1335This template context variable is not available if a ``RequestContext`` is not
1336being used.
1337
1338Permissions
1339-----------
1340
1341The currently logged-in user's permissions are stored in the template variable
1342``{{ perms }}``. This is an instance of
1343:class:`django.contrib.auth.context_processors.PermWrapper`, which is a
1344template-friendly proxy of permissions.
1345
1346.. versionchanged:: 1.3
1347    Prior to version 1.3, ``PermWrapper`` was located in
1348    ``django.contrib.auth.context_processors``.
1349
1350In the ``{{ perms }}`` object, single-attribute lookup is a proxy to
1351:meth:`User.has_module_perms <django.contrib.auth.models.User.has_module_perms>`.
1352This example would display ``True`` if the logged-in user had any permissions
1353in the ``foo`` app::
1354
1355    {{ perms.foo }}
1356
1357Two-level-attribute lookup is a proxy to
1358:meth:`User.has_perm <django.contrib.auth.models.User.has_perm>`. This example
1359would display ``True`` if the logged-in user had the permission
1360``foo.can_vote``::
1361
1362    {{ perms.foo.can_vote }}
1363
1364Thus, you can check permissions in template ``{% if %}`` statements:
1365
1366.. code-block:: html+django
1367
1368    {% if perms.foo %}
1369        <p>You have permission to do something in the foo app.</p>
1370        {% if perms.foo.can_vote %}
1371            <p>You can vote!</p>
1372        {% endif %}
1373        {% if perms.foo.can_drive %}
1374            <p>You can drive!</p>
1375        {% endif %}
1376    {% else %}
1377        <p>You don't have permission to do anything in the foo app.</p>
1378    {% endif %}
1379
1380Groups
1381======
1382
1383Groups are a generic way of categorizing users so you can apply permissions, or
1384some other label, to those users. A user can belong to any number of groups.
1385
1386A user in a group automatically has the permissions granted to that group. For
1387example, if the group ``Site editors`` has the permission
1388``can_edit_home_page``, any user in that group will have that permission.
1389
1390Beyond permissions, groups are a convenient way to categorize users to give
1391them some label, or extended functionality. For example, you could create a
1392group ``'Special users'``, and you could write code that could, say, give them
1393access to a members-only portion of your site, or send them members-only e-mail
1394messages.
1395
1396Messages
1397========
1398
1399.. deprecated:: 1.2
1400   This functionality will be removed in Django 1.4.  You should use the
1401   :doc:`messages framework </ref/contrib/messages>` for all new projects and
1402   begin to update your existing code immediately.
1403
1404The message system is a lightweight way to queue messages for given users.
1405
1406A message is associated with a :class:`~django.contrib.auth.models.User`.
1407There's no concept of expiration or timestamps.
1408
1409Messages are used by the Django admin after successful actions. For example,
1410``"The poll Foo was created successfully."`` is a message.
1411
1412The API is simple:
1413
1414.. method:: models.User.message_set.create(message)
1415
1416    To create a new message, use
1417    ``user_obj.message_set.create(message='message_text')``.
1418
1419    To retrieve/delete messages, use
1420    :meth:`user_obj.get_and_delete_messages() <django.contrib.auth.models.User.get_and_delete_messages>`,
1421    which returns a list of ``Message`` objects in the user's queue (if any)
1422    and deletes the messages from the queue.
1423
1424In this example view, the system saves a message for the user after creating
1425a playlist::
1426
1427    def create_playlist(request, songs):
1428        # Create the playlist with the given songs.
1429        # ...
1430        request.user.message_set.create(message="Your playlist was added successfully.")
1431        return render_to_response("playlists/create.html",
1432            context_instance=RequestContext(request))
1433
1434When you use :class:`~django.template.context.RequestContext`, the currently
1435logged-in user and his/her messages are made available in the
1436:doc:`template context </ref/templates/api>` as the template variable
1437``{{ messages }}``. Here's an example of template code that displays messages:
1438
1439.. code-block:: html+django
1440
1441    {% if messages %}
1442    <ul>
1443        {% for message in messages %}
1444        <li>{{ message }}</li>
1445        {% endfor %}
1446    </ul>
1447    {% endif %}
1448
1449.. versionchanged:: 1.2
1450   The ``messages`` template variable uses a backwards compatible method in the
1451   :doc:`messages framework </ref/contrib/messages>` to retrieve messages from
1452   both the user ``Message`` model and from the new framework.  Unlike in
1453   previous revisions, the messages will not be erased unless they are actually
1454   displayed.
1455
1456Finally, note that this messages framework only works with users in the user
1457database. To send messages to anonymous users, use the
1458:doc:`messages framework </ref/contrib/messages>`.
1459
1460.. _authentication-backends:
1461
1462Other authentication sources
1463============================
1464
1465The authentication that comes with Django is good enough for most common cases,
1466but you may have the need to hook into another authentication source -- that
1467is, another source of usernames and passwords or authentication methods.
1468
1469For example, your company may already have an LDAP setup that stores a username
1470and password for every employee. It'd be a hassle for both the network
1471administrator and the users themselves if users had separate accounts in LDAP
1472and the Django-based applications.
1473
1474So, to handle situations like this, the Django authentication system lets you
1475plug in other authentication sources. You can override Django's default
1476database-based scheme, or you can use the default system in tandem with other
1477systems.
1478
1479See the :doc:`authentication backend reference </ref/authbackends>`
1480for information on the authentication backends included with Django.
1481
1482Specifying authentication backends
1483----------------------------------
1484
1485Behind the scenes, Django maintains a list of "authentication backends" that it
1486checks for authentication. When somebody calls
1487:func:`django.contrib.auth.authenticate()` -- as described in :ref:`How to log
1488a user in <how-to-log-a-user-in>` above -- Django tries authenticating across
1489all of its authentication backends. If the first authentication method fails,
1490Django tries the second one, and so on, until all backends have been attempted.
1491
1492The list of authentication backends to use is specified in the
1493:setting:`AUTHENTICATION_BACKENDS` setting. This should be a tuple of Python
1494path names that point to Python classes that know how to authenticate. These
1495classes can be anywhere on your Python path.
1496
1497By default, :setting:`AUTHENTICATION_BACKENDS` is set to::
1498
1499    ('django.contrib.auth.backends.ModelBackend',)
1500
1501That's the basic authentication scheme that checks the Django users database.
1502
1503The order of :setting:`AUTHENTICATION_BACKENDS` matters, so if the same
1504username and password is valid in multiple backends, Django will stop
1505processing at the first positive match.
1506
1507.. note::
1508
1509    Once a user has authenticated, Django stores which backend was used to
1510    authenticate the user in the user's session, and re-uses the same backend
1511    for subsequent authentication attempts for that user. This effectively means
1512    that authentication sources are cached, so if you change
1513    :setting:`AUTHENTICATION_BACKENDS`, you'll need to clear out session data if
1514    you need to force users to re-authenticate using different methods. A simple
1515    way to do that is simply to execute ``Session.objects.all().delete()``.
1516
1517Writing an authentication backend
1518---------------------------------
1519
1520An authentication backend is a class that implements two methods:
1521``get_user(user_id)`` and ``authenticate(**credentials)``.
1522
1523The ``get_user`` method takes a ``user_id`` -- which could be a username,
1524database ID or whatever -- and returns a ``User`` object.
1525
1526The ``authenticate`` method takes credentials as keyword arguments. Most of
1527the time, it'll just look like this::
1528
1529    class MyBackend:
1530        def authenticate(self, username=None, password=None):
1531            # Check the username/password and return a User.
1532
1533But it could also authenticate a token, like so::
1534
1535    class MyBackend:
1536        def authenticate(self, token=None):
1537            # Check the token and return a User.
1538
1539Either way, ``authenticate`` should check the credentials it gets, and it
1540should return a ``User`` object that matches those credentials, if the
1541credentials are valid. If they're not valid, it should return ``None``.
1542
1543The Django admin system is tightly coupled to the Django ``User`` object
1544described at the beginning of this document. For now, the best way to deal with
1545this is to create a Django ``User`` object for each user that exists for your
1546backend (e.g., in your LDAP directory, your external SQL database, etc.) You
1547can either write a script to do this in advance, or your ``authenticate``
1548method can do it the first time a user logs in.
1549
1550Here's an example backend that authenticates against a username and password
1551variable defined in your ``settings.py`` file and creates a Django ``User``
1552object the first time a user authenticates::
1553
1554    from django.conf import settings
1555    from django.contrib.auth.models import User, check_password
1556
1557    class SettingsBackend:
1558        """
1559        Authenticate against the settings ADMIN_LOGIN and ADMIN_PASSWORD.
1560
1561        Use the login name, and a hash of the password. For example:
1562
1563        ADMIN_LOGIN = 'admin'
1564        ADMIN_PASSWORD = 'sha1$4e987$afbcf42e21bd417fb71db8c66b321e9fc33051de'
1565        """
1566
1567        supports_object_permissions = False
1568        supports_anonymous_user = False
1569        supports_inactive_user = False
1570
1571        def authenticate(self, username=None, password=None):
1572            login_valid = (settings.ADMIN_LOGIN == username)
1573            pwd_valid = check_password(password, settings.ADMIN_PASSWORD)
1574            if login_valid and pwd_valid:
1575                try:
1576                    user = User.objects.get(username=username)
1577                except User.DoesNotExist:
1578                    # Create a new user. Note that we can set password
1579                    # to anything, because it won't be checked; the password
1580                    # from settings.py will.
1581                    user = User(username=username, password='get from settings.py')
1582                    user.is_staff = True
1583                    user.is_superuser = True
1584                    user.save()
1585                return user
1586            return None
1587
1588        def get_user(self, user_id):
1589            try:
1590                return User.objects.get(pk=user_id)
1591            except User.DoesNotExist:
1592                return None
1593
1594Handling authorization in custom backends
1595-----------------------------------------
1596
1597Custom auth backends can provide their own permissions.
1598
1599The user model will delegate permission lookup functions
1600(:meth:`~django.contrib.auth.models.User.get_group_permissions()`,
1601:meth:`~django.contrib.auth.models.User.get_all_permissions()`,
1602:meth:`~django.contrib.auth.models.User.has_perm()`, and
1603:meth:`~django.contrib.auth.models.User.has_module_perms()`) to any
1604authentication backend that implements these functions.
1605
1606The permissions given to the user will be the superset of all permissions
1607returned by all backends. That is, Django grants a permission to a user that
1608any one backend grants.
1609
1610The simple backend above could implement permissions for the magic admin
1611fairly simply::
1612
1613    class SettingsBackend:
1614
1615        # ...
1616
1617        def has_perm(self, user_obj, perm):
1618            if user_obj.username == settings.ADMIN_LOGIN:
1619                return True
1620            else:
1621                return False
1622
1623This gives full permissions to the user granted access in the above example.
1624Notice that the backend auth functions all take the user object as an argument,
1625and they also accept the same arguments given to the associated
1626:class:`django.contrib.auth.models.User` functions.
1627
1628A full authorization implementation can be found in
1629`django/contrib/auth/backends.py`_, which is the default backend and queries
1630the ``auth_permission`` table most of the time.
1631
1632.. _django/contrib/auth/backends.py: http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/backends.py
1633
1634Authorization for anonymous users
1635~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1636
1637.. versionchanged:: 1.2
1638
1639An anonymous user is one that is not authenticated i.e. they have provided no
1640valid authentication details. However, that does not necessarily mean they are
1641not authorized to do anything. At the most basic level, most Web sites
1642authorize anonymous users to browse most of the site, and many allow anonymous
1643posting of comments etc.
1644
1645Django's permission framework does not have a place to store permissions for
1646anonymous users. However, it has a foundation that allows custom authentication
1647backends to specify authorization for anonymous users. This is especially useful
1648for the authors of re-usable apps, who can delegate all questions of authorization
1649to the auth backend, rather than needing settings, for example, to control
1650anonymous access.
1651
1652To enable this in your own backend, you must set the class attribute
1653``supports_anonymous_user`` to ``True``. (This precaution is to maintain
1654compatibility with backends that assume that all user objects are actual
1655instances of the :class:`django.contrib.auth.models.User` class). With this
1656in place, :class:`django.contrib.auth.models.AnonymousUser` will delegate all
1657the relevant permission methods to the authentication backends.
1658
1659A nonexistent ``supports_anonymous_user`` attribute will raise a hidden
1660``PendingDeprecationWarning`` if used in Django 1.2. In Django 1.3, this
1661warning will be upgraded to a ``DeprecationWarning``, which will be displayed
1662loudly. Additionally ``supports_anonymous_user`` will be set to ``False``.
1663Django 1.4 will assume that every backend supports anonymous users being
1664passed to the authorization methods.
1665
1666Authorization for inactive users
1667~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1668
1669.. versionadded:: 1.3
1670
1671An inactive user is a one that is authenticated but has its attribute
1672``is_active`` set to ``False``. However this does not mean they are not
1673authorized to do anything. For example they are allowed to activate their
1674account.
1675
1676The support for anonymous users in the permission system allows for
1677anonymous users to have permissions to do something while inactive
1678authenticated users do not.
1679
1680To enable this on your own backend, you must set the class attribute
1681``supports_inactive_user`` to ``True``.
1682
1683A nonexisting ``supports_inactive_user`` attribute will raise a
1684``PendingDeprecationWarning`` if used in Django 1.3. In Django 1.4, this
1685warning will be updated to a ``DeprecationWarning`` which will be displayed
1686loudly. Additionally ``supports_inactive_user`` will be set to ``False``.
1687Django 1.5 will assume that every backend supports inactive users being
1688passed to the authorization methods.
1689
1690
1691Handling object permissions
1692---------------------------
1693
1694Django's permission framework has a foundation for object permissions, though
1695there is no implementation for it in the core. That means that checking for
1696object permissions will always return ``False`` or an empty list (depending on
1697the check performed).
1698
1699To enable object permissions in your own
1700:doc:`authentication backend </ref/authbackends>` you'll just have
1701to allow passing an ``obj`` parameter to the permission methods and set the
1702``supports_object_permissions`` class attribute to ``True``.
1703
1704A nonexistent ``supports_object_permissions`` will raise a hidden
1705``PendingDeprecationWarning`` if used in Django 1.2. In Django 1.3, this
1706warning will be upgraded to a ``DeprecationWarning``, which will be displayed
1707loudly. Additionally ``supports_object_permissions`` will be set to ``False``.
1708Django 1.4 will assume that every backend supports object permissions and
1709won't check for the existence of ``supports_object_permissions``, which
1710means not supporting ``obj`` as a parameter will raise a ``TypeError``.