auth.txt 61 KB

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