auth.txt 57 KB

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