auth.txt 103 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696
  1. =============================
  2. User authentication in Django
  3. =============================
  4. .. module:: django.contrib.auth
  5. :synopsis: Django's authentication framework.
  6. Django comes with a user authentication system. It handles user accounts,
  7. groups, permissions and cookie-based user sessions. This document explains how
  8. things work.
  9. Overview
  10. ========
  11. The auth system consists of:
  12. * Users
  13. * Permissions: Binary (yes/no) flags designating whether a user may perform
  14. a certain task.
  15. * Groups: A generic way of applying labels and permissions to more than one
  16. user.
  17. Installation
  18. ============
  19. Authentication support is bundled as a Django application in
  20. ``django.contrib.auth``. To install it, do the following:
  21. 1. Put ``'django.contrib.auth'`` and ``'django.contrib.contenttypes'`` in
  22. your :setting:`INSTALLED_APPS` setting.
  23. (The :class:`~django.contrib.auth.models.Permission` model in
  24. :mod:`django.contrib.auth` depends on :mod:`django.contrib.contenttypes`.)
  25. 2. Run the command ``manage.py syncdb``.
  26. Note that the default :file:`settings.py` file created by
  27. :djadmin:`django-admin.py startproject <startproject>` includes
  28. ``'django.contrib.auth'`` and ``'django.contrib.contenttypes'`` in
  29. :setting:`INSTALLED_APPS` for convenience. If your :setting:`INSTALLED_APPS`
  30. already contains these apps, feel free to run :djadmin:`manage.py syncdb
  31. <syncdb>` again; you can run that command as many times as you'd like, and each
  32. time it'll only install what's needed.
  33. The :djadmin:`syncdb` command creates the necessary database tables, creates
  34. permission objects for all installed apps that need 'em, and prompts you to
  35. create a superuser account the first time you run it.
  36. Once you've taken those steps, that's it.
  37. Users
  38. =====
  39. .. class:: models.User
  40. API reference
  41. -------------
  42. Fields
  43. ~~~~~~
  44. .. class:: models.User
  45. :class:`~django.contrib.auth.models.User` objects have the following
  46. fields:
  47. .. attribute:: models.User.username
  48. Required. 30 characters or fewer. Usernames may contain alphanumeric,
  49. ``_``, ``@``, ``+``, ``.`` and ``-`` characters.
  50. .. attribute:: models.User.first_name
  51. Optional. 30 characters or fewer.
  52. .. attribute:: models.User.last_name
  53. Optional. 30 characters or fewer.
  54. .. attribute:: models.User.email
  55. Optional. Email address.
  56. .. attribute:: models.User.password
  57. Required. A hash of, and metadata about, the password. (Django doesn't
  58. store the raw password.) Raw passwords can be arbitrarily long and can
  59. contain any character. See the "Passwords" section below.
  60. .. attribute:: models.User.is_staff
  61. Boolean. Designates whether this user can access the admin site.
  62. .. attribute:: models.User.is_active
  63. Boolean. Designates whether this user account should be considered
  64. active. We recommend that you set this flag to ``False`` instead of
  65. deleting accounts; that way, if your applications have any foreign keys
  66. to users, the foreign keys won't break.
  67. This doesn't necessarily control whether or not the user can log in.
  68. Authentication backends aren't required to check for the ``is_active``
  69. flag, and the default backends do not. If you want to reject a login
  70. based on ``is_active`` being ``False``, it's up to you to check that in
  71. your own login view or a custom authentication backend. However, the
  72. :class:`~django.contrib.auth.forms.AuthenticationForm` used by the
  73. :func:`~django.contrib.auth.views.login` view (which is the default)
  74. *does* perform this check, as do the permission-checking methods such
  75. as :meth:`~models.User.has_perm` and the authentication in the Django
  76. admin. All of those functions/methods will return ``False`` for
  77. inactive users.
  78. .. attribute:: models.User.is_superuser
  79. Boolean. Designates that this user has all permissions without
  80. explicitly assigning them.
  81. .. attribute:: models.User.last_login
  82. A datetime of the user's last login. Is set to the current date/time by
  83. default.
  84. .. attribute:: models.User.date_joined
  85. A datetime designating when the account was created. Is set to the
  86. current date/time by default when the account is created.
  87. Methods
  88. ~~~~~~~
  89. .. class:: models.User
  90. :class:`~django.contrib.auth.models.User` objects have two many-to-many
  91. fields: ``groups`` and ``user_permissions``.
  92. :class:`~django.contrib.auth.models.User` objects can access their related
  93. objects in the same way as any other :doc:`Django model
  94. </topics/db/models>`:
  95. .. code-block:: python
  96. myuser.groups = [group_list]
  97. myuser.groups.add(group, group, ...)
  98. myuser.groups.remove(group, group, ...)
  99. myuser.groups.clear()
  100. myuser.user_permissions = [permission_list]
  101. myuser.user_permissions.add(permission, permission, ...)
  102. myuser.user_permissions.remove(permission, permission, ...)
  103. myuser.user_permissions.clear()
  104. In addition to those automatic API methods,
  105. :class:`~django.contrib.auth.models.User` objects have the following custom
  106. methods:
  107. .. method:: models.User.get_username()
  108. Returns the username for the user. Since the User model can be swapped
  109. out, you should use this method instead of referencing the username
  110. attribute directly.
  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. Marks the user as having no password set. This isn't the same as
  137. having a blank string for a password.
  138. :meth:`~django.contrib.auth.models.User.check_password()` for this user
  139. will never return ``True``. Doesn't save the
  140. :class:`~django.contrib.auth.models.User` object.
  141. You may need this if authentication for your application takes place
  142. against an existing external source such as an LDAP directory.
  143. .. method:: models.User.has_usable_password()
  144. Returns ``False`` if
  145. :meth:`~django.contrib.auth.models.User.set_unusable_password()` has
  146. been called for this user.
  147. .. method:: models.User.get_group_permissions(obj=None)
  148. Returns a set of permission strings that the user has, through his/her
  149. groups.
  150. If ``obj`` is passed in, only returns the group permissions for
  151. this specific object.
  152. .. method:: models.User.get_all_permissions(obj=None)
  153. Returns a set of permission strings that the user has, both through
  154. group and user permissions.
  155. If ``obj`` is passed in, only returns the permissions for this
  156. specific object.
  157. .. method:: models.User.has_perm(perm, obj=None)
  158. Returns ``True`` if the user has the specified permission, where perm is
  159. in the format ``"<app label>.<permission codename>"``. (see
  160. `permissions`_ section below). If the user is inactive, this method will
  161. always return ``False``.
  162. If ``obj`` is passed in, this method won't check for a permission for
  163. the model, but for this specific object.
  164. .. method:: models.User.has_perms(perm_list, obj=None)
  165. Returns ``True`` if the user has each of the specified permissions,
  166. where each perm is in the format
  167. ``"<app label>.<permission codename>"``. If the user is inactive,
  168. this method will always return ``False``.
  169. If ``obj`` is passed in, this method won't check for permissions for
  170. the model, but for the specific object.
  171. .. method:: models.User.has_module_perms(package_name)
  172. Returns ``True`` if the user has any permissions in the given package
  173. (the Django app label). If the user is inactive, this method will
  174. always return ``False``.
  175. .. method:: models.User.email_user(subject, message, from_email=None)
  176. Sends an email to the user. If
  177. :attr:`~django.contrib.auth.models.User.from_email` is ``None``, Django
  178. uses the :setting:`DEFAULT_FROM_EMAIL`.
  179. .. method:: models.User.get_profile()
  180. .. deprecated:: 1.5
  181. With the introduction of :ref:`custom User models <auth-custom-user>`,
  182. the use of :setting:`AUTH_PROFILE_MODULE` to define a single profile
  183. model is no longer supported. See the
  184. :doc:`Django 1.5 release notes</releases/1.5>` for more information.
  185. Returns a site-specific profile for this user. Raises
  186. :exc:`django.contrib.auth.models.SiteProfileNotAvailable` if the
  187. current site doesn't allow profiles, or
  188. :exc:`django.core.exceptions.ObjectDoesNotExist` if the user does not
  189. have a profile. For information on how to define a site-specific user
  190. profile, see the section on `storing additional user information`_ below.
  191. .. _storing additional user information: #storing-additional-information-about-users
  192. Manager functions
  193. ~~~~~~~~~~~~~~~~~
  194. .. class:: models.UserManager
  195. The :class:`~django.contrib.auth.models.User` model has a custom manager
  196. that has the following helper functions:
  197. .. method:: models.UserManager.create_user(username, email=None, password=None)
  198. .. versionchanged:: 1.4
  199. The ``email`` parameter was made optional. The username
  200. parameter is now checked for emptiness and raises a
  201. :exc:`~exceptions.ValueError` in case of a negative result.
  202. Creates, saves and returns a :class:`~django.contrib.auth.models.User`.
  203. The :attr:`~django.contrib.auth.models.User.username` and
  204. :attr:`~django.contrib.auth.models.User.password` are set as given. The
  205. domain portion of :attr:`~django.contrib.auth.models.User.email` is
  206. automatically converted to lowercase, and the returned
  207. :class:`~django.contrib.auth.models.User` object will have
  208. :attr:`~models.User.is_active` set to ``True``.
  209. If no password is provided,
  210. :meth:`~django.contrib.auth.models.User.set_unusable_password()` will
  211. be called.
  212. See `Creating users`_ for example usage.
  213. .. method:: models.UserManager.make_random_password(length=10, allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789')
  214. Returns a random password with the given length and given string of
  215. allowed characters. (Note that the default value of ``allowed_chars``
  216. doesn't contain letters that can cause user confusion, including:
  217. * ``i``, ``l``, ``I``, and ``1`` (lowercase letter i, lowercase
  218. letter L, uppercase letter i, and the number one)
  219. * ``o``, ``O``, and ``0`` (uppercase letter o, lowercase letter o,
  220. and zero)
  221. Basic usage
  222. -----------
  223. .. _topics-auth-creating-users:
  224. Creating users
  225. ~~~~~~~~~~~~~~
  226. The most basic way to create users is to use the
  227. :meth:`~django.contrib.auth.models.UserManager.create_user` helper function
  228. that comes with Django::
  229. >>> from django.contrib.auth.models import User
  230. >>> user = User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword')
  231. # At this point, user is a User object that has already been saved
  232. # to the database. You can continue to change its attributes
  233. # if you want to change other fields.
  234. >>> user.is_staff = True
  235. >>> user.save()
  236. You can also create users using the Django admin site. Assuming you've enabled
  237. the admin site and hooked it to the URL ``/admin/``, the "Add user" page is at
  238. ``/admin/auth/user/add/``. You should also see a link to "Users" in the "Auth"
  239. section of the main admin index page. The "Add user" admin page is different
  240. than standard admin pages in that it requires you to choose a username and
  241. password before allowing you to edit the rest of the user's fields.
  242. Also note: if you want your own user account to be able to create users using
  243. the Django admin site, you'll need to give yourself permission to add users
  244. *and* change users (i.e., the "Add user" and "Change user" permissions). If
  245. your account has permission to add users but not to change them, you won't be
  246. able to add users. Why? Because if you have permission to add users, you have
  247. the power to create superusers, which can then, in turn, change other users. So
  248. Django requires add *and* change permissions as a slight security measure.
  249. Changing passwords
  250. ~~~~~~~~~~~~~~~~~~
  251. :djadmin:`manage.py changepassword *username* <changepassword>` offers a method
  252. of changing a User's password from the command line. It prompts you to
  253. change the password of a given user which you must enter twice. If
  254. they both match, the new password will be changed immediately. If you
  255. do not supply a user, the command will attempt to change the password
  256. whose username matches the current user.
  257. You can also change a password programmatically, using
  258. :meth:`~django.contrib.auth.models.User.set_password()`:
  259. .. code-block:: python
  260. >>> from django.contrib.auth.models import User
  261. >>> u = User.objects.get(username__exact='john')
  262. >>> u.set_password('new password')
  263. >>> u.save()
  264. Don't set the :attr:`~django.contrib.auth.models.User.password` attribute
  265. directly unless you know what you're doing. This is explained in the next
  266. section.
  267. .. _auth_password_storage:
  268. How Django stores passwords
  269. ---------------------------
  270. .. versionadded:: 1.4
  271. Django 1.4 introduces a new flexible password storage system and uses
  272. PBKDF2 by default. Previous versions of Django used SHA1, and other
  273. algorithms couldn't be chosen.
  274. The :attr:`~django.contrib.auth.models.User.password` attribute of a
  275. :class:`~django.contrib.auth.models.User` object is a string in this format::
  276. algorithm$hash
  277. That's a storage algorithm, and hash, separated by the dollar-sign
  278. character. The algorithm is one of a number of one way hashing or password
  279. storage algorithms Django can use; see below. The hash is the result of the one-
  280. way function.
  281. By default, Django uses the PBKDF2_ algorithm with a SHA256 hash, a
  282. password stretching mechanism recommended by NIST_. This should be
  283. sufficient for most users: it's quite secure, requiring massive
  284. amounts of computing time to break.
  285. However, depending on your requirements, you may choose a different
  286. algorithm, or even use a custom algorithm to match your specific
  287. security situation. Again, most users shouldn't need to do this -- if
  288. you're not sure, you probably don't. If you do, please read on:
  289. Django chooses the an algorithm by consulting the :setting:`PASSWORD_HASHERS`
  290. setting. This is a list of hashing algorithm classes that this Django
  291. installation supports. The first entry in this list (that is,
  292. ``settings.PASSWORD_HASHERS[0]``) will be used to store passwords, and all the
  293. other entries are valid hashers that can be used to check existing passwords.
  294. This means that if you want to use a different algorithm, you'll need to modify
  295. :setting:`PASSWORD_HASHERS` to list your preferred algorithm first in the list.
  296. The default for :setting:`PASSWORD_HASHERS` is::
  297. PASSWORD_HASHERS = (
  298. 'django.contrib.auth.hashers.PBKDF2PasswordHasher',
  299. 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
  300. 'django.contrib.auth.hashers.BCryptPasswordHasher',
  301. 'django.contrib.auth.hashers.SHA1PasswordHasher',
  302. 'django.contrib.auth.hashers.MD5PasswordHasher',
  303. 'django.contrib.auth.hashers.CryptPasswordHasher',
  304. )
  305. This means that Django will use PBKDF2_ to store all passwords, but will support
  306. checking passwords stored with PBKDF2SHA1, bcrypt_, SHA1_, etc. The next few
  307. sections describe a couple of common ways advanced users may want to modify this
  308. setting.
  309. .. _bcrypt_usage:
  310. Using bcrypt with Django
  311. ~~~~~~~~~~~~~~~~~~~~~~~~
  312. Bcrypt_ is a popular password storage algorithm that's specifically designed
  313. for long-term password storage. It's not the default used by Django since it
  314. requires the use of third-party libraries, but since many people may want to
  315. use it Django supports bcrypt with minimal effort.
  316. To use Bcrypt as your default storage algorithm, do the following:
  317. 1. Install the `py-bcrypt`_ library (probably by running ``sudo pip install
  318. py-bcrypt``, or downloading the library and installing it with ``python
  319. setup.py install``).
  320. 2. Modify :setting:`PASSWORD_HASHERS` to list ``BCryptPasswordHasher``
  321. first. That is, in your settings file, you'd put::
  322. PASSWORD_HASHERS = (
  323. 'django.contrib.auth.hashers.BCryptPasswordHasher',
  324. 'django.contrib.auth.hashers.PBKDF2PasswordHasher',
  325. 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
  326. 'django.contrib.auth.hashers.SHA1PasswordHasher',
  327. 'django.contrib.auth.hashers.MD5PasswordHasher',
  328. 'django.contrib.auth.hashers.CryptPasswordHasher',
  329. )
  330. (You need to keep the other entries in this list, or else Django won't
  331. be able to upgrade passwords; see below).
  332. That's it -- now your Django install will use Bcrypt as the default storage
  333. algorithm.
  334. .. admonition:: Other bcrypt implementations
  335. There are several other implementations that allow bcrypt to be
  336. used with Django. Django's bcrypt support is NOT directly
  337. compatible with these. To upgrade, you will need to modify the
  338. hashes in your database to be in the form `bcrypt$(raw bcrypt
  339. output)`. For example:
  340. `bcrypt$$2a$12$NT0I31Sa7ihGEWpka9ASYrEFkhuTNeBQ2xfZskIiiJeyFXhRgS.Sy`.
  341. Increasing the work factor
  342. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  343. The PBKDF2 and bcrypt algorithms use a number of iterations or rounds of
  344. hashing. This deliberately slows down attackers, making attacks against hashed
  345. passwords harder. However, as computing power increases, the number of
  346. iterations needs to be increased. We've chosen a reasonable default (and will
  347. increase it with each release of Django), but you may wish to tune it up or
  348. down, depending on your security needs and available processing power. To do so,
  349. you'll subclass the appropriate algorithm and override the ``iterations``
  350. parameters. For example, to increase the number of iterations used by the
  351. default PBKDF2 algorithm:
  352. 1. Create a subclass of ``django.contrib.auth.hashers.PBKDF2PasswordHasher``::
  353. from django.contrib.auth.hashers import PBKDF2PasswordHasher
  354. class MyPBKDF2PasswordHasher(PBKDF2PasswordHasher):
  355. """
  356. A subclass of PBKDF2PasswordHasher that uses 100 times more iterations.
  357. """
  358. iterations = PBKDF2PasswordHasher.iterations * 100
  359. Save this somewhere in your project. For example, you might put this in
  360. a file like ``myproject/hashers.py``.
  361. 2. Add your new hasher as the first entry in :setting:`PASSWORD_HASHERS`::
  362. PASSWORD_HASHERS = (
  363. 'myproject.hashers.MyPBKDF2PasswordHasher',
  364. 'django.contrib.auth.hashers.PBKDF2PasswordHasher',
  365. 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
  366. 'django.contrib.auth.hashers.BCryptPasswordHasher',
  367. 'django.contrib.auth.hashers.SHA1PasswordHasher',
  368. 'django.contrib.auth.hashers.MD5PasswordHasher',
  369. 'django.contrib.auth.hashers.CryptPasswordHasher',
  370. )
  371. That's it -- now your Django install will use more iterations when it
  372. stores passwords using PBKDF2.
  373. Password upgrading
  374. ~~~~~~~~~~~~~~~~~~
  375. When users log in, if their passwords are stored with anything other than
  376. the preferred algorithm, Django will automatically upgrade the algorithm
  377. to the preferred one. This means that old installs of Django will get
  378. automatically more secure as users log in, and it also means that you
  379. can switch to new (and better) storage algorithms as they get invented.
  380. However, Django can only upgrade passwords that use algorithms mentioned in
  381. :setting:`PASSWORD_HASHERS`, so as you upgrade to new systems you should make
  382. sure never to *remove* entries from this list. If you do, users using un-
  383. mentioned algorithms won't be able to upgrade.
  384. .. _sha1: http://en.wikipedia.org/wiki/SHA1
  385. .. _pbkdf2: http://en.wikipedia.org/wiki/PBKDF2
  386. .. _nist: http://csrc.nist.gov/publications/nistpubs/800-132/nist-sp800-132.pdf
  387. .. _bcrypt: http://en.wikipedia.org/wiki/Bcrypt
  388. .. _py-bcrypt: http://pypi.python.org/pypi/py-bcrypt/
  389. Anonymous users
  390. ---------------
  391. .. class:: models.AnonymousUser
  392. :class:`django.contrib.auth.models.AnonymousUser` is a class that
  393. implements the :class:`django.contrib.auth.models.User` interface, with
  394. these differences:
  395. * :attr:`~django.contrib.auth.models.User.id` is always ``None``.
  396. * :attr:`~django.contrib.auth.models.User.is_staff` and
  397. :attr:`~django.contrib.auth.models.User.is_superuser` are always
  398. ``False``.
  399. * :attr:`~django.contrib.auth.models.User.is_active` is always ``False``.
  400. * :attr:`~django.contrib.auth.models.User.groups` and
  401. :attr:`~django.contrib.auth.models.User.user_permissions` are always
  402. empty.
  403. * :meth:`~django.contrib.auth.models.User.is_anonymous()` returns ``True``
  404. instead of ``False``.
  405. * :meth:`~django.contrib.auth.models.User.is_authenticated()` returns
  406. ``False`` instead of ``True``.
  407. * :meth:`~django.contrib.auth.models.User.set_password()`,
  408. :meth:`~django.contrib.auth.models.User.check_password()`,
  409. :meth:`~django.contrib.auth.models.User.save()`,
  410. :meth:`~django.contrib.auth.models.User.delete()`,
  411. :meth:`~django.contrib.auth.models.User.set_groups()` and
  412. :meth:`~django.contrib.auth.models.User.set_permissions()` raise
  413. :exc:`~exceptions.NotImplementedError`.
  414. In practice, you probably won't need to use
  415. :class:`~django.contrib.auth.models.AnonymousUser` objects on your own, but
  416. they're used by Web requests, as explained in the next section.
  417. .. _topics-auth-creating-superusers:
  418. Creating superusers
  419. -------------------
  420. :djadmin:`manage.py syncdb <syncdb>` prompts you to create a superuser the
  421. first time you run it after adding ``'django.contrib.auth'`` to your
  422. :setting:`INSTALLED_APPS`. If you need to create a superuser at a later date,
  423. you can use a command line utility::
  424. manage.py createsuperuser --username=joe --email=joe@example.com
  425. You will be prompted for a password. After you enter one, the user will be
  426. created immediately. If you leave off the :djadminopt:`--username` or the
  427. :djadminopt:`--email` options, it will prompt you for those values.
  428. If you're using an older release of Django, the old way of creating a superuser
  429. on the command line still works::
  430. python /path/to/django/contrib/auth/create_superuser.py
  431. ...where :file:`/path/to` is the path to the Django codebase on your
  432. filesystem. The ``manage.py`` command is preferred because it figures out the
  433. correct path and environment for you.
  434. .. _auth-profiles:
  435. Storing additional information about users
  436. ------------------------------------------
  437. .. deprecated:: 1.5
  438. With the introduction of :ref:`custom User models <auth-custom-user>`,
  439. the use of :setting:`AUTH_PROFILE_MODULE` to define a single profile
  440. model is no longer supported. See the
  441. :doc:`Django 1.5 release notes</releases/1.5>` for more information.
  442. If you'd like to store additional information related to your users, Django
  443. provides a method to specify a site-specific related model -- termed a "user
  444. profile" -- for this purpose.
  445. To make use of this feature, define a model with fields for the
  446. additional information you'd like to store, or additional methods
  447. you'd like to have available, and also add a
  448. :class:`~django.db.models.Field.OneToOneField` named ``user`` from your model
  449. to the :class:`~django.contrib.auth.models.User` model. This will ensure only
  450. one instance of your model can be created for each
  451. :class:`~django.contrib.auth.models.User`. For example::
  452. from django.contrib.auth.models import User
  453. class UserProfile(models.Model):
  454. # This field is required.
  455. user = models.OneToOneField(User)
  456. # Other fields here
  457. accepted_eula = models.BooleanField()
  458. favorite_animal = models.CharField(max_length=20, default="Dragons.")
  459. To indicate that this model is the user profile model for a given site, fill in
  460. the setting :setting:`AUTH_PROFILE_MODULE` with a string consisting of the
  461. following items, separated by a dot:
  462. 1. The name of the application (case sensitive) in which the user
  463. profile model is defined (in other words, the
  464. name which was passed to :djadmin:`manage.py startapp <startapp>` to create
  465. the application).
  466. 2. The name of the model (not case sensitive) class.
  467. For example, if the profile model was a class named ``UserProfile`` and was
  468. defined inside an application named ``accounts``, the appropriate setting would
  469. be::
  470. AUTH_PROFILE_MODULE = 'accounts.UserProfile'
  471. When a user profile model has been defined and specified in this manner, each
  472. :class:`~django.contrib.auth.models.User` object will have a method --
  473. :class:`~django.contrib.auth.models.User.get_profile()` -- which returns the
  474. instance of the user profile model associated with that
  475. :class:`~django.contrib.auth.models.User`.
  476. The method :class:`~django.contrib.auth.models.User.get_profile()`
  477. does not create a profile if one does not exist. You need to register a handler
  478. for the User model's :attr:`django.db.models.signals.post_save` signal and, in
  479. the handler, if ``created`` is ``True``, create the associated user profile::
  480. # in models.py
  481. from django.contrib.auth.models import User
  482. from django.db.models.signals import post_save
  483. # definition of UserProfile from above
  484. # ...
  485. def create_user_profile(sender, instance, created, **kwargs):
  486. if created:
  487. UserProfile.objects.create(user=instance)
  488. post_save.connect(create_user_profile, sender=User)
  489. .. seealso:: :doc:`/topics/signals` for more information on Django's signal
  490. dispatcher.
  491. Adding UserProfile fields to the admin
  492. --------------------------------------
  493. To add the UserProfile fields to the user page in the admin, define an
  494. :class:`~django.contrib.admin.InlineModelAdmin` (for this example, we'll use a
  495. :class:`~django.contrib.admin.StackedInline`) in your app's ``admin.py`` and
  496. add it to a ``UserAdmin`` class which is registered with the
  497. :class:`~django.contrib.auth.models.User` class::
  498. from django.contrib import admin
  499. from django.contrib.auth.admin import UserAdmin
  500. from django.contrib.auth.models import User
  501. from my_user_profile_app.models import UserProfile
  502. # Define an inline admin descriptor for UserProfile model
  503. # which acts a bit like a singleton
  504. class UserProfileInline(admin.StackedInline):
  505. model = UserProfile
  506. can_delete = False
  507. verbose_name_plural = 'profile'
  508. # Define a new User admin
  509. class UserAdmin(UserAdmin):
  510. inlines = (UserProfileInline, )
  511. # Re-register UserAdmin
  512. admin.site.unregister(User)
  513. admin.site.register(User, UserAdmin)
  514. Authentication in Web requests
  515. ==============================
  516. Until now, this document has dealt with the low-level APIs for manipulating
  517. authentication-related objects. On a higher level, Django can hook this
  518. authentication framework into its system of
  519. :class:`request objects <django.http.HttpRequest>`.
  520. First, install the
  521. :class:`~django.contrib.sessions.middleware.SessionMiddleware` and
  522. :class:`~django.contrib.auth.middleware.AuthenticationMiddleware`
  523. middlewares by adding them to your :setting:`MIDDLEWARE_CLASSES` setting. See
  524. the :doc:`session documentation </topics/http/sessions>` for more information.
  525. Once you have those middlewares installed, you'll be able to access
  526. :attr:`request.user <django.http.HttpRequest.user>` in views.
  527. :attr:`request.user <django.http.HttpRequest.user>` will give you a
  528. :class:`~django.contrib.auth.models.User` object representing the currently
  529. logged-in user. If a user isn't currently logged in,
  530. :attr:`request.user <django.http.HttpRequest.user>` will be set to an instance
  531. of :class:`~django.contrib.auth.models.AnonymousUser` (see the previous
  532. section). You can tell them apart with
  533. :meth:`~django.contrib.auth.models.User.is_authenticated()`, like so::
  534. if request.user.is_authenticated():
  535. # Do something for authenticated users.
  536. else:
  537. # Do something for anonymous users.
  538. .. _how-to-log-a-user-in:
  539. How to log a user in
  540. --------------------
  541. Django provides two functions in :mod:`django.contrib.auth`:
  542. :func:`~django.contrib.auth.authenticate()` and
  543. :func:`~django.contrib.auth.login()`.
  544. .. function:: authenticate()
  545. To authenticate a given username and password, use
  546. :func:`~django.contrib.auth.authenticate()`. It takes two keyword
  547. arguments, ``username`` and ``password``, and it returns a
  548. :class:`~django.contrib.auth.models.User` object if the password is valid
  549. for the given username. If the password is invalid,
  550. :func:`~django.contrib.auth.authenticate()` returns ``None``. Example::
  551. from django.contrib.auth import authenticate
  552. user = authenticate(username='john', password='secret')
  553. if user is not None:
  554. if user.is_active:
  555. print("You provided a correct username and password!")
  556. else:
  557. print("Your account has been disabled!")
  558. else:
  559. print("Your username and password were incorrect.")
  560. .. function:: login()
  561. To log a user in, in a view, use :func:`~django.contrib.auth.login()`. It
  562. takes an :class:`~django.http.HttpRequest` object and a
  563. :class:`~django.contrib.auth.models.User` object.
  564. :func:`~django.contrib.auth.login()` saves the user's ID in the session,
  565. using Django's session framework, so, as mentioned above, you'll need to
  566. make sure to have the session middleware installed.
  567. Note that data set during the anonymous session is retained when the user
  568. logs in.
  569. This example shows how you might use both
  570. :func:`~django.contrib.auth.authenticate()` and
  571. :func:`~django.contrib.auth.login()`::
  572. from django.contrib.auth import authenticate, login
  573. def my_view(request):
  574. username = request.POST['username']
  575. password = request.POST['password']
  576. user = authenticate(username=username, password=password)
  577. if user is not None:
  578. if user.is_active:
  579. login(request, user)
  580. # Redirect to a success page.
  581. else:
  582. # Return a 'disabled account' error message
  583. else:
  584. # Return an 'invalid login' error message.
  585. .. admonition:: Calling ``authenticate()`` first
  586. When you're manually logging a user in, you *must* call
  587. :func:`~django.contrib.auth.authenticate()` before you call
  588. :func:`~django.contrib.auth.login()`.
  589. :func:`~django.contrib.auth.authenticate()`
  590. sets an attribute on the :class:`~django.contrib.auth.models.User` noting
  591. which authentication backend successfully authenticated that user (see the
  592. `backends documentation`_ for details), and this information is needed
  593. later during the login process.
  594. .. _backends documentation: #other-authentication-sources
  595. Manually managing a user's password
  596. -----------------------------------
  597. .. currentmodule:: django.contrib.auth.hashers
  598. .. versionadded:: 1.4
  599. The :mod:`django.contrib.auth.hashers` module provides a set of functions
  600. to create and validate hashed password. You can use them independently
  601. from the ``User`` model.
  602. .. function:: check_password(password, encoded)
  603. .. versionadded:: 1.4
  604. If you'd like to manually authenticate a user by comparing a plain-text
  605. password to the hashed password in the database, use the convenience
  606. function :func:`django.contrib.auth.hashers.check_password`. It takes two
  607. arguments: the plain-text password to check, and the full value of a
  608. user's ``password`` field in the database to check against, and returns
  609. ``True`` if they match, ``False`` otherwise.
  610. .. function:: make_password(password[, salt, hashers])
  611. .. versionadded:: 1.4
  612. Creates a hashed password in the format used by this application. It takes
  613. one mandatory argument: the password in plain-text. Optionally, you can
  614. provide a salt and a hashing algorithm to use, if you don't want to use the
  615. defaults (first entry of ``PASSWORD_HASHERS`` setting).
  616. Currently supported algorithms are: ``'pbkdf2_sha256'``, ``'pbkdf2_sha1'``,
  617. ``'bcrypt'`` (see :ref:`bcrypt_usage`), ``'sha1'``, ``'md5'``,
  618. ``'unsalted_md5'`` (only for backward compatibility) and ``'crypt'``
  619. if you have the ``crypt`` library installed. If the password argument is
  620. ``None``, an unusable password is returned (a one that will be never
  621. accepted by :func:`django.contrib.auth.hashers.check_password`).
  622. .. function:: is_password_usable(encoded_password)
  623. .. versionadded:: 1.4
  624. Checks if the given string is a hashed password that has a chance
  625. of being verified against :func:`django.contrib.auth.hashers.check_password`.
  626. How to log a user out
  627. ---------------------
  628. .. currentmodule:: django.contrib.auth
  629. .. function:: logout()
  630. To log out a user who has been logged in via
  631. :func:`django.contrib.auth.login()`, use
  632. :func:`django.contrib.auth.logout()` within your view. It takes an
  633. :class:`~django.http.HttpRequest` object and has no return value.
  634. Example::
  635. from django.contrib.auth import logout
  636. def logout_view(request):
  637. logout(request)
  638. # Redirect to a success page.
  639. Note that :func:`~django.contrib.auth.logout()` doesn't throw any errors if
  640. the user wasn't logged in.
  641. When you call :func:`~django.contrib.auth.logout()`, the session data for
  642. the current request is completely cleaned out. All existing data is
  643. removed. This is to prevent another person from using the same Web browser
  644. to log in and have access to the previous user's session data. If you want
  645. to put anything into the session that will be available to the user
  646. immediately after logging out, do that *after* calling
  647. :func:`django.contrib.auth.logout()`.
  648. .. _topics-auth-signals:
  649. Login and logout signals
  650. ------------------------
  651. The auth framework uses two :doc:`signals </topics/signals>` that can be used
  652. for notification when a user logs in or out.
  653. .. data:: django.contrib.auth.signals.user_logged_in
  654. :module:
  655. Sent when a user logs in successfully.
  656. Arguments sent with this signal:
  657. ``sender``
  658. The class of the user that just logged in.
  659. ``request``
  660. The current :class:`~django.http.HttpRequest` instance.
  661. ``user``
  662. The user instance that just logged in.
  663. .. data:: django.contrib.auth.signals.user_logged_out
  664. :module:
  665. Sent when the logout method is called.
  666. ``sender``
  667. As above: the class of the user that just logged out or ``None``
  668. if the user was not authenticated.
  669. ``request``
  670. The current :class:`~django.http.HttpRequest` instance.
  671. ``user``
  672. The user instance that just logged out or ``None`` if the
  673. user was not authenticated.
  674. .. data:: django.contrib.auth.signals.user_login_failed
  675. :module:
  676. .. versionadded:: 1.5
  677. Sent when the user failed to login successfully
  678. ``sender``
  679. The name of the module used for authentication.
  680. ``credentials``
  681. A dictonary of keyword arguments containing the user credentials that were
  682. passed to :func:`~django.contrib.auth.authenticate()` or your own custom
  683. authentication backend. Credentials matching a set of 'sensitive' patterns,
  684. (including password) will not be sent in the clear as part of the signal.
  685. Limiting access to logged-in users
  686. ----------------------------------
  687. The raw way
  688. ~~~~~~~~~~~
  689. The simple, raw way to limit access to pages is to check
  690. :meth:`request.user.is_authenticated()
  691. <django.contrib.auth.models.User.is_authenticated()>` and either redirect to a
  692. login page::
  693. from django.http import HttpResponseRedirect
  694. def my_view(request):
  695. if not request.user.is_authenticated():
  696. return HttpResponseRedirect('/login/?next=%s' % request.path)
  697. # ...
  698. ...or display an error message::
  699. def my_view(request):
  700. if not request.user.is_authenticated():
  701. return render_to_response('myapp/login_error.html')
  702. # ...
  703. The login_required decorator
  704. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  705. .. function:: decorators.login_required([redirect_field_name=REDIRECT_FIELD_NAME, login_url=None])
  706. As a shortcut, you can use the convenient
  707. :func:`~django.contrib.auth.decorators.login_required` decorator::
  708. from django.contrib.auth.decorators import login_required
  709. @login_required
  710. def my_view(request):
  711. ...
  712. :func:`~django.contrib.auth.decorators.login_required` does the following:
  713. * If the user isn't logged in, redirect to
  714. :setting:`settings.LOGIN_URL <LOGIN_URL>`, passing the current absolute
  715. path in the query string. Example: ``/accounts/login/?next=/polls/3/``.
  716. * If the user is logged in, execute the view normally. The view code is
  717. free to assume the user is logged in.
  718. By default, the path that the user should be redirected to upon
  719. successful authentication is stored in a query string parameter called
  720. ``"next"``. If you would prefer to use a different name for this parameter,
  721. :func:`~django.contrib.auth.decorators.login_required` takes an
  722. optional ``redirect_field_name`` parameter::
  723. from django.contrib.auth.decorators import login_required
  724. @login_required(redirect_field_name='my_redirect_field')
  725. def my_view(request):
  726. ...
  727. Note that if you provide a value to ``redirect_field_name``, you will most
  728. likely need to customize your login template as well, since the template
  729. context variable which stores the redirect path will use the value of
  730. ``redirect_field_name`` as its key rather than ``"next"`` (the default).
  731. :func:`~django.contrib.auth.decorators.login_required` also takes an
  732. optional ``login_url`` parameter. Example::
  733. from django.contrib.auth.decorators import login_required
  734. @login_required(login_url='/accounts/login/')
  735. def my_view(request):
  736. ...
  737. Note that if you don't specify the ``login_url`` parameter, you'll need to map
  738. the appropriate Django view to :setting:`settings.LOGIN_URL <LOGIN_URL>`. For
  739. example, using the defaults, add the following line to your URLconf::
  740. (r'^accounts/login/$', 'django.contrib.auth.views.login'),
  741. .. versionchanged:: 1.5
  742. As of version 1.5 :setting:`settings.LOGIN_URL <LOGIN_URL>` now also accepts
  743. view function names and :ref:`named URL patterns <naming-url-patterns>`.
  744. This allows you to freely remap your login view within your URLconf
  745. without having to update the setting.
  746. .. function:: views.login(request, [template_name, redirect_field_name, authentication_form])
  747. **URL name:** ``login``
  748. See :doc:`the URL documentation </topics/http/urls>` for details on using
  749. named URL patterns.
  750. Here's what ``django.contrib.auth.views.login`` does:
  751. * If called via ``GET``, it displays a login form that POSTs to the
  752. same URL. More on this in a bit.
  753. * If called via ``POST``, it tries to log the user in. If login is
  754. successful, the view redirects to the URL specified in ``next``. If
  755. ``next`` isn't provided, it redirects to
  756. :setting:`settings.LOGIN_REDIRECT_URL <LOGIN_REDIRECT_URL>` (which
  757. defaults to ``/accounts/profile/``). If login isn't successful, it
  758. redisplays the login form.
  759. It's your responsibility to provide the login form in a template called
  760. ``registration/login.html`` by default. This template gets passed four
  761. template context variables:
  762. * ``form``: A :class:`~django.forms.Form` object representing the login
  763. form. See the :doc:`forms documentation </topics/forms/index>` for
  764. more on ``Form`` objects.
  765. * ``next``: The URL to redirect to after successful login. This may
  766. contain a query string, too.
  767. * ``site``: The current :class:`~django.contrib.sites.models.Site`,
  768. according to the :setting:`SITE_ID` setting. If you don't have the
  769. site framework installed, this will be set to an instance of
  770. :class:`~django.contrib.sites.models.RequestSite`, which derives the
  771. site name and domain from the current
  772. :class:`~django.http.HttpRequest`.
  773. * ``site_name``: An alias for ``site.name``. If you don't have the site
  774. framework installed, this will be set to the value of
  775. :attr:`request.META['SERVER_NAME'] <django.http.HttpRequest.META>`.
  776. For more on sites, see :doc:`/ref/contrib/sites`.
  777. If you'd prefer not to call the template :file:`registration/login.html`,
  778. you can pass the ``template_name`` parameter via the extra arguments to
  779. the view in your URLconf. For example, this URLconf line would use
  780. :file:`myapp/login.html` instead::
  781. (r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'myapp/login.html'}),
  782. You can also specify the name of the ``GET`` field which contains the URL
  783. to redirect to after login by passing ``redirect_field_name`` to the view.
  784. By default, the field is called ``next``.
  785. Here's a sample :file:`registration/login.html` template you can use as a
  786. starting point. It assumes you have a :file:`base.html` template that
  787. defines a ``content`` block:
  788. .. code-block:: html+django
  789. {% extends "base.html" %}
  790. {% block content %}
  791. {% if form.errors %}
  792. <p>Your username and password didn't match. Please try again.</p>
  793. {% endif %}
  794. <form method="post" action="{% url 'django.contrib.auth.views.login' %}">
  795. {% csrf_token %}
  796. <table>
  797. <tr>
  798. <td>{{ form.username.label_tag }}</td>
  799. <td>{{ form.username }}</td>
  800. </tr>
  801. <tr>
  802. <td>{{ form.password.label_tag }}</td>
  803. <td>{{ form.password }}</td>
  804. </tr>
  805. </table>
  806. <input type="submit" value="login" />
  807. <input type="hidden" name="next" value="{{ next }}" />
  808. </form>
  809. {% endblock %}
  810. If you are using alternate authentication (see
  811. :ref:`authentication-backends`) you can pass a custom authentication form
  812. to the login view via the ``authentication_form`` parameter. This form must
  813. accept a ``request`` keyword argument in its ``__init__`` method, and
  814. provide a ``get_user`` method which returns the authenticated user object
  815. (this method is only ever called after successful form validation).
  816. .. _forms documentation: ../forms/
  817. .. _site framework docs: ../sites/
  818. .. versionadded:: 1.4
  819. The :func:`~views.login` view and the :ref:`other-built-in-views` now all
  820. return a :class:`~django.template.response.TemplateResponse` instance,
  821. which allows you to easily customize the response data before rendering.
  822. For more details, see the
  823. :doc:`TemplateResponse documentation </ref/template-response>`.
  824. .. _other-built-in-views:
  825. Other built-in views
  826. --------------------
  827. .. module:: django.contrib.auth.views
  828. In addition to the :func:`~views.login` view, the authentication system
  829. includes a few other useful built-in views located in
  830. :mod:`django.contrib.auth.views`:
  831. .. function:: logout(request, [next_page, template_name, redirect_field_name])
  832. Logs a user out.
  833. **URL name:** ``logout``
  834. See :doc:`the URL documentation </topics/http/urls>` for details on using
  835. named URL patterns.
  836. **Optional arguments:**
  837. * ``next_page``: The URL to redirect to after logout.
  838. * ``template_name``: The full name of a template to display after
  839. logging the user out. Defaults to
  840. :file:`registration/logged_out.html` if no argument is supplied.
  841. * ``redirect_field_name``: The name of a ``GET`` field containing the
  842. URL to redirect to after log out. Overrides ``next_page`` if the given
  843. ``GET`` parameter is passed.
  844. **Template context:**
  845. * ``title``: The string "Logged out", localized.
  846. * ``site``: The current :class:`~django.contrib.sites.models.Site`,
  847. according to the :setting:`SITE_ID` setting. If you don't have the
  848. site framework installed, this will be set to an instance of
  849. :class:`~django.contrib.sites.models.RequestSite`, which derives the
  850. site name and domain from the current
  851. :class:`~django.http.HttpRequest`.
  852. * ``site_name``: An alias for ``site.name``. If you don't have the site
  853. framework installed, this will be set to the value of
  854. :attr:`request.META['SERVER_NAME'] <django.http.HttpRequest.META>`.
  855. For more on sites, see :doc:`/ref/contrib/sites`.
  856. .. function:: logout_then_login(request[, login_url])
  857. Logs a user out, then redirects to the login page.
  858. **URL name:** No default URL provided
  859. **Optional arguments:**
  860. * ``login_url``: The URL of the login page to redirect to.
  861. Defaults to :setting:`settings.LOGIN_URL <LOGIN_URL>` if not supplied.
  862. .. function:: password_change(request[, template_name, post_change_redirect, password_change_form])
  863. Allows a user to change their password.
  864. **URL name:** ``password_change``
  865. **Optional arguments:**
  866. * ``template_name``: The full name of a template to use for
  867. displaying the password change form. Defaults to
  868. :file:`registration/password_change_form.html` if not supplied.
  869. * ``post_change_redirect``: The URL to redirect to after a successful
  870. password change.
  871. * ``password_change_form``: A custom "change password" form which must
  872. accept a ``user`` keyword argument. The form is responsible for
  873. actually changing the user's password. Defaults to
  874. :class:`~django.contrib.auth.forms.PasswordChangeForm`.
  875. **Template context:**
  876. * ``form``: The password change form (see ``password_change_form`` above).
  877. .. function:: password_change_done(request[, template_name])
  878. The page shown after a user has changed their password.
  879. **URL name:** ``password_change_done``
  880. **Optional arguments:**
  881. * ``template_name``: The full name of a template to use.
  882. Defaults to :file:`registration/password_change_done.html` if not
  883. supplied.
  884. .. function:: password_reset(request[, is_admin_site, template_name, email_template_name, password_reset_form, token_generator, post_reset_redirect, from_email])
  885. Allows a user to reset their password by generating a one-time use link
  886. that can be used to reset the password, and sending that link to the
  887. user's registered email address.
  888. .. versionchanged:: 1.4
  889. Users flagged with an unusable password (see
  890. :meth:`~django.contrib.auth.models.User.set_unusable_password()`
  891. will not be able to request a password reset to prevent misuse
  892. when using an external authentication source like LDAP.
  893. **URL name:** ``password_reset``
  894. **Optional arguments:**
  895. * ``template_name``: The full name of a template to use for
  896. displaying the password reset form. Defaults to
  897. :file:`registration/password_reset_form.html` if not supplied.
  898. * ``email_template_name``: The full name of a template to use for
  899. generating the email with the reset password link. Defaults to
  900. :file:`registration/password_reset_email.html` if not supplied.
  901. * ``subject_template_name``: The full name of a template to use for
  902. the subject of the email with the reset password link. Defaults
  903. to :file:`registration/password_reset_subject.txt` if not supplied.
  904. .. versionadded:: 1.4
  905. * ``password_reset_form``: Form that will be used to get the email of
  906. the user to reset the password for. Defaults to
  907. :class:`~django.contrib.auth.forms.PasswordResetForm`.
  908. * ``token_generator``: Instance of the class to check the one time link.
  909. This will default to ``default_token_generator``, it's an instance of
  910. ``django.contrib.auth.tokens.PasswordResetTokenGenerator``.
  911. * ``post_reset_redirect``: The URL to redirect to after a successful
  912. password reset request.
  913. * ``from_email``: A valid email address. By default Django uses
  914. the :setting:`DEFAULT_FROM_EMAIL`.
  915. **Template context:**
  916. * ``form``: The form (see ``password_reset_form`` above) for resetting
  917. the user's password.
  918. **Email template context:**
  919. * ``email``: An alias for ``user.email``
  920. * ``user``: The current :class:`~django.contrib.auth.models.User`,
  921. according to the ``email`` form field. Only active users are able to
  922. reset their passwords (``User.is_active is True``).
  923. * ``site_name``: An alias for ``site.name``. If you don't have the site
  924. framework installed, this will be set to the value of
  925. :attr:`request.META['SERVER_NAME'] <django.http.HttpRequest.META>`.
  926. For more on sites, see :doc:`/ref/contrib/sites`.
  927. * ``domain``: An alias for ``site.domain``. If you don't have the site
  928. framework installed, this will be set to the value of
  929. ``request.get_host()``.
  930. * ``protocol``: http or https
  931. * ``uid``: The user's id encoded in base 36.
  932. * ``token``: Token to check that the reset link is valid.
  933. Sample ``registration/password_reset_email.html`` (email body template):
  934. .. code-block:: html+django
  935. Someone asked for password reset for email {{ email }}. Follow the link below:
  936. {{ protocol}}://{{ domain }}{% url 'password_reset_confirm' uidb36=uid token=token %}
  937. The same template context is used for subject template. Subject must be
  938. single line plain text string.
  939. .. function:: password_reset_done(request[, template_name])
  940. The page shown after a user has been emailed a link to reset their
  941. password. This view is called by default if the :func:`password_reset` view
  942. doesn't have an explicit ``post_reset_redirect`` URL set.
  943. **URL name:** ``password_reset_done``
  944. **Optional arguments:**
  945. * ``template_name``: The full name of a template to use.
  946. Defaults to :file:`registration/password_reset_done.html` if not
  947. supplied.
  948. .. function:: password_reset_confirm(request[, uidb36, token, template_name, token_generator, set_password_form, post_reset_redirect])
  949. Presents a form for entering a new password.
  950. **URL name:** ``password_reset_confirm``
  951. **Optional arguments:**
  952. * ``uidb36``: The user's id encoded in base 36. Defaults to ``None``.
  953. * ``token``: Token to check that the password is valid. Defaults to
  954. ``None``.
  955. * ``template_name``: The full name of a template to display the confirm
  956. password view. Default value is :file:`registration/password_reset_confirm.html`.
  957. * ``token_generator``: Instance of the class to check the password. This
  958. will default to ``default_token_generator``, it's an instance of
  959. ``django.contrib.auth.tokens.PasswordResetTokenGenerator``.
  960. * ``set_password_form``: Form that will be used to set the password.
  961. Defaults to :class:`~django.contrib.auth.forms.SetPasswordForm`
  962. * ``post_reset_redirect``: URL to redirect after the password reset
  963. done. Defaults to ``None``.
  964. **Template context:**
  965. * ``form``: The form (see ``set_password_form`` above) for setting the
  966. new user's password.
  967. * ``validlink``: Boolean, True if the link (combination of uidb36 and
  968. token) is valid or unused yet.
  969. .. function:: password_reset_complete(request[,template_name])
  970. Presents a view which informs the user that the password has been
  971. successfully changed.
  972. **URL name:** ``password_reset_complete``
  973. **Optional arguments:**
  974. * ``template_name``: The full name of a template to display the view.
  975. Defaults to :file:`registration/password_reset_complete.html`.
  976. Helper functions
  977. ----------------
  978. .. currentmodule:: django.contrib.auth.views
  979. .. function:: redirect_to_login(next[, login_url, redirect_field_name])
  980. Redirects to the login page, and then back to another URL after a
  981. successful login.
  982. **Required arguments:**
  983. * ``next``: The URL to redirect to after a successful login.
  984. **Optional arguments:**
  985. * ``login_url``: The URL of the login page to redirect to.
  986. Defaults to :setting:`settings.LOGIN_URL <LOGIN_URL>` if not supplied.
  987. * ``redirect_field_name``: The name of a ``GET`` field containing the
  988. URL to redirect to after log out. Overrides ``next`` if the given
  989. ``GET`` parameter is passed.
  990. .. _built-in-auth-forms:
  991. Built-in forms
  992. --------------
  993. .. module:: django.contrib.auth.forms
  994. If you don't want to use the built-in views, but want the convenience of not
  995. having to write forms for this functionality, the authentication system
  996. provides several built-in forms located in :mod:`django.contrib.auth.forms`:
  997. .. class:: AdminPasswordChangeForm
  998. A form used in the admin interface to change a user's password.
  999. .. class:: AuthenticationForm
  1000. A form for logging a user in.
  1001. .. class:: PasswordChangeForm
  1002. A form for allowing a user to change their password.
  1003. .. class:: PasswordResetForm
  1004. A form for generating and emailing a one-time use link to reset a
  1005. user's password.
  1006. .. class:: SetPasswordForm
  1007. A form that lets a user change his/her password without entering the old
  1008. password.
  1009. .. class:: UserChangeForm
  1010. A form used in the admin interface to change a user's information and
  1011. permissions.
  1012. .. class:: UserCreationForm
  1013. A form for creating a new user.
  1014. Limiting access to logged-in users that pass a test
  1015. ---------------------------------------------------
  1016. .. currentmodule:: django.contrib.auth.decorators
  1017. To limit access based on certain permissions or some other test, you'd do
  1018. essentially the same thing as described in the previous section.
  1019. The simple way is to run your test on :attr:`request.user
  1020. <django.http.HttpRequest.user>` in the view directly. For example, this view
  1021. checks to make sure the user is logged in and has the permission
  1022. ``polls.can_vote``::
  1023. def my_view(request):
  1024. if not request.user.has_perm('polls.can_vote'):
  1025. return HttpResponse("You can't vote in this poll.")
  1026. # ...
  1027. .. function:: user_passes_test(func, [login_url=None])
  1028. As a shortcut, you can use the convenient ``user_passes_test`` decorator::
  1029. from django.contrib.auth.decorators import user_passes_test
  1030. @user_passes_test(lambda u: u.has_perm('polls.can_vote'))
  1031. def my_view(request):
  1032. ...
  1033. We're using this particular test as a relatively simple example. However,
  1034. if you just want to test whether a permission is available to a user, you
  1035. can use the :func:`~django.contrib.auth.decorators.permission_required()`
  1036. decorator, described later in this document.
  1037. :func:`~django.contrib.auth.decorators.user_passes_test` takes a required
  1038. argument: a callable that takes a
  1039. :class:`~django.contrib.auth.models.User` object and returns ``True`` if
  1040. the user is allowed to view the page. Note that
  1041. :func:`~django.contrib.auth.decorators.user_passes_test` does not
  1042. automatically check that the :class:`~django.contrib.auth.models.User` is
  1043. not anonymous.
  1044. :func:`~django.contrib.auth.decorators.user_passes_test()` takes an
  1045. optional ``login_url`` argument, which lets you specify the URL for your
  1046. login page (:setting:`settings.LOGIN_URL <LOGIN_URL>` by default).
  1047. For example::
  1048. from django.contrib.auth.decorators import user_passes_test
  1049. @user_passes_test(lambda u: u.has_perm('polls.can_vote'), login_url='/login/')
  1050. def my_view(request):
  1051. ...
  1052. The permission_required decorator
  1053. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1054. .. function:: permission_required([login_url=None, raise_exception=False])
  1055. It's a relatively common task to check whether a user has a particular
  1056. permission. For that reason, Django provides a shortcut for that case: the
  1057. :func:`~django.contrib.auth.decorators.permission_required()` decorator.
  1058. Using this decorator, the earlier example can be written as::
  1059. from django.contrib.auth.decorators import permission_required
  1060. @permission_required('polls.can_vote')
  1061. def my_view(request):
  1062. ...
  1063. As for the :meth:`User.has_perm` method, permission names take the form
  1064. ``"<app label>.<permission codename>"`` (i.e. ``polls.can_vote`` for a
  1065. permission on a model in the ``polls`` application).
  1066. Note that :func:`~django.contrib.auth.decorators.permission_required()`
  1067. also takes an optional ``login_url`` parameter. Example::
  1068. from django.contrib.auth.decorators import permission_required
  1069. @permission_required('polls.can_vote', login_url='/loginpage/')
  1070. def my_view(request):
  1071. ...
  1072. As in the :func:`~decorators.login_required` decorator, ``login_url``
  1073. defaults to :setting:`settings.LOGIN_URL <LOGIN_URL>`.
  1074. .. versionchanged:: 1.4
  1075. Added ``raise_exception`` parameter. If given, the decorator will raise
  1076. :exc:`~django.core.exceptions.PermissionDenied`, prompting
  1077. :ref:`the 403 (HTTP Forbidden) view<http_forbidden_view>` instead of
  1078. redirecting to the login page.
  1079. .. currentmodule:: django.contrib.auth
  1080. Applying permissions to generic views
  1081. -------------------------------------
  1082. To apply a permission to a :doc:`class-based generic view
  1083. </ref/class-based-views/index>`, decorate the :meth:`View.dispatch
  1084. <django.views.generic.base.View.dispatch>` method on the class. See
  1085. :ref:`decorating-class-based-views` for details.
  1086. .. _permissions:
  1087. Permissions
  1088. ===========
  1089. Django comes with a simple permissions system. It provides a way to assign
  1090. permissions to specific users and groups of users.
  1091. It's used by the Django admin site, but you're welcome to use it in your own
  1092. code.
  1093. The Django admin site uses permissions as follows:
  1094. * Access to view the "add" form and add an object is limited to users with
  1095. the "add" permission for that type of object.
  1096. * Access to view the change list, view the "change" form and change an
  1097. object is limited to users with the "change" permission for that type of
  1098. object.
  1099. * Access to delete an object is limited to users with the "delete"
  1100. permission for that type of object.
  1101. Permissions can be set not only per type of object, but also per specific
  1102. object instance. By using the
  1103. :meth:`~django.contrib.admin.ModelAdmin.has_add_permission`,
  1104. :meth:`~django.contrib.admin.ModelAdmin.has_change_permission` and
  1105. :meth:`~django.contrib.admin.ModelAdmin.has_delete_permission` methods provided
  1106. by the :class:`~django.contrib.admin.ModelAdmin` class, it is possible to
  1107. customize permissions for different object instances of the same type.
  1108. Default permissions
  1109. -------------------
  1110. When ``django.contrib.auth`` is listed in your :setting:`INSTALLED_APPS`
  1111. setting, it will ensure that three default permissions -- add, change and
  1112. delete -- are created for each Django model defined in one of your installed
  1113. applications.
  1114. These permissions will be created when you run :djadmin:`manage.py syncdb
  1115. <syncdb>`; the first time you run ``syncdb`` after adding
  1116. ``django.contrib.auth`` to :setting:`INSTALLED_APPS`, the default permissions
  1117. will be created for all previously-installed models, as well as for any new
  1118. models being installed at that time. Afterward, it will create default
  1119. permissions for new models each time you run :djadmin:`manage.py syncdb
  1120. <syncdb>`.
  1121. Assuming you have an application with an
  1122. :attr:`~django.db.models.Options.app_label` ``foo`` and a model named ``Bar``,
  1123. to test for basic permissions you should use:
  1124. * add: ``user.has_perm('foo.add_bar')``
  1125. * change: ``user.has_perm('foo.change_bar')``
  1126. * delete: ``user.has_perm('foo.delete_bar')``
  1127. .. _custom-permissions:
  1128. Custom permissions
  1129. ------------------
  1130. To create custom permissions for a given model object, use the ``permissions``
  1131. :ref:`model Meta attribute <meta-options>`.
  1132. This example Task model creates three custom permissions, i.e., actions users
  1133. can or cannot do with Task instances, specific to your application::
  1134. class Task(models.Model):
  1135. ...
  1136. class Meta:
  1137. permissions = (
  1138. ("view_task", "Can see available tasks"),
  1139. ("change_task_status", "Can change the status of tasks"),
  1140. ("close_task", "Can remove a task by setting its status as closed"),
  1141. )
  1142. The only thing this does is create those extra permissions when you run
  1143. :djadmin:`manage.py syncdb <syncdb>`. Your code is in charge of checking the
  1144. value of these permissions when an user is trying to access the functionality
  1145. provided by the application (viewing tasks, changing the status of tasks,
  1146. closing tasks.) Continuing the above example, the following checks if a user may
  1147. view tasks::
  1148. user.has_perm('app.view_task')
  1149. API reference
  1150. -------------
  1151. .. currentmodule:: django.contrib.auth.models
  1152. .. class:: models.Permission
  1153. Fields
  1154. ~~~~~~
  1155. :class:`~django.contrib.auth.models.Permission` objects have the following
  1156. fields:
  1157. .. attribute:: Permission.name
  1158. Required. 50 characters or fewer. Example: ``'Can vote'``.
  1159. .. attribute:: Permission.content_type
  1160. Required. A reference to the ``django_content_type`` database table, which
  1161. contains a record for each installed Django model.
  1162. .. attribute:: Permission.codename
  1163. Required. 100 characters or fewer. Example: ``'can_vote'``.
  1164. Methods
  1165. ~~~~~~~
  1166. :class:`~django.contrib.auth.models.Permission` objects have the standard
  1167. data-access methods like any other :doc:`Django model </ref/models/instances>`.
  1168. .. currentmodule:: django.contrib.auth
  1169. Programmatically creating permissions
  1170. -------------------------------------
  1171. While custom permissions can be defined within a model's ``Meta`` class, you
  1172. can also create permissions directly. For example, you can create the
  1173. ``can_publish`` permission for a ``BlogPost`` model in ``myapp``::
  1174. from django.contrib.auth.models import Group, Permission
  1175. from django.contrib.contenttypes.models import ContentType
  1176. content_type = ContentType.objects.get(app_label='myapp', model='BlogPost')
  1177. permission = Permission.objects.create(codename='can_publish',
  1178. name='Can Publish Posts',
  1179. content_type=content_type)
  1180. The permission can then be assigned to a
  1181. :class:`~django.contrib.auth.models.User` via its ``user_permissions``
  1182. attribute or to a :class:`~django.contrib.auth.models.Group` via its
  1183. ``permissions`` attribute.
  1184. Authentication data in templates
  1185. ================================
  1186. The currently logged-in user and his/her permissions are made available in the
  1187. :doc:`template context </ref/templates/api>` when you use
  1188. :class:`~django.template.context.RequestContext`.
  1189. .. admonition:: Technicality
  1190. Technically, these variables are only made available in the template context
  1191. if you use :class:`~django.template.context.RequestContext` *and* your
  1192. :setting:`TEMPLATE_CONTEXT_PROCESSORS` setting contains
  1193. ``"django.contrib.auth.context_processors.auth"``, which is default. For
  1194. more, see the :ref:`RequestContext docs <subclassing-context-requestcontext>`.
  1195. Users
  1196. -----
  1197. When rendering a template :class:`~django.template.context.RequestContext`, the
  1198. currently logged-in user, either a :class:`~django.contrib.auth.models.User`
  1199. instance or an :class:`~django.contrib.auth.models.AnonymousUser` instance, is
  1200. stored in the template variable ``{{ user }}``:
  1201. .. code-block:: html+django
  1202. {% if user.is_authenticated %}
  1203. <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
  1204. {% else %}
  1205. <p>Welcome, new user. Please log in.</p>
  1206. {% endif %}
  1207. This template context variable is not available if a ``RequestContext`` is not
  1208. being used.
  1209. Permissions
  1210. -----------
  1211. The currently logged-in user's permissions are stored in the template variable
  1212. ``{{ perms }}``. This is an instance of
  1213. :class:`django.contrib.auth.context_processors.PermWrapper`, which is a
  1214. template-friendly proxy of permissions.
  1215. In the ``{{ perms }}`` object, single-attribute lookup is a proxy to
  1216. :meth:`User.has_module_perms <django.contrib.auth.models.User.has_module_perms>`.
  1217. This example would display ``True`` if the logged-in user had any permissions
  1218. in the ``foo`` app::
  1219. {{ perms.foo }}
  1220. Two-level-attribute lookup is a proxy to
  1221. :meth:`User.has_perm <django.contrib.auth.models.User.has_perm>`. This example
  1222. would display ``True`` if the logged-in user had the permission
  1223. ``foo.can_vote``::
  1224. {{ perms.foo.can_vote }}
  1225. Thus, you can check permissions in template ``{% if %}`` statements:
  1226. .. code-block:: html+django
  1227. {% if perms.foo %}
  1228. <p>You have permission to do something in the foo app.</p>
  1229. {% if perms.foo.can_vote %}
  1230. <p>You can vote!</p>
  1231. {% endif %}
  1232. {% if perms.foo.can_drive %}
  1233. <p>You can drive!</p>
  1234. {% endif %}
  1235. {% else %}
  1236. <p>You don't have permission to do anything in the foo app.</p>
  1237. {% endif %}
  1238. .. versionadded:: 1.5
  1239. Permission lookup by "if in".
  1240. It is possible to also look permissions up by ``{% if in %}`` statements.
  1241. For example:
  1242. .. code-block:: html+django
  1243. {% if 'foo' in perms %}
  1244. {% if 'foo.can_vote' in perms %}
  1245. <p>In lookup works, too.</p>
  1246. {% endif %}
  1247. {% endif %}
  1248. Groups
  1249. ======
  1250. Groups are a generic way of categorizing users so you can apply permissions, or
  1251. some other label, to those users. A user can belong to any number of groups.
  1252. A user in a group automatically has the permissions granted to that group. For
  1253. example, if the group ``Site editors`` has the permission
  1254. ``can_edit_home_page``, any user in that group will have that permission.
  1255. Beyond permissions, groups are a convenient way to categorize users to give
  1256. them some label, or extended functionality. For example, you could create a
  1257. group ``'Special users'``, and you could write code that could, say, give them
  1258. access to a members-only portion of your site, or send them members-only email
  1259. messages.
  1260. API reference
  1261. -------------
  1262. .. class:: models.Group
  1263. Fields
  1264. ~~~~~~
  1265. :class:`~django.contrib.auth.models.Group` objects have the following fields:
  1266. .. attribute:: Group.name
  1267. Required. 80 characters or fewer. Any characters are permitted. Example:
  1268. ``'Awesome Users'``.
  1269. .. attribute:: Group.permissions
  1270. Many-to-many field to :class:`~django.contrib.auth.models.Permissions`::
  1271. group.permissions = [permission_list]
  1272. group.permissions.add(permission, permission, ...)
  1273. group.permissions.remove(permission, permission, ...)
  1274. group.permissions.clear()
  1275. .. _auth-custom-user:
  1276. Customizing the User model
  1277. ==========================
  1278. .. versionadded:: 1.5
  1279. Some kinds of projects may have authentication requirements for which Django's
  1280. built-in :class:`~django.contrib.auth.models.User` model is not always
  1281. appropriate. For instance, on some sites it makes more sense to use an email
  1282. address as your identification token instead of a username.
  1283. Django allows you to override the default User model by providing a value for
  1284. the :setting:`AUTH_USER_MODEL` setting that references a custom model::
  1285. AUTH_USER_MODEL = 'myapp.MyUser'
  1286. This dotted pair describes the name of the Django app, and the name of the Django
  1287. model that you wish to use as your User model.
  1288. .. admonition:: Warning
  1289. Changing :setting:`AUTH_USER_MODEL` has a big effect on your database
  1290. structure. It changes the tables that are available, and it will affect the
  1291. construction of foreign keys and many-to-many relationships. If you intend
  1292. to set :setting:`AUTH_USER_MODEL`, you should set it before running
  1293. ``manage.py syncdb`` for the first time.
  1294. If you have an existing project and you want to migrate to using a custom
  1295. User model, you may need to look into using a migration tool like South_
  1296. to ease the transition.
  1297. .. _South: http://south.aeracode.org
  1298. Referencing the User model
  1299. --------------------------
  1300. If you reference :class:`~django.contrib.auth.models.User` directly (for
  1301. example, by referring to it in a foreign key), your code will not work in
  1302. projects where the :setting:`AUTH_USER_MODEL` setting has been changed to a
  1303. different User model.
  1304. Instead of referring to :class:`~django.contrib.auth.models.User` directly,
  1305. you should reference the user model using
  1306. :func:`django.contrib.auth.get_user_model()`. This method will return the
  1307. currently active User model -- the custom User model if one is specified, or
  1308. :class:`~django.contrib.auth.User` otherwise.
  1309. When you define a foreign key or many-to-many relations to the User model,
  1310. you should specify the custom model using the :setting:`AUTH_USER_MODEL`
  1311. setting. For example::
  1312. from django.conf import settings
  1313. from django.db import models
  1314. class Article(models.Model)
  1315. author = models.ForeignKey(settings.AUTH_USER_MODEL)
  1316. Specifying a custom User model
  1317. ------------------------------
  1318. .. admonition:: Model design considerations
  1319. Think carefully before handling information not directly related to
  1320. authentication in your custom User Model.
  1321. It may be better to store app-specific user information in a model
  1322. that has a relation with the User model. That allows each app to specify
  1323. its own user data requirements without risking conflicts with other
  1324. apps. On the other hand, queries to retrieve this related information
  1325. will involve a database join, which may have an effect on performance.
  1326. Django expects your custom User model to meet some minimum requirements.
  1327. 1. Your model must have a single unique field that can be used for
  1328. identification purposes. This can be a username, an email address,
  1329. or any other unique attribute.
  1330. 2. Your model must provide a way to address the user in a "short" and
  1331. "long" form. The most common interpretation of this would be to use
  1332. the user's given name as the "short" identifier, and the user's full
  1333. name as the "long" identifier. However, there are no constraints on
  1334. what these two methods return - if you want, they can return exactly
  1335. the same value.
  1336. The easiest way to construct a compliant custom User model is to inherit from
  1337. :class:`~django.contrib.auth.models.AbstractBaseUser`.
  1338. :class:`~django.contrib.auth.models.AbstractBaseUser` provides the core
  1339. implementation of a `User` model, including hashed passwords and tokenized
  1340. password resets. You must then provide some key implementation details:
  1341. .. class:: models.CustomUser
  1342. .. attribute:: User.USERNAME_FIELD
  1343. A string describing the name of the field on the User model that is
  1344. used as the unique identifier. This will usually be a username of
  1345. some kind, but it can also be an email address, or any other unique
  1346. identifier. In the following example, the field `identifier` is used
  1347. as the identifying field::
  1348. class MyUser(AbstractBaseUser):
  1349. identifier = models.CharField(max_length=40, unique=True, db_index=True)
  1350. ...
  1351. USERNAME_FIELD = 'identifier'
  1352. .. attribute:: User.REQUIRED_FIELDS
  1353. A list of the field names that *must* be provided when creating
  1354. a user. For example, here is the partial definition for a User model
  1355. that defines two required fields - a date of birth and height::
  1356. class MyUser(AbstractBaseUser):
  1357. ...
  1358. date_of_birth = models.DateField()
  1359. height = models.FloatField()
  1360. ...
  1361. REQUIRED_FIELDS = ['date_of_birth', 'height']
  1362. .. note::
  1363. ``REQUIRED_FIELDS`` must contain all required fields on your User
  1364. model, but should *not* contain the ``USERNAME_FIELD``.
  1365. .. attribute:: User.is_active
  1366. A boolean attribute that indicates whether the user is considered
  1367. "active". This attribute is provided as an attribute on
  1368. ``AbstractBaseUser`` defaulting to ``True``. How you choose to
  1369. implement it will depend on the details of your chosen auth backends.
  1370. See the documentation of the :attr:`attribute on the builtin user model
  1371. <django.contrib.auth.models.User.is_active>` for details.
  1372. .. method:: User.get_full_name():
  1373. A longer formal identifier for the user. A common interpretation
  1374. would be the full name name of the user, but it can be any string that
  1375. identifies the user.
  1376. .. method:: User.get_short_name():
  1377. A short, informal identifier for the user. A common interpretation
  1378. would be the first name of the user, but it can be any string that
  1379. identifies the user in an informal way. It may also return the same
  1380. value as :meth:`django.contrib.auth.User.get_full_name()`.
  1381. The following methods are available on any subclass of
  1382. :class:`~django.contrib.auth.models.AbstractBaseUser`:
  1383. .. class:: models.AbstractBaseUser
  1384. .. method:: models.AbstractBaseUser.get_username()
  1385. Returns the value of the field nominated by ``USERNAME_FIELD``.
  1386. .. method:: models.AbstractBaseUser.is_anonymous()
  1387. Always returns ``False``. This is a way of differentiating
  1388. from :class:`~django.contrib.auth.models.AnonymousUser` objects.
  1389. Generally, you should prefer using
  1390. :meth:`~django.contrib.auth.models.AbstractBaseUser.is_authenticated()` to this
  1391. method.
  1392. .. method:: models.AbstractBaseUser.is_authenticated()
  1393. Always returns ``True``. This is a way to tell if the user has been
  1394. authenticated. This does not imply any permissions, and doesn't check
  1395. if the user is active - it only indicates that the user has provided a
  1396. valid username and password.
  1397. .. method:: models.AbstractBaseUser.set_password(raw_password)
  1398. Sets the user's password to the given raw string, taking care of the
  1399. password hashing. Doesn't save the
  1400. :class:`~django.contrib.auth.models.AbstractBaseUser` object.
  1401. .. method:: models.AbstractBaseUser.check_password(raw_password)
  1402. Returns ``True`` if the given raw string is the correct password for
  1403. the user. (This takes care of the password hashing in making the
  1404. comparison.)
  1405. .. method:: models.AbstractBaseUser.set_unusable_password()
  1406. Marks the user as having no password set. This isn't the same as
  1407. having a blank string for a password.
  1408. :meth:`~django.contrib.auth.models.AbstractBaseUser.check_password()` for this user
  1409. will never return ``True``. Doesn't save the
  1410. :class:`~django.contrib.auth.models.AbstractBaseUser` object.
  1411. You may need this if authentication for your application takes place
  1412. against an existing external source such as an LDAP directory.
  1413. .. method:: models.AbstractBaseUser.has_usable_password()
  1414. Returns ``False`` if
  1415. :meth:`~django.contrib.auth.models.AbstractBaseUser.set_unusable_password()` has
  1416. been called for this user.
  1417. You should also define a custom manager for your User model. If your User
  1418. model defines `username` and `email` fields the same as Django's default User,
  1419. you can just install Django's
  1420. :class:`~django.contrib.auth.models.UserManager`; however, if your User model
  1421. defines different fields, you will need to define a custom manager that
  1422. extends :class:`~django.contrib.auth.models.BaseUserManager` providing two
  1423. additional methods:
  1424. .. class:: models.CustomUserManager
  1425. .. method:: models.CustomUserManager.create_user(*username_field*, password=None, **other_fields)
  1426. The prototype of `create_user()` should accept the username field,
  1427. plus all required fields as arguments. For example, if your user model
  1428. uses `email` as the username field, and has `date_of_birth` as a required
  1429. fields, then create_user should be defined as::
  1430. def create_user(self, email, date_of_birth, password=None):
  1431. # create user here
  1432. .. method:: models.CustomUserManager.create_superuser(*username_field*, password, **other_fields)
  1433. The prototype of `create_superuser()` should accept the username field,
  1434. plus all required fields as arguments. For example, if your user model
  1435. uses `email` as the username field, and has `date_of_birth` as a required
  1436. fields, then create_superuser should be defined as::
  1437. def create_superuser(self, email, date_of_birth, password):
  1438. # create superuser here
  1439. Unlike `create_user()`, `create_superuser()` *must* require the caller
  1440. to provider a password.
  1441. :class:`~django.contrib.auth.models.BaseUserManager` provides the following
  1442. utility methods:
  1443. .. class:: models.BaseUserManager
  1444. .. method:: models.BaseUserManager.normalize_email(email)
  1445. A classmethod that normalizes email addresses by lowercasing
  1446. the domain portion of the email address.
  1447. .. method:: models.BaseUserManager.get_by_natural_key(username)
  1448. Retrieves a user instance using the contents of the field
  1449. nominated by ``USERNAME_FIELD``.
  1450. .. method:: models.BaseUserManager.make_random_password(length=10, allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789')
  1451. Returns a random password with the given length and given string of
  1452. allowed characters. (Note that the default value of ``allowed_chars``
  1453. doesn't contain letters that can cause user confusion, including:
  1454. * ``i``, ``l``, ``I``, and ``1`` (lowercase letter i, lowercase
  1455. letter L, uppercase letter i, and the number one)
  1456. * ``o``, ``O``, and ``0`` (uppercase letter o, lowercase letter o,
  1457. and zero)
  1458. Extending Django's default User
  1459. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1460. If you're entirely happy with Django's :class:`~django.contrib.auth.models.User`
  1461. model and you just want to add some additional profile information, you can
  1462. simply subclass :class:`~django.contrib.auth.models.AbstractUser` and add your
  1463. custom profile fields.
  1464. Custom users and the built-in auth forms
  1465. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1466. As you may expect, built-in Django's :ref:`forms <built-in-auth-forms>`
  1467. and :ref:`views <other-built-in-views>` make certain assumptions about
  1468. the user model that they are working with.
  1469. If your user model doesn't follow the same assumptions, it may be necessary to define
  1470. a replacement form, and pass that form in as part of the configuration of the
  1471. auth views.
  1472. * :class:`~django.contrib.auth.forms.UserCreationForm`
  1473. Depends on the :class:`~django.contrib.auth.models.User` model.
  1474. Must be re-written for any custom user model.
  1475. * :class:`~django.contrib.auth.forms.UserChangeForm`
  1476. Depends on the :class:`~django.contrib.auth.models.User` model.
  1477. Must be re-written for any custom user model.
  1478. * :class:`~django.contrib.auth.forms.AuthenticationForm`
  1479. Works with any subclass of :class:`~django.contrib.auth.models.AbstractBaseUser`,
  1480. and will adapt to use the field defined in `USERNAME_FIELD`.
  1481. * :class:`~django.contrib.auth.forms.PasswordResetForm`
  1482. Assumes that the user model has an integer primary key, has a field named
  1483. `email` that can be used to identify the user, and a boolean field
  1484. named `is_active` to prevent password resets for inactive users.
  1485. * :class:`~django.contrib.auth.forms.SetPasswordForm`
  1486. Works with any subclass of :class:`~django.contrib.auth.models.AbstractBaseUser`
  1487. * :class:`~django.contrib.auth.forms.PasswordChangeForm`
  1488. Works with any subclass of :class:`~django.contrib.auth.models.AbstractBaseUser`
  1489. * :class:`~django.contrib.auth.forms.AdminPasswordChangeForm`
  1490. Works with any subclass of :class:`~django.contrib.auth.models.AbstractBaseUser`
  1491. Custom users and django.contrib.admin
  1492. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1493. If you want your custom User model to also work with Admin, your User model must
  1494. define some additional attributes and methods. These methods allow the admin to
  1495. control access of the User to admin content:
  1496. .. attribute:: User.is_staff
  1497. Returns True if the user is allowed to have access to the admin site.
  1498. .. attribute:: User.is_active
  1499. Returns True if the user account is currently active.
  1500. .. method:: User.has_perm(perm, obj=None):
  1501. Returns True if the user has the named permission. If `obj` is
  1502. provided, the permission needs to be checked against a specific object
  1503. instance.
  1504. .. method:: User.has_module_perms(app_label):
  1505. Returns True if the user has permission to access models in
  1506. the given app.
  1507. You will also need to register your custom User model with the admin. If
  1508. your custom User model extends :class:`~django.contrib.auth.models.AbstractUser`,
  1509. you can use Django's existing :class:`~django.contrib.auth.admin.UserAdmin`
  1510. class. However, if your User model extends
  1511. :class:`~django.contrib.auth.models.AbstractBaseUser`, you'll need to define
  1512. a custom ModelAdmin class. It may be possible to subclass the default
  1513. :class:`~django.contrib.auth.admin.UserAdmin`; however, you'll need to
  1514. override any of the definitions that refer to fields on
  1515. :class:`~django.contrib.auth.models.AbstractUser` that aren't on your
  1516. custom User class.
  1517. Custom users and permissions
  1518. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1519. To make it easy to include Django's permission framework into your own User
  1520. class, Django provides :class:`~django.contrib.auth.model.PermissionsMixin`.
  1521. This is an abstract model you can include in the class heirarchy for your User
  1522. model, giving you all the methods and database fields necessary to support
  1523. Django's permission model.
  1524. :class:`~django.contrib.auth.model.PermissionsMixin` provides the following
  1525. methods and attributes:
  1526. .. class:: models.PermissionsMixin
  1527. .. attribute:: models.PermissionsMixin.is_superuser
  1528. Boolean. Designates that this user has all permissions without
  1529. explicitly assigning them.
  1530. .. method:: models.PermissionsMixin.get_group_permissions(obj=None)
  1531. Returns a set of permission strings that the user has, through his/her
  1532. groups.
  1533. If ``obj`` is passed in, only returns the group permissions for
  1534. this specific object.
  1535. .. method:: models.PermissionsMixin.get_all_permissions(obj=None)
  1536. Returns a set of permission strings that the user has, both through
  1537. group and user permissions.
  1538. If ``obj`` is passed in, only returns the permissions for this
  1539. specific object.
  1540. .. method:: models.PermissionsMixin.has_perm(perm, obj=None)
  1541. Returns ``True`` if the user has the specified permission, where perm is
  1542. in the format ``"<app label>.<permission codename>"`` (see
  1543. `permissions`_). If the user is inactive, this method will
  1544. always return ``False``.
  1545. If ``obj`` is passed in, this method won't check for a permission for
  1546. the model, but for this specific object.
  1547. .. method:: models.PermissionsMixin.has_perms(perm_list, obj=None)
  1548. Returns ``True`` if the user has each of the specified permissions,
  1549. where each perm is in the format
  1550. ``"<app label>.<permission codename>"``. If the user is inactive,
  1551. this method will always return ``False``.
  1552. If ``obj`` is passed in, this method won't check for permissions for
  1553. the model, but for the specific object.
  1554. .. method:: models.PermissionsMixin.has_module_perms(package_name)
  1555. Returns ``True`` if the user has any permissions in the given package
  1556. (the Django app label). If the user is inactive, this method will
  1557. always return ``False``.
  1558. .. admonition:: ModelBackend
  1559. If you don't include the
  1560. :class:`~django.contrib.auth.model.PermissionsMixin`, you must ensure you
  1561. don't invoke the permissions methods on ``ModelBackend``. ``ModelBackend``
  1562. assumes that certain fields are available on your user model. If your User
  1563. model doesn't provide those fields, you will receive database errors when
  1564. you check permissions.
  1565. Custom users and Proxy models
  1566. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1567. One limitation of custom User models is that installing a custom User model
  1568. will break any proxy model extending :class:`~django.contrib.auth.models.User`.
  1569. Proxy models must be based on a concrete base class; by defining a custom User
  1570. model, you remove the ability of Django to reliably identify the base class.
  1571. If your project uses proxy models, you must either modify the proxy to extend
  1572. the User model that is currently in use in your project, or merge your proxy's
  1573. behavior into your User subclass.
  1574. Custom users and signals
  1575. ~~~~~~~~~~~~~~~~~~~~~~~~
  1576. Another limitation of custom User models is that you can't use
  1577. :func:`django.contrib.auth.get_user_model()` as the sender or target of a signal
  1578. handler. Instead, you must register the handler with the actual User model.
  1579. Custom users and testing/fixtures
  1580. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1581. If you are writing an application that interacts with the User model, you must
  1582. take some precautions to ensure that your test suite will run regardless of
  1583. the User model that is being used by a project. Any test that instantiates an
  1584. instance of User will fail if the User model has been swapped out. This
  1585. includes any attempt to create an instance of User with a fixture.
  1586. To ensure that your test suite will pass in any project configuration,
  1587. ``django.contrib.auth.tests.utils`` defines a ``@skipIfCustomUser`` decorator.
  1588. This decorator will cause a test case to be skipped if any User model other
  1589. than the default Django user is in use. This decorator can be applied to a
  1590. single test, or to an entire test class.
  1591. Depending on your application, tests may also be needed to be added to ensure
  1592. that the application works with *any* user model, not just the default User
  1593. model. To assist with this, Django provides two substitute user models that
  1594. can be used in test suites:
  1595. * :class:`django.contrib.auth.tests.custom_user.CustomUser`, a custom user
  1596. model that uses an ``email`` field as the username, and has a basic
  1597. admin-compliant permissions setup
  1598. * :class:`django.contrib.auth.tests.custom_user.ExtensionUser`, a custom
  1599. user model that extends :class:`~django.contrib.auth.models.AbstractUser`,
  1600. adding a ``date_of_birth`` field.
  1601. You can then use the ``@override_settings`` decorator to make that test run
  1602. with the custom User model. For example, here is a skeleton for a test that
  1603. would test three possible User models -- the default, plus the two User
  1604. models provided by ``auth`` app::
  1605. from django.contrib.auth.tests.utils import skipIfCustomUser
  1606. from django.test import TestCase
  1607. from django.test.utils import override_settings
  1608. class ApplicationTestCase(TestCase):
  1609. @skipIfCustomUser
  1610. def test_normal_user(self):
  1611. "Run tests for the normal user model"
  1612. self.assertSomething()
  1613. @override_settings(AUTH_USER_MODEL='auth.CustomUser')
  1614. def test_custom_user(self):
  1615. "Run tests for a custom user model with email-based authentication"
  1616. self.assertSomething()
  1617. @override_settings(AUTH_USER_MODEL='auth.ExtensionUser')
  1618. def test_extension_user(self):
  1619. "Run tests for a simple extension of the built-in User."
  1620. self.assertSomething()
  1621. A full example
  1622. --------------
  1623. Here is an example of an admin-compliant custom user app. This user model uses
  1624. an email address as the username, and has a required date of birth; it
  1625. provides no permission checking, beyond a simple `admin` flag on the user
  1626. account. This model would be compatible with all the built-in auth forms and
  1627. views, except for the User creation forms.
  1628. This code would all live in a ``models.py`` file for a custom
  1629. authentication app::
  1630. from django.db import models
  1631. from django.contrib.auth.models import (
  1632. BaseUserManager, AbstractBaseUser
  1633. )
  1634. class MyUserManager(BaseUserManager):
  1635. def create_user(self, email, date_of_birth, password=None):
  1636. """
  1637. Creates and saves a User with the given email, date of
  1638. birth and password.
  1639. """
  1640. if not email:
  1641. raise ValueError('Users must have an email address')
  1642. user = self.model(
  1643. email=MyUserManager.normalize_email(email),
  1644. date_of_birth=date_of_birth,
  1645. )
  1646. user.set_password(password)
  1647. user.save(using=self._db)
  1648. return user
  1649. def create_superuser(self, email, date_of_birth, password):
  1650. """
  1651. Creates and saves a superuser with the given email, date of
  1652. birth and password.
  1653. """
  1654. user = self.create_user(email,
  1655. password=password,
  1656. date_of_birth=date_of_birth
  1657. )
  1658. user.is_admin = True
  1659. user.save(using=self._db)
  1660. return user
  1661. class MyUser(AbstractBaseUser):
  1662. email = models.EmailField(
  1663. verbose_name='email address',
  1664. max_length=255,
  1665. unique=True,
  1666. db_index=True,
  1667. )
  1668. date_of_birth = models.DateField()
  1669. is_active = models.BooleanField(default=True)
  1670. is_admin = models.BooleanField(default=False)
  1671. objects = MyUserManager()
  1672. USERNAME_FIELD = 'email'
  1673. REQUIRED_FIELDS = ['date_of_birth']
  1674. def get_full_name(self):
  1675. # The user is identified by their email address
  1676. return self.email
  1677. def get_short_name(self):
  1678. # The user is identified by their email address
  1679. return self.email
  1680. def __unicode__(self):
  1681. return self.email
  1682. def has_perm(self, perm, obj=None):
  1683. "Does the user have a specific permission?"
  1684. # Simplest possible answer: Yes, always
  1685. return True
  1686. def has_module_perms(self, app_label):
  1687. "Does the user have permissions to view the app `app_label`?"
  1688. # Simplest possible answer: Yes, always
  1689. return True
  1690. @property
  1691. def is_staff(self):
  1692. "Is the user a member of staff?"
  1693. # Simplest possible answer: All admins are staff
  1694. return self.is_admin
  1695. Then, to register this custom User model with Django's admin, the following
  1696. code would be required in the app's ``admin.py`` file::
  1697. from django import forms
  1698. from django.contrib import admin
  1699. from django.contrib.auth.models import Group
  1700. from django.contrib.auth.admin import UserAdmin
  1701. from django.contrib.auth.forms import ReadOnlyPasswordHashField
  1702. from customauth.models import MyUser
  1703. class UserCreationForm(forms.ModelForm):
  1704. """A form for creating new users. Includes all the required
  1705. fields, plus a repeated password."""
  1706. password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
  1707. password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
  1708. class Meta:
  1709. model = MyUser
  1710. fields = ('email', 'date_of_birth')
  1711. def clean_password2(self):
  1712. # Check that the two password entries match
  1713. password1 = self.cleaned_data.get("password1")
  1714. password2 = self.cleaned_data.get("password2")
  1715. if password1 and password2 and password1 != password2:
  1716. raise forms.ValidationError("Passwords don't match")
  1717. return password2
  1718. def save(self, commit=True):
  1719. # Save the provided password in hashed format
  1720. user = super(UserCreationForm, self).save(commit=False)
  1721. user.set_password(self.cleaned_data["password1"])
  1722. if commit:
  1723. user.save()
  1724. return user
  1725. class UserChangeForm(forms.ModelForm):
  1726. """A form for updating users. Includes all the fields on
  1727. the user, but replaces the password field with admin's
  1728. password hash display field.
  1729. """
  1730. password = ReadOnlyPasswordHashField()
  1731. class Meta:
  1732. model = MyUser
  1733. def clean_password(self):
  1734. # Regardless of what the user provides, return the initial value.
  1735. # This is done here, rather than on the field, because the
  1736. # field does not have access to the initial value
  1737. return self.initial["password"]
  1738. class MyUserAdmin(UserAdmin):
  1739. # The forms to add and change user instances
  1740. form = UserChangeForm
  1741. add_form = UserCreationForm
  1742. # The fields to be used in displaying the User model.
  1743. # These override the definitions on the base UserAdmin
  1744. # that reference specific fields on auth.User.
  1745. list_display = ('email', 'date_of_birth', 'is_admin')
  1746. list_filter = ('is_admin',)
  1747. fieldsets = (
  1748. (None, {'fields': ('email', 'password')}),
  1749. ('Personal info', {'fields': ('date_of_birth',)}),
  1750. ('Permissions', {'fields': ('is_admin',)}),
  1751. ('Important dates', {'fields': ('last_login',)}),
  1752. )
  1753. add_fieldsets = (
  1754. (None, {
  1755. 'classes': ('wide',),
  1756. 'fields': ('email', 'date_of_birth', 'password1', 'password2')}
  1757. ),
  1758. )
  1759. search_fields = ('email',)
  1760. ordering = ('email',)
  1761. filter_horizontal = ()
  1762. # Now register the new UserAdmin...
  1763. admin.site.register(MyUser, MyUserAdmin)
  1764. # ... and, since we're not using Django's builtin permissions,
  1765. # unregister the Group model from admin.
  1766. admin.site.unregister(Group)
  1767. .. _authentication-backends:
  1768. Other authentication sources
  1769. ============================
  1770. The authentication that comes with Django is good enough for most common cases,
  1771. but you may have the need to hook into another authentication source -- that
  1772. is, another source of usernames and passwords or authentication methods.
  1773. For example, your company may already have an LDAP setup that stores a username
  1774. and password for every employee. It'd be a hassle for both the network
  1775. administrator and the users themselves if users had separate accounts in LDAP
  1776. and the Django-based applications.
  1777. So, to handle situations like this, the Django authentication system lets you
  1778. plug in other authentication sources. You can override Django's default
  1779. database-based scheme, or you can use the default system in tandem with other
  1780. systems.
  1781. See the :doc:`authentication backend reference </ref/authbackends>`
  1782. for information on the authentication backends included with Django.
  1783. Specifying authentication backends
  1784. ----------------------------------
  1785. Behind the scenes, Django maintains a list of "authentication backends" that it
  1786. checks for authentication. When somebody calls
  1787. :func:`django.contrib.auth.authenticate()` -- as described in :ref:`How to log
  1788. a user in <how-to-log-a-user-in>` above -- Django tries authenticating across
  1789. all of its authentication backends. If the first authentication method fails,
  1790. Django tries the second one, and so on, until all backends have been attempted.
  1791. The list of authentication backends to use is specified in the
  1792. :setting:`AUTHENTICATION_BACKENDS` setting. This should be a tuple of Python
  1793. path names that point to Python classes that know how to authenticate. These
  1794. classes can be anywhere on your Python path.
  1795. By default, :setting:`AUTHENTICATION_BACKENDS` is set to::
  1796. ('django.contrib.auth.backends.ModelBackend',)
  1797. That's the basic authentication backend that checks the Django users database
  1798. and queries the builtin permissions. It does not provide protection against
  1799. brute force attacks via any rate limiting mechanism. You may either implement
  1800. your own rate limiting mechanism in a custom auth backend, or use the
  1801. mechanisms provided by most Web servers.
  1802. The order of :setting:`AUTHENTICATION_BACKENDS` matters, so if the same
  1803. username and password is valid in multiple backends, Django will stop
  1804. processing at the first positive match.
  1805. .. note::
  1806. Once a user has authenticated, Django stores which backend was used to
  1807. authenticate the user in the user's session, and re-uses the same backend
  1808. for the duration of that session whenever access to the currently
  1809. authenticated user is needed. This effectively means that authentication
  1810. sources are cached on a per-session basis, so if you change
  1811. :setting:`AUTHENTICATION_BACKENDS`, you'll need to clear out session data if
  1812. you need to force users to re-authenticate using different methods. A simple
  1813. way to do that is simply to execute ``Session.objects.all().delete()``.
  1814. .. versionadded:: 1.6
  1815. If a backend raises a :class:`~django.core.exceptions.PermissionDenied`
  1816. exception, authentication will immediately fail. Django won't check the
  1817. backends that follow.
  1818. Writing an authentication backend
  1819. ---------------------------------
  1820. An authentication backend is a class that implements two required methods:
  1821. ``get_user(user_id)`` and ``authenticate(**credentials)``, as well as a set of
  1822. optional permission related :ref:`authorization methods <authorization_methods>`.
  1823. The ``get_user`` method takes a ``user_id`` -- which could be a username,
  1824. database ID or whatever -- and returns a ``User`` object.
  1825. The ``authenticate`` method takes credentials as keyword arguments. Most of
  1826. the time, it'll just look like this::
  1827. class MyBackend(object):
  1828. def authenticate(self, username=None, password=None):
  1829. # Check the username/password and return a User.
  1830. But it could also authenticate a token, like so::
  1831. class MyBackend(object):
  1832. def authenticate(self, token=None):
  1833. # Check the token and return a User.
  1834. Either way, ``authenticate`` should check the credentials it gets, and it
  1835. should return a ``User`` object that matches those credentials, if the
  1836. credentials are valid. If they're not valid, it should return ``None``.
  1837. The Django admin system is tightly coupled to the Django ``User`` object
  1838. described at the beginning of this document. For now, the best way to deal with
  1839. this is to create a Django ``User`` object for each user that exists for your
  1840. backend (e.g., in your LDAP directory, your external SQL database, etc.) You
  1841. can either write a script to do this in advance, or your ``authenticate``
  1842. method can do it the first time a user logs in.
  1843. Here's an example backend that authenticates against a username and password
  1844. variable defined in your ``settings.py`` file and creates a Django ``User``
  1845. object the first time a user authenticates::
  1846. from django.conf import settings
  1847. from django.contrib.auth.models import User, check_password
  1848. class SettingsBackend(object):
  1849. """
  1850. Authenticate against the settings ADMIN_LOGIN and ADMIN_PASSWORD.
  1851. Use the login name, and a hash of the password. For example:
  1852. ADMIN_LOGIN = 'admin'
  1853. ADMIN_PASSWORD = 'sha1$4e987$afbcf42e21bd417fb71db8c66b321e9fc33051de'
  1854. """
  1855. def authenticate(self, username=None, password=None):
  1856. login_valid = (settings.ADMIN_LOGIN == username)
  1857. pwd_valid = check_password(password, settings.ADMIN_PASSWORD)
  1858. if login_valid and pwd_valid:
  1859. try:
  1860. user = User.objects.get(username=username)
  1861. except User.DoesNotExist:
  1862. # Create a new user. Note that we can set password
  1863. # to anything, because it won't be checked; the password
  1864. # from settings.py will.
  1865. user = User(username=username, password='get from settings.py')
  1866. user.is_staff = True
  1867. user.is_superuser = True
  1868. user.save()
  1869. return user
  1870. return None
  1871. def get_user(self, user_id):
  1872. try:
  1873. return User.objects.get(pk=user_id)
  1874. except User.DoesNotExist:
  1875. return None
  1876. .. _authorization_methods:
  1877. Handling authorization in custom backends
  1878. -----------------------------------------
  1879. Custom auth backends can provide their own permissions.
  1880. The user model will delegate permission lookup functions
  1881. (:meth:`~django.contrib.auth.models.User.get_group_permissions()`,
  1882. :meth:`~django.contrib.auth.models.User.get_all_permissions()`,
  1883. :meth:`~django.contrib.auth.models.User.has_perm()`, and
  1884. :meth:`~django.contrib.auth.models.User.has_module_perms()`) to any
  1885. authentication backend that implements these functions.
  1886. The permissions given to the user will be the superset of all permissions
  1887. returned by all backends. That is, Django grants a permission to a user that
  1888. any one backend grants.
  1889. The simple backend above could implement permissions for the magic admin
  1890. fairly simply::
  1891. class SettingsBackend(object):
  1892. # ...
  1893. def has_perm(self, user_obj, perm, obj=None):
  1894. if user_obj.username == settings.ADMIN_LOGIN:
  1895. return True
  1896. else:
  1897. return False
  1898. This gives full permissions to the user granted access in the above example.
  1899. Notice that in addition to the same arguments given to the associated
  1900. :class:`django.contrib.auth.models.User` functions, the backend auth functions
  1901. all take the user object, which may be an anonymous user, as an argument.
  1902. A full authorization implementation can be found in the ``ModelBackend`` class
  1903. in `django/contrib/auth/backends.py`_, which is the default backend and queries
  1904. the ``auth_permission`` table most of the time. If you wish to provide
  1905. custom behavior for only part of the backend API, you can take advantage of
  1906. Python inheritence and subclass ``ModelBackend`` instead of implementing the
  1907. complete API in a custom backend.
  1908. .. _django/contrib/auth/backends.py: https://github.com/django/django/blob/master/django/contrib/auth/backends.py
  1909. .. _anonymous_auth:
  1910. Authorization for anonymous users
  1911. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1912. An anonymous user is one that is not authenticated i.e. they have provided no
  1913. valid authentication details. However, that does not necessarily mean they are
  1914. not authorized to do anything. At the most basic level, most Web sites
  1915. authorize anonymous users to browse most of the site, and many allow anonymous
  1916. posting of comments etc.
  1917. Django's permission framework does not have a place to store permissions for
  1918. anonymous users. However, the user object passed to an authentication backend
  1919. may be an :class:`django.contrib.auth.models.AnonymousUser` object, allowing
  1920. the backend to specify custom authorization behavior for anonymous users. This
  1921. is especially useful for the authors of re-usable apps, who can delegate all
  1922. questions of authorization to the auth backend, rather than needing settings,
  1923. for example, to control anonymous access.
  1924. .. _inactive_auth:
  1925. Authorization for inactive users
  1926. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1927. An inactive user is a one that is authenticated but has its attribute
  1928. ``is_active`` set to ``False``. However this does not mean they are not
  1929. authorized to do anything. For example they are allowed to activate their
  1930. account.
  1931. The support for anonymous users in the permission system allows for a scenario
  1932. where anonymous users have permissions to do something while inactive
  1933. authenticated users do not.
  1934. Do not forget to test for the ``is_active`` attribute of the user in your own
  1935. backend permission methods.
  1936. Handling object permissions
  1937. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1938. Django's permission framework has a foundation for object permissions, though
  1939. there is no implementation for it in the core. That means that checking for
  1940. object permissions will always return ``False`` or an empty list (depending on
  1941. the check performed). An authentication backend will receive the keyword
  1942. parameters ``obj`` and ``user_obj`` for each object related authorization
  1943. method and can return the object level permission as appropriate.