auth.txt 57 KB

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