2
0

index.txt 99 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543
  1. =====================
  2. The Django admin site
  3. =====================
  4. .. module:: django.contrib.admin
  5. :synopsis: Django's admin site.
  6. One of the most powerful parts of Django is the automatic admin interface. It
  7. reads metadata in your model to provide a powerful and production-ready
  8. interface that content producers can immediately use to start adding content to
  9. the site. In this document, we discuss how to activate, use and customize
  10. Django's admin interface.
  11. Overview
  12. ========
  13. The admin is enabled in the default project template used by
  14. :djadmin:`startproject`.
  15. .. versionchanged:: 1.6
  16. In previous versions, the admin wasn't enabled by default.
  17. For reference, here are the requirements:
  18. 1. Add ``'django.contrib.admin'`` to your :setting:`INSTALLED_APPS`
  19. setting.
  20. 2. The admin has four dependencies - :mod:`django.contrib.auth`,
  21. :mod:`django.contrib.contenttypes`,
  22. :mod:`django.contrib.messages` and
  23. :mod:`django.contrib.sessions`. If these applications are not
  24. in your :setting:`INSTALLED_APPS` list, add them.
  25. 3. Add ``django.contrib.messages.context_processors.messages`` to
  26. :setting:`TEMPLATE_CONTEXT_PROCESSORS` as well as
  27. :class:`django.contrib.auth.middleware.AuthenticationMiddleware` and
  28. :class:`django.contrib.messages.middleware.MessageMiddleware` to
  29. :setting:`MIDDLEWARE_CLASSES`. (These are all active by default, so
  30. you only need to do this if you've manually tweaked the settings.)
  31. 4. Determine which of your application's models should be editable in the
  32. admin interface.
  33. 5. For each of those models, optionally create a ``ModelAdmin`` class that
  34. encapsulates the customized admin functionality and options for that
  35. particular model.
  36. 6. Instantiate an ``AdminSite`` and tell it about each of your models and
  37. ``ModelAdmin`` classes.
  38. 7. Hook the ``AdminSite`` instance into your URLconf.
  39. After you've taken these steps, you'll be able to use your Django admin site
  40. by visiting the URL you hooked it into (``/admin/``, by default).
  41. Other topics
  42. ------------
  43. .. toctree::
  44. :maxdepth: 1
  45. actions
  46. admindocs
  47. .. seealso::
  48. For information about serving the static files (images, JavaScript, and
  49. CSS) associated with the admin in production, see :ref:`serving-files`.
  50. Having problems? Try :doc:`/faq/admin`.
  51. ``ModelAdmin`` objects
  52. ======================
  53. .. class:: ModelAdmin
  54. The ``ModelAdmin`` class is the representation of a model in the admin
  55. interface. These are stored in a file named ``admin.py`` in your
  56. application. Let's take a look at a very simple example of
  57. the ``ModelAdmin``::
  58. from django.contrib import admin
  59. from myproject.myapp.models import Author
  60. class AuthorAdmin(admin.ModelAdmin):
  61. pass
  62. admin.site.register(Author, AuthorAdmin)
  63. .. admonition:: Do you need a ``ModelAdmin`` object at all?
  64. In the preceding example, the ``ModelAdmin`` class doesn't define any
  65. custom values (yet). As a result, the default admin interface will be
  66. provided. If you are happy with the default admin interface, you don't
  67. need to define a ``ModelAdmin`` object at all -- you can register the
  68. model class without providing a ``ModelAdmin`` description. The
  69. preceding example could be simplified to::
  70. from django.contrib import admin
  71. from myproject.myapp.models import Author
  72. admin.site.register(Author)
  73. The register decorator
  74. ----------------------
  75. .. function:: register(*models, [site=django.admin.sites.site])
  76. .. versionadded:: 1.7
  77. There is also a decorator for registering your ``ModelAdmin`` classes::
  78. from django.contrib import admin
  79. from .models import Author
  80. @admin.register(Author)
  81. class AuthorAdmin(admin.ModelAdmin):
  82. pass
  83. It is given one or more model classes to register with the ``ModelAdmin``
  84. and an optional keyword argument ``site`` if you are not using the default
  85. ``AdminSite``::
  86. from django.contrib import admin
  87. from .models import Author, Reader, Editor
  88. from myproject.admin_site import custom_admin_site
  89. @admin.register(Author, Reader, Editor, site=custom_admin_site)
  90. class PersonAdmin(admin.ModelAdmin):
  91. pass
  92. ``ModelAdmin`` options
  93. ----------------------
  94. The ``ModelAdmin`` is very flexible. It has several options for dealing with
  95. customizing the interface. All options are defined on the ``ModelAdmin``
  96. subclass::
  97. from django.contrib import admin
  98. class AuthorAdmin(admin.ModelAdmin):
  99. date_hierarchy = 'pub_date'
  100. .. attribute:: ModelAdmin.actions
  101. A list of actions to make available on the change list page. See
  102. :doc:`/ref/contrib/admin/actions` for details.
  103. .. attribute:: ModelAdmin.actions_on_top
  104. .. attribute:: ModelAdmin.actions_on_bottom
  105. Controls where on the page the actions bar appears. By default, the admin
  106. changelist displays actions at the top of the page (``actions_on_top = True;
  107. actions_on_bottom = False``).
  108. .. attribute:: ModelAdmin.actions_selection_counter
  109. Controls whether a selection counter is displayed next to the action dropdown.
  110. By default, the admin changelist will display it
  111. (``actions_selection_counter = True``).
  112. .. attribute:: ModelAdmin.date_hierarchy
  113. Set ``date_hierarchy`` to the name of a ``DateField`` or ``DateTimeField``
  114. in your model, and the change list page will include a date-based drilldown
  115. navigation by that field.
  116. Example::
  117. date_hierarchy = 'pub_date'
  118. This will intelligently populate itself based on available data,
  119. e.g. if all the dates are in one month, it'll show the day-level
  120. drill-down only.
  121. .. note::
  122. ``date_hierarchy`` uses :meth:`QuerySet.datetimes()
  123. <django.db.models.query.QuerySet.datetimes>` internally. Please refer
  124. to its documentation for some caveats when time zone support is
  125. enabled (:setting:`USE_TZ = True <USE_TZ>`).
  126. .. attribute:: ModelAdmin.exclude
  127. This attribute, if given, should be a list of field names to exclude from
  128. the form.
  129. For example, let's consider the following model::
  130. from django.db import models
  131. class Author(models.Model):
  132. name = models.CharField(max_length=100)
  133. title = models.CharField(max_length=3)
  134. birth_date = models.DateField(blank=True, null=True)
  135. If you want a form for the ``Author`` model that includes only the ``name``
  136. and ``title`` fields, you would specify ``fields`` or ``exclude`` like
  137. this::
  138. from django.contrib import admin
  139. class AuthorAdmin(admin.ModelAdmin):
  140. fields = ('name', 'title')
  141. class AuthorAdmin(admin.ModelAdmin):
  142. exclude = ('birth_date',)
  143. Since the Author model only has three fields, ``name``, ``title``, and
  144. ``birth_date``, the forms resulting from the above declarations will
  145. contain exactly the same fields.
  146. .. attribute:: ModelAdmin.fields
  147. If you need to achieve simple changes in the layout of fields in the forms
  148. of the "add" and "change" pages like only showing a subset of the available
  149. fields, modifying their order or grouping them in rows you can use the
  150. ``fields`` option (for more complex layout needs see the
  151. :attr:`~ModelAdmin.fieldsets` option described in the next section). For
  152. example, you could define a simpler version of the admin form for the
  153. :class:`django.contrib.flatpages.models.FlatPage` model as follows::
  154. class FlatPageAdmin(admin.ModelAdmin):
  155. fields = ('url', 'title', 'content')
  156. In the above example, only the fields ``url``, ``title`` and ``content``
  157. will be displayed, sequentially, in the form. ``fields`` can contain
  158. values defined in :attr:`ModelAdmin.readonly_fields` to be displayed as
  159. read-only.
  160. The ``fields`` option, unlike :attr:`~ModelAdmin.list_display`, may only
  161. contain names of fields on the model or the form specified by
  162. :attr:`~ModelAdmin.form`. It may contain callables only if they are listed
  163. in :attr:`~ModelAdmin.readonly_fields`.
  164. To display multiple fields on the same line, wrap those fields in their own
  165. tuple. In this example, the ``url`` and ``title`` fields will display on the
  166. same line and the ``content`` field will be displayed below them in its
  167. own line::
  168. class FlatPageAdmin(admin.ModelAdmin):
  169. fields = (('url', 'title'), 'content')
  170. .. admonition:: Note
  171. This ``fields`` option should not be confused with the ``fields``
  172. dictionary key that is within the :attr:`~ModelAdmin.fieldsets` option,
  173. as described in the next section.
  174. If neither ``fields`` nor :attr:`~ModelAdmin.fieldsets` options are present,
  175. Django will default to displaying each field that isn't an ``AutoField`` and
  176. has ``editable=True``, in a single fieldset, in the same order as the fields
  177. are defined in the model.
  178. .. attribute:: ModelAdmin.fieldsets
  179. Set ``fieldsets`` to control the layout of admin "add" and "change" pages.
  180. ``fieldsets`` is a list of two-tuples, in which each two-tuple represents a
  181. ``<fieldset>`` on the admin form page. (A ``<fieldset>`` is a "section" of
  182. the form.)
  183. The two-tuples are in the format ``(name, field_options)``, where ``name``
  184. is a string representing the title of the fieldset and ``field_options`` is
  185. a dictionary of information about the fieldset, including a list of fields
  186. to be displayed in it.
  187. A full example, taken from the
  188. :class:`django.contrib.flatpages.models.FlatPage` model::
  189. from django.contrib import admin
  190. class FlatPageAdmin(admin.ModelAdmin):
  191. fieldsets = (
  192. (None, {
  193. 'fields': ('url', 'title', 'content', 'sites')
  194. }),
  195. ('Advanced options', {
  196. 'classes': ('collapse',),
  197. 'fields': ('enable_comments', 'registration_required', 'template_name')
  198. }),
  199. )
  200. This results in an admin page that looks like:
  201. .. image:: _images/flatfiles_admin.png
  202. If neither ``fieldsets`` nor :attr:`~ModelAdmin.fields` options are present,
  203. Django will default to displaying each field that isn't an ``AutoField`` and
  204. has ``editable=True``, in a single fieldset, in the same order as the fields
  205. are defined in the model.
  206. The ``field_options`` dictionary can have the following keys:
  207. * ``fields``
  208. A tuple of field names to display in this fieldset. This key is
  209. required.
  210. Example::
  211. {
  212. 'fields': ('first_name', 'last_name', 'address', 'city', 'state'),
  213. }
  214. As with the :attr:`~ModelAdmin.fields` option, to display multiple
  215. fields on the same line, wrap those fields in their own tuple. In this
  216. example, the ``first_name`` and ``last_name`` fields will display on
  217. the same line::
  218. {
  219. 'fields': (('first_name', 'last_name'), 'address', 'city', 'state'),
  220. }
  221. ``fields`` can contain values defined in
  222. :attr:`~ModelAdmin.readonly_fields` to be displayed as read-only.
  223. If you add the name of a callable to ``fields``, the same rule applies
  224. as with the :attr:`~ModelAdmin.fields` option: the callable must be
  225. listed in :attr:`~ModelAdmin.readonly_fields`.
  226. * ``classes``
  227. A list containing extra CSS classes to apply to the fieldset.
  228. Example::
  229. {
  230. 'classes': ('wide', 'extrapretty'),
  231. }
  232. Two useful classes defined by the default admin site stylesheet are
  233. ``collapse`` and ``wide``. Fieldsets with the ``collapse`` style
  234. will be initially collapsed in the admin and replaced with a small
  235. "click to expand" link. Fieldsets with the ``wide`` style will be
  236. given extra horizontal space.
  237. * ``description``
  238. A string of optional extra text to be displayed at the top of each
  239. fieldset, under the heading of the fieldset.
  240. Note that this value is *not* HTML-escaped when it's displayed in
  241. the admin interface. This lets you include HTML if you so desire.
  242. Alternatively you can use plain text and
  243. ``django.utils.html.escape()`` to escape any HTML special
  244. characters.
  245. .. attribute:: ModelAdmin.filter_horizontal
  246. By default, a :class:`~django.db.models.ManyToManyField` is displayed in
  247. the admin site with a ``<select multiple>``. However, multiple-select boxes
  248. can be difficult to use when selecting many items. Adding a
  249. :class:`~django.db.models.ManyToManyField` to this list will instead use
  250. a nifty unobtrusive JavaScript "filter" interface that allows searching
  251. within the options. The unselected and selected options appear in two boxes
  252. side by side. See :attr:`~ModelAdmin.filter_vertical` to use a vertical
  253. interface.
  254. .. attribute:: ModelAdmin.filter_vertical
  255. Same as :attr:`~ModelAdmin.filter_horizontal`, but uses a vertical display
  256. of the filter interface with the box of unselected options appearing above
  257. the box of selected options.
  258. .. attribute:: ModelAdmin.form
  259. By default a ``ModelForm`` is dynamically created for your model. It is
  260. used to create the form presented on both the add/change pages. You can
  261. easily provide your own ``ModelForm`` to override any default form behavior
  262. on the add/change pages. Alternatively, you can customize the default
  263. form rather than specifying an entirely new one by using the
  264. :meth:`ModelAdmin.get_form` method.
  265. For an example see the section `Adding custom validation to the admin`_.
  266. .. admonition:: Note
  267. .. versionchanged:: 1.6
  268. If you define the ``Meta.model`` attribute on a
  269. :class:`~django.forms.ModelForm`, you must also define the
  270. ``Meta.fields`` attribute (or the ``Meta.exclude`` attribute). However,
  271. since the admin has its own way of defining fields, the ``Meta.fields``
  272. attribute will be ignored.
  273. If the ``ModelForm`` is only going to be used for the admin, the easiest
  274. solution is to omit the ``Meta.model`` attribute, since ``ModelAdmin``
  275. will provide the correct model to use. Alternatively, you can set
  276. ``fields = []`` in the ``Meta`` class to satisfy the validation on the
  277. ``ModelForm``.
  278. .. admonition:: Note
  279. If your ``ModelForm`` and ``ModelAdmin`` both define an ``exclude``
  280. option then ``ModelAdmin`` takes precedence::
  281. from django import forms
  282. from django.contrib import admin
  283. from myapp.models import Person
  284. class PersonForm(forms.ModelForm):
  285. class Meta:
  286. model = Person
  287. exclude = ['name']
  288. class PersonAdmin(admin.ModelAdmin):
  289. exclude = ['age']
  290. form = PersonForm
  291. In the above example, the "age" field will be excluded but the "name"
  292. field will be included in the generated form.
  293. .. attribute:: ModelAdmin.formfield_overrides
  294. This provides a quick-and-dirty way to override some of the
  295. :class:`~django.forms.Field` options for use in the admin.
  296. ``formfield_overrides`` is a dictionary mapping a field class to a dict of
  297. arguments to pass to the field at construction time.
  298. Since that's a bit abstract, let's look at a concrete example. The most
  299. common use of ``formfield_overrides`` is to add a custom widget for a
  300. certain type of field. So, imagine we've written a ``RichTextEditorWidget``
  301. that we'd like to use for large text fields instead of the default
  302. ``<textarea>``. Here's how we'd do that::
  303. from django.db import models
  304. from django.contrib import admin
  305. # Import our custom widget and our model from where they're defined
  306. from myapp.widgets import RichTextEditorWidget
  307. from myapp.models import MyModel
  308. class MyModelAdmin(admin.ModelAdmin):
  309. formfield_overrides = {
  310. models.TextField: {'widget': RichTextEditorWidget},
  311. }
  312. Note that the key in the dictionary is the actual field class, *not* a
  313. string. The value is another dictionary; these arguments will be passed to
  314. the form field's ``__init__()`` method. See :doc:`/ref/forms/api` for
  315. details.
  316. .. warning::
  317. If you want to use a custom widget with a relation field (i.e.
  318. :class:`~django.db.models.ForeignKey` or
  319. :class:`~django.db.models.ManyToManyField`), make sure you haven't
  320. included that field's name in ``raw_id_fields`` or ``radio_fields``.
  321. ``formfield_overrides`` won't let you change the widget on relation
  322. fields that have ``raw_id_fields`` or ``radio_fields`` set. That's
  323. because ``raw_id_fields`` and ``radio_fields`` imply custom widgets of
  324. their own.
  325. .. attribute:: ModelAdmin.inlines
  326. See :class:`InlineModelAdmin` objects below as well as
  327. :meth:`ModelAdmin.get_formsets_with_inlines`.
  328. .. attribute:: ModelAdmin.list_display
  329. Set ``list_display`` to control which fields are displayed on the change
  330. list page of the admin.
  331. Example::
  332. list_display = ('first_name', 'last_name')
  333. If you don't set ``list_display``, the admin site will display a single
  334. column that displays the ``__unicode__()`` (``__str__()`` on Python 3)
  335. representation of each object.
  336. You have four possible values that can be used in ``list_display``:
  337. * A field of the model. For example::
  338. class PersonAdmin(admin.ModelAdmin):
  339. list_display = ('first_name', 'last_name')
  340. * A callable that accepts one parameter for the model instance. For
  341. example::
  342. def upper_case_name(obj):
  343. return ("%s %s" % (obj.first_name, obj.last_name)).upper()
  344. upper_case_name.short_description = 'Name'
  345. class PersonAdmin(admin.ModelAdmin):
  346. list_display = (upper_case_name,)
  347. * A string representing an attribute on the ``ModelAdmin``. This
  348. behaves same as the callable. For example::
  349. class PersonAdmin(admin.ModelAdmin):
  350. list_display = ('upper_case_name',)
  351. def upper_case_name(self, obj):
  352. return ("%s %s" % (obj.first_name, obj.last_name)).upper()
  353. upper_case_name.short_description = 'Name'
  354. * A string representing an attribute on the model. This behaves almost
  355. the same as the callable, but ``self`` in this context is the model
  356. instance. Here's a full model example::
  357. from django.db import models
  358. from django.contrib import admin
  359. class Person(models.Model):
  360. name = models.CharField(max_length=50)
  361. birthday = models.DateField()
  362. def decade_born_in(self):
  363. return self.birthday.strftime('%Y')[:3] + "0's"
  364. decade_born_in.short_description = 'Birth decade'
  365. class PersonAdmin(admin.ModelAdmin):
  366. list_display = ('name', 'decade_born_in')
  367. A few special cases to note about ``list_display``:
  368. * If the field is a ``ForeignKey``, Django will display the
  369. ``__unicode__()`` (``__str__()`` on Python 3) of the related object.
  370. * ``ManyToManyField`` fields aren't supported, because that would
  371. entail executing a separate SQL statement for each row in the table.
  372. If you want to do this nonetheless, give your model a custom method,
  373. and add that method's name to ``list_display``. (See below for more
  374. on custom methods in ``list_display``.)
  375. * If the field is a ``BooleanField`` or ``NullBooleanField``, Django
  376. will display a pretty "on" or "off" icon instead of ``True`` or
  377. ``False``.
  378. * If the string given is a method of the model, ``ModelAdmin`` or a
  379. callable, Django will HTML-escape the output by default. If you'd
  380. rather not escape the output of the method, give the method an
  381. ``allow_tags`` attribute whose value is ``True``. However, to avoid an
  382. XSS vulnerability, you should use :func:`~django.utils.html.format_html`
  383. to escape user-provided inputs.
  384. Here's a full example model::
  385. from django.db import models
  386. from django.contrib import admin
  387. from django.utils.html import format_html
  388. class Person(models.Model):
  389. first_name = models.CharField(max_length=50)
  390. last_name = models.CharField(max_length=50)
  391. color_code = models.CharField(max_length=6)
  392. def colored_name(self):
  393. return format_html('<span style="color: #{0};">{1} {2}</span>',
  394. self.color_code,
  395. self.first_name,
  396. self.last_name)
  397. colored_name.allow_tags = True
  398. class PersonAdmin(admin.ModelAdmin):
  399. list_display = ('first_name', 'last_name', 'colored_name')
  400. * If the string given is a method of the model, ``ModelAdmin`` or a
  401. callable that returns True or False Django will display a pretty
  402. "on" or "off" icon if you give the method a ``boolean`` attribute
  403. whose value is ``True``.
  404. Here's a full example model::
  405. from django.db import models
  406. from django.contrib import admin
  407. class Person(models.Model):
  408. first_name = models.CharField(max_length=50)
  409. birthday = models.DateField()
  410. def born_in_fifties(self):
  411. return self.birthday.strftime('%Y')[:3] == '195'
  412. born_in_fifties.boolean = True
  413. class PersonAdmin(admin.ModelAdmin):
  414. list_display = ('name', 'born_in_fifties')
  415. * The ``__str__()`` and ``__unicode__()`` methods are just as valid in
  416. ``list_display`` as any other model method, so it's perfectly OK to
  417. do this::
  418. list_display = ('__unicode__', 'some_other_field')
  419. * Usually, elements of ``list_display`` that aren't actual database
  420. fields can't be used in sorting (because Django does all the sorting
  421. at the database level).
  422. However, if an element of ``list_display`` represents a certain
  423. database field, you can indicate this fact by setting the
  424. ``admin_order_field`` attribute of the item.
  425. For example::
  426. from django.db import models
  427. from django.contrib import admin
  428. from django.utils.html import format_html
  429. class Person(models.Model):
  430. first_name = models.CharField(max_length=50)
  431. color_code = models.CharField(max_length=6)
  432. def colored_first_name(self):
  433. return format_html('<span style="color: #{0};">{1}</span>',
  434. self.color_code,
  435. self.first_name)
  436. colored_first_name.allow_tags = True
  437. colored_first_name.admin_order_field = 'first_name'
  438. class PersonAdmin(admin.ModelAdmin):
  439. list_display = ('first_name', 'colored_first_name')
  440. The above will tell Django to order by the ``first_name`` field when
  441. trying to sort by ``colored_first_name`` in the admin.
  442. * Elements of ``list_display`` can also be properties. Please note however,
  443. that due to the way properties work in Python, setting
  444. ``short_description`` on a property is only possible when using the
  445. ``property()`` function and **not** with the ``@property`` decorator.
  446. For example::
  447. class Person(object):
  448. first_name = models.CharField(max_length=50)
  449. last_name = models.CharField(max_length=50)
  450. def my_property(self):
  451. return self.first_name + ' ' + self.last_name
  452. my_property.short_description = "Full name of the person"
  453. full_name = property(my_property)
  454. class PersonAdmin(admin.ModelAdmin):
  455. list_display = ('full_name',)
  456. * .. versionadded:: 1.6
  457. The field names in ``list_display`` will also appear as CSS classes in
  458. the HTML output, in the form of ``column-<field_name>`` on each ``<th>``
  459. element. This can be used to set column widths in a CSS file for example.
  460. .. attribute:: ModelAdmin.list_display_links
  461. Use ``list_display_links`` to control if and which fields in
  462. :attr:`list_display` should be linked to the "change" page for an object.
  463. By default, the change list page will link the first column -- the first
  464. field specified in ``list_display`` -- to the change page for each item.
  465. But ``list_display_links`` lets you change this:
  466. * Set it to ``None`` to get no links at all.
  467. * Set it to a list or tuple of fields (in the same format as
  468. ``list_display``) whose columns you want converted to links.
  469. You can specify one or many fields. As long as the fields appear in
  470. ``list_display``, Django doesn't care how many (or how few) fields are
  471. linked. The only requirement is that if you want to use
  472. ``list_display_links`` in this fashion, you must define ``list_display``.
  473. In this example, the ``first_name`` and ``last_name`` fields will be
  474. linked on the change list page::
  475. class PersonAdmin(admin.ModelAdmin):
  476. list_display = ('first_name', 'last_name', 'birthday')
  477. list_display_links = ('first_name', 'last_name')
  478. In this example, the change list page grid will have no links::
  479. class AuditEntryAdmin(admin.ModelAdmin):
  480. list_display = ('timestamp', 'message')
  481. list_display_links = None
  482. .. versionchanged:: 1.7
  483. ``None`` was added as a valid ``list_display_links`` value.
  484. .. _admin-list-editable:
  485. .. attribute:: ModelAdmin.list_editable
  486. Set ``list_editable`` to a list of field names on the model which will
  487. allow editing on the change list page. That is, fields listed in
  488. ``list_editable`` will be displayed as form widgets on the change list
  489. page, allowing users to edit and save multiple rows at once.
  490. .. note::
  491. ``list_editable`` interacts with a couple of other options in
  492. particular ways; you should note the following rules:
  493. * Any field in ``list_editable`` must also be in ``list_display``.
  494. You can't edit a field that's not displayed!
  495. * The same field can't be listed in both ``list_editable`` and
  496. ``list_display_links`` -- a field can't be both a form and
  497. a link.
  498. You'll get a validation error if either of these rules are broken.
  499. .. attribute:: ModelAdmin.list_filter
  500. Set ``list_filter`` to activate filters in the right sidebar of the change
  501. list page of the admin, as illustrated in the following screenshot:
  502. .. image:: _images/users_changelist.png
  503. ``list_filter`` should be a list or tuple of elements, where each element
  504. should be of one of the following types:
  505. * a field name, where the specified field should be either a
  506. ``BooleanField``, ``CharField``, ``DateField``, ``DateTimeField``,
  507. ``IntegerField``, ``ForeignKey`` or ``ManyToManyField``, for example::
  508. class PersonAdmin(admin.ModelAdmin):
  509. list_filter = ('is_staff', 'company')
  510. Field names in ``list_filter`` can also span relations
  511. using the ``__`` lookup, for example::
  512. class PersonAdmin(admin.UserAdmin):
  513. list_filter = ('company__name',)
  514. * a class inheriting from ``django.contrib.admin.SimpleListFilter``,
  515. which you need to provide the ``title`` and ``parameter_name``
  516. attributes to and override the ``lookups`` and ``queryset`` methods,
  517. e.g.::
  518. from datetime import date
  519. from django.contrib import admin
  520. from django.utils.translation import ugettext_lazy as _
  521. class DecadeBornListFilter(admin.SimpleListFilter):
  522. # Human-readable title which will be displayed in the
  523. # right admin sidebar just above the filter options.
  524. title = _('decade born')
  525. # Parameter for the filter that will be used in the URL query.
  526. parameter_name = 'decade'
  527. def lookups(self, request, model_admin):
  528. """
  529. Returns a list of tuples. The first element in each
  530. tuple is the coded value for the option that will
  531. appear in the URL query. The second element is the
  532. human-readable name for the option that will appear
  533. in the right sidebar.
  534. """
  535. return (
  536. ('80s', _('in the eighties')),
  537. ('90s', _('in the nineties')),
  538. )
  539. def queryset(self, request, queryset):
  540. """
  541. Returns the filtered queryset based on the value
  542. provided in the query string and retrievable via
  543. `self.value()`.
  544. """
  545. # Compare the requested value (either '80s' or '90s')
  546. # to decide how to filter the queryset.
  547. if self.value() == '80s':
  548. return queryset.filter(birthday__gte=date(1980, 1, 1),
  549. birthday__lte=date(1989, 12, 31))
  550. if self.value() == '90s':
  551. return queryset.filter(birthday__gte=date(1990, 1, 1),
  552. birthday__lte=date(1999, 12, 31))
  553. class PersonAdmin(admin.ModelAdmin):
  554. list_filter = (DecadeBornListFilter,)
  555. .. note::
  556. As a convenience, the ``HttpRequest`` object is passed to the
  557. ``lookups`` and ``queryset`` methods, for example::
  558. class AuthDecadeBornListFilter(DecadeBornListFilter):
  559. def lookups(self, request, model_admin):
  560. if request.user.is_superuser:
  561. return super(AuthDecadeBornListFilter,
  562. self).lookups(request, model_admin)
  563. def queryset(self, request, queryset):
  564. if request.user.is_superuser:
  565. return super(AuthDecadeBornListFilter,
  566. self).queryset(request, queryset)
  567. Also as a convenience, the ``ModelAdmin`` object is passed to
  568. the ``lookups`` method, for example if you want to base the
  569. lookups on the available data::
  570. class AdvancedDecadeBornListFilter(DecadeBornListFilter):
  571. def lookups(self, request, model_admin):
  572. """
  573. Only show the lookups if there actually is
  574. anyone born in the corresponding decades.
  575. """
  576. qs = model_admin.get_queryset(request)
  577. if qs.filter(birthday__gte=date(1980, 1, 1),
  578. birthday__lte=date(1989, 12, 31)).exists():
  579. yield ('80s', _('in the eighties'))
  580. if qs.filter(birthday__gte=date(1990, 1, 1),
  581. birthday__lte=date(1999, 12, 31)).exists():
  582. yield ('90s', _('in the nineties'))
  583. * a tuple, where the first element is a field name and the second
  584. element is a class inheriting from
  585. ``django.contrib.admin.FieldListFilter``, for example::
  586. class PersonAdmin(admin.ModelAdmin):
  587. list_filter = (
  588. ('is_staff', admin.BooleanFieldListFilter),
  589. )
  590. .. note::
  591. The ``FieldListFilter`` API is considered internal and might be
  592. changed.
  593. It is possible to specify a custom template for rendering a list filter::
  594. class FilterWithCustomTemplate(admin.SimpleListFilter):
  595. template = "custom_template.html"
  596. See the default template provided by django (``admin/filter.html``) for
  597. a concrete example.
  598. .. attribute:: ModelAdmin.list_max_show_all
  599. Set ``list_max_show_all`` to control how many items can appear on a "Show
  600. all" admin change list page. The admin will display a "Show all" link on the
  601. change list only if the total result count is less than or equal to this
  602. setting. By default, this is set to ``200``.
  603. .. attribute:: ModelAdmin.list_per_page
  604. Set ``list_per_page`` to control how many items appear on each paginated
  605. admin change list page. By default, this is set to ``100``.
  606. .. attribute:: ModelAdmin.list_select_related
  607. Set ``list_select_related`` to tell Django to use
  608. :meth:`~django.db.models.query.QuerySet.select_related` in retrieving
  609. the list of objects on the admin change list page. This can save you a
  610. bunch of database queries.
  611. .. versionchanged:: 1.6
  612. The value should be either a boolean, a list or a tuple. Default is
  613. ``False``.
  614. When value is ``True``, ``select_related()`` will always be called. When
  615. value is set to ``False``, Django will look at ``list_display`` and call
  616. ``select_related()`` if any ``ForeignKey`` is present.
  617. If you need more fine-grained control, use a tuple (or list) as value for
  618. ``list_select_related``. Empty tuple will prevent Django from calling
  619. ``select_related`` at all. Any other tuple will be passed directly to
  620. ``select_related`` as parameters. For example::
  621. class ArticleAdmin(admin.ModelAdmin):
  622. list_select_related = ('author', 'category')
  623. will call ``select_related('author', 'category')``.
  624. .. attribute:: ModelAdmin.ordering
  625. Set ``ordering`` to specify how lists of objects should be ordered in the
  626. Django admin views. This should be a list or tuple in the same format as a
  627. model's :attr:`~django.db.models.Options.ordering` parameter.
  628. If this isn't provided, the Django admin will use the model's default
  629. ordering.
  630. If you need to specify a dynamic order (for example depending on user or
  631. language) you can implement a :meth:`~ModelAdmin.get_ordering` method.
  632. .. attribute:: ModelAdmin.paginator
  633. The paginator class to be used for pagination. By default,
  634. :class:`django.core.paginator.Paginator` is used. If the custom paginator
  635. class doesn't have the same constructor interface as
  636. :class:`django.core.paginator.Paginator`, you will also need to
  637. provide an implementation for :meth:`ModelAdmin.get_paginator`.
  638. .. attribute:: ModelAdmin.prepopulated_fields
  639. Set ``prepopulated_fields`` to a dictionary mapping field names to the
  640. fields it should prepopulate from::
  641. class ArticleAdmin(admin.ModelAdmin):
  642. prepopulated_fields = {"slug": ("title",)}
  643. When set, the given fields will use a bit of JavaScript to populate from
  644. the fields assigned. The main use for this functionality is to
  645. automatically generate the value for ``SlugField`` fields from one or more
  646. other fields. The generated value is produced by concatenating the values
  647. of the source fields, and then by transforming that result into a valid
  648. slug (e.g. substituting dashes for spaces).
  649. ``prepopulated_fields`` doesn't accept ``DateTimeField``, ``ForeignKey``,
  650. nor ``ManyToManyField`` fields.
  651. .. attribute:: ModelAdmin.preserve_filters
  652. .. versionadded:: 1.6
  653. The admin now preserves filters on the list view after creating, editing
  654. or deleting an object. You can restore the previous behavior of clearing
  655. filters by setting this attribute to ``False``.
  656. .. attribute:: ModelAdmin.radio_fields
  657. By default, Django's admin uses a select-box interface (<select>) for
  658. fields that are ``ForeignKey`` or have ``choices`` set. If a field is
  659. present in ``radio_fields``, Django will use a radio-button interface
  660. instead. Assuming ``group`` is a ``ForeignKey`` on the ``Person`` model::
  661. class PersonAdmin(admin.ModelAdmin):
  662. radio_fields = {"group": admin.VERTICAL}
  663. You have the choice of using ``HORIZONTAL`` or ``VERTICAL`` from the
  664. ``django.contrib.admin`` module.
  665. Don't include a field in ``radio_fields`` unless it's a ``ForeignKey`` or has
  666. ``choices`` set.
  667. .. attribute:: ModelAdmin.raw_id_fields
  668. By default, Django's admin uses a select-box interface (<select>) for
  669. fields that are ``ForeignKey``. Sometimes you don't want to incur the
  670. overhead of having to select all the related instances to display in the
  671. drop-down.
  672. ``raw_id_fields`` is a list of fields you would like to change
  673. into an ``Input`` widget for either a ``ForeignKey`` or
  674. ``ManyToManyField``::
  675. class ArticleAdmin(admin.ModelAdmin):
  676. raw_id_fields = ("newspaper",)
  677. The ``raw_id_fields`` ``Input`` widget should contain a primary key if the
  678. field is a ``ForeignKey`` or a comma separated list of values if the field
  679. is a ``ManyToManyField``. The ``raw_id_fields`` widget shows a magnifying
  680. glass button next to the field which allows users to search for and select
  681. a value:
  682. .. image:: _images/raw_id_fields.png
  683. .. attribute:: ModelAdmin.readonly_fields
  684. By default the admin shows all fields as editable. Any fields in this
  685. option (which should be a ``list`` or ``tuple``) will display its data
  686. as-is and non-editable; they are also excluded from the
  687. :class:`~django.forms.ModelForm` used for creating and editing. Note that
  688. when specifying :attr:`ModelAdmin.fields` or :attr:`ModelAdmin.fieldsets`
  689. the read-only fields must be present to be shown (they are ignored
  690. otherwise).
  691. If ``readonly_fields`` is used without defining explicit ordering through
  692. :attr:`ModelAdmin.fields` or :attr:`ModelAdmin.fieldsets` they will be
  693. added last after all editable fields.
  694. A read-only field can not only display data from a model's field, it can
  695. also display the output of a model's method or a method of the
  696. ``ModelAdmin`` class itself. This is very similar to the way
  697. :attr:`ModelAdmin.list_display` behaves. This provides an easy way to use
  698. the admin interface to provide feedback on the status of the objects being
  699. edited, for example::
  700. from django.contrib import admin
  701. from django.utils.html import format_html_join
  702. from django.utils.safestring import mark_safe
  703. class PersonAdmin(admin.ModelAdmin):
  704. readonly_fields = ('address_report',)
  705. def address_report(self, instance):
  706. # assuming get_full_address() returns a list of strings
  707. # for each line of the address and you want to separate each
  708. # line by a linebreak
  709. return format_html_join(
  710. mark_safe('<br/>'),
  711. '{0}',
  712. ((line,) for line in instance.get_full_address()),
  713. ) or "<span class='errors'>I can't determine this address.</span>"
  714. # short_description functions like a model field's verbose_name
  715. address_report.short_description = "Address"
  716. # in this example, we have used HTML tags in the output
  717. address_report.allow_tags = True
  718. .. attribute:: ModelAdmin.save_as
  719. Set ``save_as`` to enable a "save as" feature on admin change forms.
  720. Normally, objects have three save options: "Save", "Save and continue
  721. editing" and "Save and add another". If ``save_as`` is ``True``, "Save
  722. and add another" will be replaced by a "Save as" button.
  723. "Save as" means the object will be saved as a new object (with a new ID),
  724. rather than the old object.
  725. By default, ``save_as`` is set to ``False``.
  726. .. attribute:: ModelAdmin.save_on_top
  727. Set ``save_on_top`` to add save buttons across the top of your admin change
  728. forms.
  729. Normally, the save buttons appear only at the bottom of the forms. If you
  730. set ``save_on_top``, the buttons will appear both on the top and the
  731. bottom.
  732. By default, ``save_on_top`` is set to ``False``.
  733. .. attribute:: ModelAdmin.search_fields
  734. Set ``search_fields`` to enable a search box on the admin change list page.
  735. This should be set to a list of field names that will be searched whenever
  736. somebody submits a search query in that text box.
  737. These fields should be some kind of text field, such as ``CharField`` or
  738. ``TextField``. You can also perform a related lookup on a ``ForeignKey`` or
  739. ``ManyToManyField`` with the lookup API "follow" notation::
  740. search_fields = ['foreign_key__related_fieldname']
  741. For example, if you have a blog entry with an author, the following
  742. definition would enable search blog entries by the email address of the
  743. author::
  744. search_fields = ['user__email']
  745. When somebody does a search in the admin search box, Django splits the
  746. search query into words and returns all objects that contain each of the
  747. words, case insensitive, where each word must be in at least one of
  748. ``search_fields``. For example, if ``search_fields`` is set to
  749. ``['first_name', 'last_name']`` and a user searches for ``john lennon``,
  750. Django will do the equivalent of this SQL ``WHERE`` clause::
  751. WHERE (first_name ILIKE '%john%' OR last_name ILIKE '%john%')
  752. AND (first_name ILIKE '%lennon%' OR last_name ILIKE '%lennon%')
  753. For faster and/or more restrictive searches, prefix the field name
  754. with an operator:
  755. ``^``
  756. Matches the beginning of the field. For example, if ``search_fields``
  757. is set to ``['^first_name', '^last_name']`` and a user searches for
  758. ``john lennon``, Django will do the equivalent of this SQL ``WHERE``
  759. clause::
  760. WHERE (first_name ILIKE 'john%' OR last_name ILIKE 'john%')
  761. AND (first_name ILIKE 'lennon%' OR last_name ILIKE 'lennon%')
  762. This query is more efficient than the normal ``'%john%'`` query,
  763. because the database only needs to check the beginning of a column's
  764. data, rather than seeking through the entire column's data. Plus, if
  765. the column has an index on it, some databases may be able to use the
  766. index for this query, even though it's a ``LIKE`` query.
  767. ``=``
  768. Matches exactly, case-insensitive. For example, if
  769. ``search_fields`` is set to ``['=first_name', '=last_name']`` and
  770. a user searches for ``john lennon``, Django will do the equivalent
  771. of this SQL ``WHERE`` clause::
  772. WHERE (first_name ILIKE 'john' OR last_name ILIKE 'john')
  773. AND (first_name ILIKE 'lennon' OR last_name ILIKE 'lennon')
  774. Note that the query input is split by spaces, so, following this
  775. example, it's currently not possible to search for all records in which
  776. ``first_name`` is exactly ``'john winston'`` (containing a space).
  777. ``@``
  778. Performs a full-text match. This is like the default search method but
  779. uses an index. Currently this is only available for MySQL.
  780. If you need to customize search you can use
  781. :meth:`ModelAdmin.get_search_results` to provide additional or alternate
  782. search behavior.
  783. .. attribute:: ModelAdmin.view_on_site
  784. .. versionadded:: 1.7
  785. Set ``view_on_site`` to control whether or not to display the "View on site" link.
  786. This link should bring you to a URL where you can display the saved object.
  787. This value can be either a boolean flag or a callable. If ``True`` (the
  788. default), the object's :meth:`~django.db.models.Model.get_absolute_url`
  789. method will be used to generate the url.
  790. If your model has a :meth:`~django.db.models.Model.get_absolute_url` method
  791. but you don't want the "View on site" button to appear, you only need to set
  792. ``view_on_site`` to ``False``::
  793. from django.contrib import admin
  794. class PersonAdmin(admin.ModelAdmin):
  795. view_on_site = False
  796. In case it is a callable, it accepts the model instance as a parameter.
  797. For example::
  798. from django.contrib import admin
  799. from django.core.urlresolvers import reverse
  800. class PersonAdmin(admin.ModelAdmin):
  801. def view_on_site(self, obj):
  802. return 'http://example.com' + reverse('person-detail',
  803. kwargs={'slug': obj.slug})
  804. Custom template options
  805. ~~~~~~~~~~~~~~~~~~~~~~~
  806. The `Overriding Admin Templates`_ section describes how to override or extend
  807. the default admin templates. Use the following options to override the default
  808. templates used by the :class:`ModelAdmin` views:
  809. .. attribute:: ModelAdmin.add_form_template
  810. Path to a custom template, used by :meth:`add_view`.
  811. .. attribute:: ModelAdmin.change_form_template
  812. Path to a custom template, used by :meth:`change_view`.
  813. .. attribute:: ModelAdmin.change_list_template
  814. Path to a custom template, used by :meth:`changelist_view`.
  815. .. attribute:: ModelAdmin.delete_confirmation_template
  816. Path to a custom template, used by :meth:`delete_view` for displaying a
  817. confirmation page when deleting one or more objects.
  818. .. attribute:: ModelAdmin.delete_selected_confirmation_template
  819. Path to a custom template, used by the ``delete_selected`` action method
  820. for displaying a confirmation page when deleting one or more objects. See
  821. the :doc:`actions documentation</ref/contrib/admin/actions>`.
  822. .. attribute:: ModelAdmin.object_history_template
  823. Path to a custom template, used by :meth:`history_view`.
  824. .. _model-admin-methods:
  825. ``ModelAdmin`` methods
  826. ----------------------
  827. .. warning::
  828. :meth:`ModelAdmin.save_model` and :meth:`ModelAdmin.delete_model` must
  829. save/delete the object, they are not for veto purposes, rather they allow
  830. you to perform extra operations.
  831. .. method:: ModelAdmin.save_model(self, request, obj, form, change)
  832. The ``save_model`` method is given the ``HttpRequest``, a model instance,
  833. a ``ModelForm`` instance and a boolean value based on whether it is adding
  834. or changing the object. Here you can do any pre- or post-save operations.
  835. For example to attach ``request.user`` to the object prior to saving::
  836. from django.contrib import admin
  837. class ArticleAdmin(admin.ModelAdmin):
  838. def save_model(self, request, obj, form, change):
  839. obj.user = request.user
  840. obj.save()
  841. .. method:: ModelAdmin.delete_model(self, request, obj)
  842. The ``delete_model`` method is given the ``HttpRequest`` and a model
  843. instance. Use this method to do pre- or post-delete operations.
  844. .. method:: ModelAdmin.save_formset(self, request, form, formset, change)
  845. The ``save_formset`` method is given the ``HttpRequest``, the parent
  846. ``ModelForm`` instance and a boolean value based on whether it is adding or
  847. changing the parent object.
  848. For example to attach ``request.user`` to each changed formset
  849. model instance::
  850. class ArticleAdmin(admin.ModelAdmin):
  851. def save_formset(self, request, form, formset, change):
  852. instances = formset.save(commit=False)
  853. for instance in instances:
  854. instance.user = request.user
  855. instance.save()
  856. formset.save_m2m()
  857. .. method:: ModelAdmin.get_ordering(self, request)
  858. The ``get_ordering`` method takes a``request`` as parameter and
  859. is expected to return a ``list`` or ``tuple`` for ordering similar
  860. to the :attr:`ordering` attribute. For example::
  861. class PersonAdmin(admin.ModelAdmin):
  862. def get_ordering(self, request):
  863. if request.user.is_superuser:
  864. return ['name', 'rank']
  865. else:
  866. return ['name']
  867. .. method:: ModelAdmin.get_search_results(self, request, queryset, search_term)
  868. .. versionadded:: 1.6
  869. The ``get_search_results`` method modifies the list of objects displayed in
  870. to those that match the provided search term. It accepts the request, a
  871. queryset that applies the current filters, and the user-provided search term.
  872. It returns a tuple containing a queryset modified to implement the search, and
  873. a boolean indicating if the results may contain duplicates.
  874. The default implementation searches the fields named in :attr:`ModelAdmin.search_fields`.
  875. This method may be overridden with your own custom search method. For
  876. example, you might wish to search by an integer field, or use an external
  877. tool such as Solr or Haystack. You must establish if the queryset changes
  878. implemented by your search method may introduce duplicates into the results,
  879. and return ``True`` in the second element of the return value.
  880. For example, to enable search by integer field, you could use::
  881. class PersonAdmin(admin.ModelAdmin):
  882. list_display = ('name', 'age')
  883. search_fields = ('name',)
  884. def get_search_results(self, request, queryset, search_term):
  885. queryset, use_distinct = super(PersonAdmin, self).get_search_results(request, queryset, search_term)
  886. try:
  887. search_term_as_int = int(search_term)
  888. queryset |= self.model.objects.filter(age=search_term_as_int)
  889. except:
  890. pass
  891. return queryset, use_distinct
  892. .. method:: ModelAdmin.save_related(self, request, form, formsets, change)
  893. The ``save_related`` method is given the ``HttpRequest``, the parent
  894. ``ModelForm`` instance, the list of inline formsets and a boolean value
  895. based on whether the parent is being added or changed. Here you can do any
  896. pre- or post-save operations for objects related to the parent. Note
  897. that at this point the parent object and its form have already been saved.
  898. .. method:: ModelAdmin.get_readonly_fields(self, request, obj=None)
  899. The ``get_readonly_fields`` method is given the ``HttpRequest`` and the
  900. ``obj`` being edited (or ``None`` on an add form) and is expected to return
  901. a ``list`` or ``tuple`` of field names that will be displayed as read-only,
  902. as described above in the :attr:`ModelAdmin.readonly_fields` section.
  903. .. method:: ModelAdmin.get_prepopulated_fields(self, request, obj=None)
  904. The ``get_prepopulated_fields`` method is given the ``HttpRequest`` and the
  905. ``obj`` being edited (or ``None`` on an add form) and is expected to return
  906. a ``dictionary``, as described above in the :attr:`ModelAdmin.prepopulated_fields`
  907. section.
  908. .. method:: ModelAdmin.get_list_display(self, request)
  909. The ``get_list_display`` method is given the ``HttpRequest`` and is
  910. expected to return a ``list`` or ``tuple`` of field names that will be
  911. displayed on the changelist view as described above in the
  912. :attr:`ModelAdmin.list_display` section.
  913. .. method:: ModelAdmin.get_list_display_links(self, request, list_display)
  914. The ``get_list_display_links`` method is given the ``HttpRequest`` and
  915. the ``list`` or ``tuple`` returned by :meth:`ModelAdmin.get_list_display`.
  916. It is expected to return either ``None`` or a ``list`` or ``tuple`` of field
  917. names on the changelist that will be linked to the change view, as described
  918. in the :attr:`ModelAdmin.list_display_links` section.
  919. .. versionchanged:: 1.7
  920. ``None`` was added as a valid ``get_list_display_links()`` return value.
  921. .. method:: ModelAdmin.get_fields(self, request, obj=None)
  922. .. versionadded:: 1.7
  923. The ``get_fields`` method is given the ``HttpRequest`` and the ``obj``
  924. being edited (or ``None`` on an add form) and is expected to return a list
  925. of fields, as described above in the :attr:`ModelAdmin.fields` section.
  926. .. method:: ModelAdmin.get_fieldsets(self, request, obj=None)
  927. The ``get_fieldsets`` method is given the ``HttpRequest`` and the ``obj``
  928. being edited (or ``None`` on an add form) and is expected to return a list
  929. of two-tuples, in which each two-tuple represents a ``<fieldset>`` on the
  930. admin form page, as described above in the :attr:`ModelAdmin.fieldsets` section.
  931. .. method:: ModelAdmin.get_list_filter(self, request)
  932. The ``get_list_filter`` method is given the ``HttpRequest`` and is expected
  933. to return the same kind of sequence type as for the
  934. :attr:`~ModelAdmin.list_filter` attribute.
  935. .. method:: ModelAdmin.get_search_fields(self, request)
  936. .. versionadded:: 1.7
  937. The ``get_search_fields`` method is given the ``HttpRequest`` and is expected
  938. to return the same kind of sequence type as for the
  939. :attr:`~ModelAdmin.search_fields` attribute.
  940. .. method:: ModelAdmin.get_inline_instances(self, request, obj=None)
  941. The ``get_inline_instances`` method is given the ``HttpRequest`` and the
  942. ``obj`` being edited (or ``None`` on an add form) and is expected to return
  943. a ``list`` or ``tuple`` of :class:`~django.contrib.admin.InlineModelAdmin`
  944. objects, as described below in the :class:`~django.contrib.admin.InlineModelAdmin`
  945. section.
  946. .. method:: ModelAdmin.get_urls(self)
  947. The ``get_urls`` method on a ``ModelAdmin`` returns the URLs to be used for
  948. that ModelAdmin in the same way as a URLconf. Therefore you can extend
  949. them as documented in :doc:`/topics/http/urls`::
  950. class MyModelAdmin(admin.ModelAdmin):
  951. def get_urls(self):
  952. urls = super(MyModelAdmin, self).get_urls()
  953. my_urls = patterns('',
  954. (r'^my_view/$', self.my_view)
  955. )
  956. return my_urls + urls
  957. def my_view(self, request):
  958. # custom view which should return an HttpResponse
  959. pass
  960. .. note::
  961. Notice that the custom patterns are included *before* the regular admin
  962. URLs: the admin URL patterns are very permissive and will match nearly
  963. anything, so you'll usually want to prepend your custom URLs to the
  964. built-in ones.
  965. In this example, ``my_view`` will be accessed at
  966. ``/admin/myapp/mymodel/my_view/`` (assuming the admin URLs are included
  967. at ``/admin/``.)
  968. However, the ``self.my_view`` function registered above suffers from two
  969. problems:
  970. * It will *not* perform any permission checks, so it will be accessible
  971. to the general public.
  972. * It will *not* provide any header details to prevent caching. This means
  973. if the page retrieves data from the database, and caching middleware is
  974. active, the page could show outdated information.
  975. Since this is usually not what you want, Django provides a convenience
  976. wrapper to check permissions and mark the view as non-cacheable. This
  977. wrapper is ``AdminSite.admin_view()`` (i.e. ``self.admin_site.admin_view``
  978. inside a ``ModelAdmin`` instance); use it like so::
  979. class MyModelAdmin(admin.ModelAdmin):
  980. def get_urls(self):
  981. urls = super(MyModelAdmin, self).get_urls()
  982. my_urls = patterns('',
  983. (r'^my_view/$', self.admin_site.admin_view(self.my_view))
  984. )
  985. return my_urls + urls
  986. Notice the wrapped view in the fifth line above::
  987. (r'^my_view/$', self.admin_site.admin_view(self.my_view))
  988. This wrapping will protect ``self.my_view`` from unauthorized access and
  989. will apply the ``django.views.decorators.cache.never_cache`` decorator to
  990. make sure it is not cached if the cache middleware is active.
  991. If the page is cacheable, but you still want the permission check to be
  992. performed, you can pass a ``cacheable=True`` argument to
  993. ``AdminSite.admin_view()``::
  994. (r'^my_view/$', self.admin_site.admin_view(self.my_view, cacheable=True))
  995. .. method:: ModelAdmin.get_form(self, request, obj=None, **kwargs)
  996. Returns a :class:`~django.forms.ModelForm` class for use in the admin add
  997. and change views, see :meth:`add_view` and :meth:`change_view`.
  998. If you wanted to hide a field from non-superusers, for example, you could
  999. override ``get_form`` as follows::
  1000. class MyModelAdmin(admin.ModelAdmin):
  1001. def get_form(self, request, obj=None, **kwargs):
  1002. self.exclude = []
  1003. if not request.user.is_superuser:
  1004. self.exclude.append('field_to_hide')
  1005. return super(MyModelAdmin, self).get_form(request, obj, **kwargs)
  1006. .. method:: ModelAdmin.get_formsets(self, request, obj=None)
  1007. .. deprecated:: 1.7
  1008. Use :meth:`get_formsets_with_inlines()` instead.
  1009. Yields :class:`InlineModelAdmin`\s for use in admin add and change views.
  1010. For example if you wanted to display a particular inline only in the change
  1011. view, you could override ``get_formsets`` as follows::
  1012. class MyModelAdmin(admin.ModelAdmin):
  1013. inlines = [MyInline, SomeOtherInline]
  1014. def get_formsets(self, request, obj=None):
  1015. for inline in self.get_inline_instances(request, obj):
  1016. # hide MyInline in the add view
  1017. if isinstance(inline, MyInline) and obj is None:
  1018. continue
  1019. yield inline.get_formset(request, obj)
  1020. .. method:: ModelAdmin.get_formsets_with_inlines(self, request, obj=None)
  1021. Yields (``FormSet``, :class:`InlineModelAdmin`) pairs for use in admin add
  1022. and change views.
  1023. For example if you wanted to display a particular inline only in the change
  1024. view, you could override ``get_formsets_with_inlines`` as follows::
  1025. class MyModelAdmin(admin.ModelAdmin):
  1026. inlines = [MyInline, SomeOtherInline]
  1027. def get_formsets_with_inlines(self, request, obj=None):
  1028. for inline in self.get_inline_instances(request, obj):
  1029. # hide MyInline in the add view
  1030. if isinstance(inline, MyInline) and obj is None:
  1031. continue
  1032. yield inline.get_formset(request, obj), inline
  1033. .. method:: ModelAdmin.formfield_for_foreignkey(self, db_field, request, **kwargs)
  1034. The ``formfield_for_foreignkey`` method on a ``ModelAdmin`` allows you to
  1035. override the default formfield for a foreign keys field. For example, to
  1036. return a subset of objects for this foreign key field based on the user::
  1037. class MyModelAdmin(admin.ModelAdmin):
  1038. def formfield_for_foreignkey(self, db_field, request, **kwargs):
  1039. if db_field.name == "car":
  1040. kwargs["queryset"] = Car.objects.filter(owner=request.user)
  1041. return super(MyModelAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
  1042. This uses the ``HttpRequest`` instance to filter the ``Car`` foreign key
  1043. field to only display the cars owned by the ``User`` instance.
  1044. .. method:: ModelAdmin.formfield_for_manytomany(self, db_field, request, **kwargs)
  1045. Like the ``formfield_for_foreignkey`` method, the
  1046. ``formfield_for_manytomany`` method can be overridden to change the
  1047. default formfield for a many to many field. For example, if an owner can
  1048. own multiple cars and cars can belong to multiple owners -- a many to
  1049. many relationship -- you could filter the ``Car`` foreign key field to
  1050. only display the cars owned by the ``User``::
  1051. class MyModelAdmin(admin.ModelAdmin):
  1052. def formfield_for_manytomany(self, db_field, request, **kwargs):
  1053. if db_field.name == "cars":
  1054. kwargs["queryset"] = Car.objects.filter(owner=request.user)
  1055. return super(MyModelAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)
  1056. .. method:: ModelAdmin.formfield_for_choice_field(self, db_field, request, **kwargs)
  1057. Like the ``formfield_for_foreignkey`` and ``formfield_for_manytomany``
  1058. methods, the ``formfield_for_choice_field`` method can be overridden to
  1059. change the default formfield for a field that has declared choices. For
  1060. example, if the choices available to a superuser should be different than
  1061. those available to regular staff, you could proceed as follows::
  1062. class MyModelAdmin(admin.ModelAdmin):
  1063. def formfield_for_choice_field(self, db_field, request, **kwargs):
  1064. if db_field.name == "status":
  1065. kwargs['choices'] = (
  1066. ('accepted', 'Accepted'),
  1067. ('denied', 'Denied'),
  1068. )
  1069. if request.user.is_superuser:
  1070. kwargs['choices'] += (('ready', 'Ready for deployment'),)
  1071. return super(MyModelAdmin, self).formfield_for_choice_field(db_field, request, **kwargs)
  1072. .. admonition:: Note
  1073. Any ``choices`` attribute set on the formfield will limited to the form
  1074. field only. If the corresponding field on the model has choices set,
  1075. the choices provided to the form must be a valid subset of those
  1076. choices, otherwise the form submission will fail with
  1077. a :exc:`~django.core.exceptions.ValidationError` when the model itself
  1078. is validated before saving.
  1079. .. method:: ModelAdmin.get_changelist(self, request, **kwargs)
  1080. Returns the ``Changelist`` class to be used for listing. By default,
  1081. ``django.contrib.admin.views.main.ChangeList`` is used. By inheriting this
  1082. class you can change the behavior of the listing.
  1083. .. method:: ModelAdmin.get_changelist_form(self, request, **kwargs)
  1084. Returns a :class:`~django.forms.ModelForm` class for use in the ``Formset``
  1085. on the changelist page. To use a custom form, for example::
  1086. from django import forms
  1087. class MyForm(forms.ModelForm):
  1088. pass
  1089. class MyModelAdmin(admin.ModelAdmin):
  1090. def get_changelist_form(self, request, **kwargs):
  1091. return MyForm
  1092. .. admonition:: Note
  1093. .. versionchanged:: 1.6
  1094. If you define the ``Meta.model`` attribute on a
  1095. :class:`~django.forms.ModelForm`, you must also define the
  1096. ``Meta.fields`` attribute (or the ``Meta.exclude`` attribute). However,
  1097. ``ModelAdmin`` ignores this value, overriding it with the
  1098. :attr:`ModelAdmin.list_editable` attribute. The easiest solution is to
  1099. omit the ``Meta.model`` attribute, since ``ModelAdmin`` will provide the
  1100. correct model to use.
  1101. .. method:: ModelAdmin.get_changelist_formset(self, request, **kwargs)
  1102. Returns a :ref:`ModelFormSet <model-formsets>` class for use on the
  1103. changelist page if :attr:`~ModelAdmin.list_editable` is used. To use a
  1104. custom formset, for example::
  1105. from django.forms.models import BaseModelFormSet
  1106. class MyAdminFormSet(BaseModelFormSet):
  1107. pass
  1108. class MyModelAdmin(admin.ModelAdmin):
  1109. def get_changelist_formset(self, request, **kwargs):
  1110. kwargs['formset'] = MyAdminFormSet
  1111. return super(MyModelAdmin, self).get_changelist_formset(request, **kwargs)
  1112. .. method:: ModelAdmin.has_add_permission(self, request)
  1113. Should return ``True`` if adding an object is permitted, ``False``
  1114. otherwise.
  1115. .. method:: ModelAdmin.has_change_permission(self, request, obj=None)
  1116. Should return ``True`` if editing obj is permitted, ``False`` otherwise.
  1117. If obj is ``None``, should return ``True`` or ``False`` to indicate whether
  1118. editing of objects of this type is permitted in general (e.g., ``False``
  1119. will be interpreted as meaning that the current user is not permitted to
  1120. edit any object of this type).
  1121. .. method:: ModelAdmin.has_delete_permission(self, request, obj=None)
  1122. Should return ``True`` if deleting obj is permitted, ``False`` otherwise.
  1123. If obj is ``None``, should return ``True`` or ``False`` to indicate whether
  1124. deleting objects of this type is permitted in general (e.g., ``False`` will
  1125. be interpreted as meaning that the current user is not permitted to delete
  1126. any object of this type).
  1127. .. method:: ModelAdmin.get_queryset(self, request)
  1128. The ``get_queryset`` method on a ``ModelAdmin`` returns a
  1129. :class:`~django.db.models.query.QuerySet` of all model instances that
  1130. can be edited by the admin site. One use case for overriding this method
  1131. is to show objects owned by the logged-in user::
  1132. class MyModelAdmin(admin.ModelAdmin):
  1133. def get_queryset(self, request):
  1134. qs = super(MyModelAdmin, self).get_queryset(request)
  1135. if request.user.is_superuser:
  1136. return qs
  1137. return qs.filter(author=request.user)
  1138. .. versionchanged:: 1.6
  1139. The ``get_queryset`` method was previously named ``queryset``.
  1140. .. method:: ModelAdmin.message_user(request, message, level=messages.INFO, extra_tags='', fail_silently=False)
  1141. Sends a message to the user using the :mod:`django.contrib.messages`
  1142. backend. See the :ref:`custom ModelAdmin example <custom-admin-action>`.
  1143. Keyword arguments allow you to change the message level, add extra CSS
  1144. tags, or fail silently if the ``contrib.messages`` framework is not
  1145. installed. These keyword arguments match those for
  1146. :func:`django.contrib.messages.add_message`, see that function's
  1147. documentation for more details. One difference is that the level may be
  1148. passed as a string label in addition to integer/constant.
  1149. .. method:: ModelAdmin.get_paginator(queryset, per_page, orphans=0, allow_empty_first_page=True)
  1150. Returns an instance of the paginator to use for this view. By default,
  1151. instantiates an instance of :attr:`paginator`.
  1152. .. method:: ModelAdmin.response_add(self, request, obj, post_url_continue=None)
  1153. Determines the :class:`~django.http.HttpResponse` for the
  1154. :meth:`add_view` stage.
  1155. ``response_add`` is called after the admin form is submitted and
  1156. just after the object and all the related instances have
  1157. been created and saved. You can override it to change the default behavior
  1158. after the object has been created.
  1159. .. method:: ModelAdmin.response_change(self, request, obj)
  1160. Determines the :class:`~django.http.HttpResponse` for the
  1161. :meth:`change_view` stage.
  1162. ``response_change`` is called after the admin form is submitted and
  1163. just after the object and all the related instances have
  1164. been saved. You can override it to change the default
  1165. behavior after the object has been changedn.
  1166. .. method:: ModelAdmin.response_delete(self, request, obj_display)
  1167. .. versionadded:: 1.7
  1168. Determines the :class:`~django.http.HttpResponse` for the
  1169. :meth:`delete_view` stage.
  1170. ``response_delete`` is called after the object has been
  1171. deleted. You can override it to change the default
  1172. behavior after the object has been deleted.
  1173. ``obj_display`` is a string with the name of the deleted
  1174. object.
  1175. Other methods
  1176. ~~~~~~~~~~~~~
  1177. .. method:: ModelAdmin.add_view(self, request, form_url='', extra_context=None)
  1178. Django view for the model instance addition page. See note below.
  1179. .. method:: ModelAdmin.change_view(self, request, object_id, form_url='', extra_context=None)
  1180. Django view for the model instance edition page. See note below.
  1181. .. method:: ModelAdmin.changelist_view(self, request, extra_context=None)
  1182. Django view for the model instances change list/actions page. See note
  1183. below.
  1184. .. method:: ModelAdmin.delete_view(self, request, object_id, extra_context=None)
  1185. Django view for the model instance(s) deletion confirmation page. See note
  1186. below.
  1187. .. method:: ModelAdmin.history_view(self, request, object_id, extra_context=None)
  1188. Django view for the page that shows the modification history for a given
  1189. model instance.
  1190. Unlike the hook-type ``ModelAdmin`` methods detailed in the previous section,
  1191. these five methods are in reality designed to be invoked as Django views from
  1192. the admin application URL dispatching handler to render the pages that deal
  1193. with model instances CRUD operations. As a result, completely overriding these
  1194. methods will significantly change the behavior of the admin application.
  1195. One common reason for overriding these methods is to augment the context data
  1196. that is provided to the template that renders the view. In the following
  1197. example, the change view is overridden so that the rendered template is
  1198. provided some extra mapping data that would not otherwise be available::
  1199. class MyModelAdmin(admin.ModelAdmin):
  1200. # A template for a very customized change view:
  1201. change_form_template = 'admin/myapp/extras/openstreetmap_change_form.html'
  1202. def get_osm_info(self):
  1203. # ...
  1204. pass
  1205. def change_view(self, request, object_id, form_url='', extra_context=None):
  1206. extra_context = extra_context or {}
  1207. extra_context['osm_data'] = self.get_osm_info()
  1208. return super(MyModelAdmin, self).change_view(request, object_id,
  1209. form_url, extra_context=extra_context)
  1210. These views return :class:`~django.template.response.TemplateResponse`
  1211. instances which allow you to easily customize the response data before
  1212. rendering. For more details, see the :doc:`TemplateResponse documentation
  1213. </ref/template-response>`.
  1214. .. _modeladmin-asset-definitions:
  1215. ``ModelAdmin`` asset definitions
  1216. --------------------------------
  1217. There are times where you would like add a bit of CSS and/or JavaScript to
  1218. the add/change views. This can be accomplished by using a ``Media`` inner class
  1219. on your ``ModelAdmin``::
  1220. class ArticleAdmin(admin.ModelAdmin):
  1221. class Media:
  1222. css = {
  1223. "all": ("my_styles.css",)
  1224. }
  1225. js = ("my_code.js",)
  1226. The :doc:`staticfiles app </ref/contrib/staticfiles>` prepends
  1227. :setting:`STATIC_URL` (or :setting:`MEDIA_URL` if :setting:`STATIC_URL` is
  1228. ``None``) to any asset paths. The same rules apply as :ref:`regular asset
  1229. definitions on forms <form-asset-paths>`.
  1230. jQuery
  1231. ~~~~~~
  1232. Django admin Javascript makes use of the `jQuery`_ library.
  1233. To avoid conflicts with user-supplied scripts or libraries, Django's jQuery
  1234. (version 1.9.1) is namespaced as ``django.jQuery``. If you want to use jQuery
  1235. in your own admin JavaScript without including a second copy, you can use the
  1236. ``django.jQuery`` object on changelist and add/edit views.
  1237. .. versionchanged:: 1.6
  1238. The embedded jQuery has been upgraded from 1.4.2 to 1.9.1.
  1239. The :class:`ModelAdmin` class requires jQuery by default, so there is no need
  1240. to add jQuery to your ``ModelAdmin``’s list of media resources unless you have
  1241. a specifc need. For example, if you require the jQuery library to be in the
  1242. global namespace (for example when using third-party jQuery plugins) or if you
  1243. need a newer version of jQuery, you will have to include your own copy.
  1244. Django provides both uncompressed and 'minified' versions of jQuery, as
  1245. ``jquery.js`` and ``jquery.min.js`` respectively.
  1246. :class:`ModelAdmin` and :class:`InlineModelAdmin` have a ``media`` property
  1247. that returns a list of ``Media`` objects which store paths to the JavaScript
  1248. files for the forms and/or formsets. If :setting:`DEBUG` is ``True`` it will
  1249. return the uncompressed versions of the various JavaScript files, including
  1250. ``jquery.js``; if not, it will return the 'minified' versions.
  1251. .. _jQuery: http://jquery.com
  1252. Adding custom validation to the admin
  1253. -------------------------------------
  1254. Adding custom validation of data in the admin is quite easy. The automatic
  1255. admin interface reuses :mod:`django.forms`, and the ``ModelAdmin`` class gives
  1256. you the ability define your own form::
  1257. class ArticleAdmin(admin.ModelAdmin):
  1258. form = MyArticleAdminForm
  1259. ``MyArticleAdminForm`` can be defined anywhere as long as you import where
  1260. needed. Now within your form you can add your own custom validation for
  1261. any field::
  1262. class MyArticleAdminForm(forms.ModelForm):
  1263. def clean_name(self):
  1264. # do something that validates your data
  1265. return self.cleaned_data["name"]
  1266. It is important you use a ``ModelForm`` here otherwise things can break. See
  1267. the :doc:`forms </ref/forms/index>` documentation on :doc:`custom validation
  1268. </ref/forms/validation>` and, more specifically, the
  1269. :ref:`model form validation notes <overriding-modelform-clean-method>` for more
  1270. information.
  1271. .. _admin-inlines:
  1272. ``InlineModelAdmin`` objects
  1273. ============================
  1274. .. class:: InlineModelAdmin
  1275. .. class:: TabularInline
  1276. .. class:: StackedInline
  1277. The admin interface has the ability to edit models on the same page as a
  1278. parent model. These are called inlines. Suppose you have these two models::
  1279. from django.db import models
  1280. class Author(models.Model):
  1281. name = models.CharField(max_length=100)
  1282. class Book(models.Model):
  1283. author = models.ForeignKey(Author)
  1284. title = models.CharField(max_length=100)
  1285. You can edit the books authored by an author on the author page. You add
  1286. inlines to a model by specifying them in a ``ModelAdmin.inlines``::
  1287. from django.contrib import admin
  1288. class BookInline(admin.TabularInline):
  1289. model = Book
  1290. class AuthorAdmin(admin.ModelAdmin):
  1291. inlines = [
  1292. BookInline,
  1293. ]
  1294. Django provides two subclasses of ``InlineModelAdmin`` and they are:
  1295. * :class:`~django.contrib.admin.TabularInline`
  1296. * :class:`~django.contrib.admin.StackedInline`
  1297. The difference between these two is merely the template used to render
  1298. them.
  1299. ``InlineModelAdmin`` options
  1300. -----------------------------
  1301. ``InlineModelAdmin`` shares many of the same features as ``ModelAdmin``, and
  1302. adds some of its own (the shared features are actually defined in the
  1303. ``BaseModelAdmin`` superclass). The shared features are:
  1304. - :attr:`~InlineModelAdmin.form`
  1305. - :attr:`~ModelAdmin.fieldsets`
  1306. - :attr:`~ModelAdmin.fields`
  1307. - :attr:`~ModelAdmin.formfield_overrides`
  1308. - :attr:`~ModelAdmin.exclude`
  1309. - :attr:`~ModelAdmin.filter_horizontal`
  1310. - :attr:`~ModelAdmin.filter_vertical`
  1311. - :attr:`~ModelAdmin.ordering`
  1312. - :attr:`~ModelAdmin.prepopulated_fields`
  1313. - :meth:`~ModelAdmin.get_queryset`
  1314. - :attr:`~ModelAdmin.radio_fields`
  1315. - :attr:`~ModelAdmin.readonly_fields`
  1316. - :attr:`~InlineModelAdmin.raw_id_fields`
  1317. - :meth:`~ModelAdmin.formfield_for_foreignkey`
  1318. - :meth:`~ModelAdmin.formfield_for_manytomany`
  1319. - :meth:`~ModelAdmin.has_add_permission`
  1320. - :meth:`~ModelAdmin.has_change_permission`
  1321. - :meth:`~ModelAdmin.has_delete_permission`
  1322. The ``InlineModelAdmin`` class adds:
  1323. .. attribute:: InlineModelAdmin.model
  1324. The model which the inline is using. This is required.
  1325. .. attribute:: InlineModelAdmin.fk_name
  1326. The name of the foreign key on the model. In most cases this will be dealt
  1327. with automatically, but ``fk_name`` must be specified explicitly if there
  1328. are more than one foreign key to the same parent model.
  1329. .. attribute:: InlineModelAdmin.formset
  1330. This defaults to :class:`~django.forms.models.BaseInlineFormSet`. Using
  1331. your own formset can give you many possibilities of customization. Inlines
  1332. are built around :ref:`model formsets <model-formsets>`.
  1333. .. attribute:: InlineModelAdmin.form
  1334. The value for ``form`` defaults to ``ModelForm``. This is what is passed
  1335. through to :func:`~django.forms.models.inlineformset_factory` when
  1336. creating the formset for this inline.
  1337. .. attribute:: InlineModelAdmin.extra
  1338. This controls the number of extra forms the formset will display in
  1339. addition to the initial forms. See the
  1340. :doc:`formsets documentation </topics/forms/formsets>` for more
  1341. information.
  1342. For users with JavaScript-enabled browsers, an "Add another" link is
  1343. provided to enable any number of additional inlines to be added in addition
  1344. to those provided as a result of the ``extra`` argument.
  1345. The dynamic link will not appear if the number of currently displayed forms
  1346. exceeds ``max_num``, or if the user does not have JavaScript enabled.
  1347. .. versionadded:: 1.6
  1348. :meth:`InlineModelAdmin.get_extra` also allows you to customize the number
  1349. of extra forms.
  1350. .. _ref-contrib-admin-inline-max-num:
  1351. .. attribute:: InlineModelAdmin.max_num
  1352. This controls the maximum number of forms to show in the inline. This
  1353. doesn't directly correlate to the number of objects, but can if the value
  1354. is small enough. See :ref:`model-formsets-max-num` for more information.
  1355. .. versionadded:: 1.6
  1356. :meth:`InlineModelAdmin.get_max_num` also allows you to customize the
  1357. maximum number of extra forms.
  1358. .. attribute:: InlineModelAdmin.raw_id_fields
  1359. By default, Django's admin uses a select-box interface (<select>) for
  1360. fields that are ``ForeignKey``. Sometimes you don't want to incur the
  1361. overhead of having to select all the related instances to display in the
  1362. drop-down.
  1363. ``raw_id_fields`` is a list of fields you would like to change into a
  1364. ``Input`` widget for either a ``ForeignKey`` or ``ManyToManyField``::
  1365. class BookInline(admin.TabularInline):
  1366. model = Book
  1367. raw_id_fields = ("pages",)
  1368. .. attribute:: InlineModelAdmin.template
  1369. The template used to render the inline on the page.
  1370. .. attribute:: InlineModelAdmin.verbose_name
  1371. An override to the ``verbose_name`` found in the model's inner ``Meta``
  1372. class.
  1373. .. attribute:: InlineModelAdmin.verbose_name_plural
  1374. An override to the ``verbose_name_plural`` found in the model's inner
  1375. ``Meta`` class.
  1376. .. attribute:: InlineModelAdmin.can_delete
  1377. Specifies whether or not inline objects can be deleted in the inline.
  1378. Defaults to ``True``.
  1379. .. method:: InlineModelAdmin.get_formset(self, request, obj=None, **kwargs)
  1380. Returns a :class:`~django.forms.models.BaseInlineFormSet` class for use in
  1381. admin add/change views. See the example for
  1382. :class:`ModelAdmin.get_formsets`.
  1383. .. method:: InlineModelAdmin.get_extra(self, request, obj=None, **kwargs)
  1384. .. versionadded:: 1.6
  1385. Returns the number of extra inline forms to use. By default, returns the
  1386. :attr:`InlineModelAdmin.extra` attribute.
  1387. Override this method to programmatically determine the number of extra
  1388. inline forms. For example, this may be based on the model instance
  1389. (passed as the keyword argument ``obj``)::
  1390. class BinaryTreeAdmin(admin.TabularInline):
  1391. model = BinaryTree
  1392. def get_extra(self, request, obj=None, **kwargs):
  1393. extra = 2
  1394. if obj:
  1395. return extra - obj.binarytree_set.count()
  1396. return extra
  1397. .. method:: InlineModelAdmin.get_max_num(self, request, obj=None, **kwargs)
  1398. .. versionadded:: 1.6
  1399. Returns the maximum number of extra inline forms to use. By default,
  1400. returns the :attr:`InlineModelAdmin.max_num` attribute.
  1401. Override this method to programmatically determine the maximum number of
  1402. inline forms. For example, this may be based on the model instance
  1403. (passed as the keyword argument ``obj``)::
  1404. class BinaryTreeAdmin(admin.TabularInline):
  1405. model = BinaryTree
  1406. def get_max_num(self, request, obj=None, **kwargs):
  1407. max_num = 10
  1408. if obj.parent:
  1409. return max_num - 5
  1410. return max_num
  1411. Working with a model with two or more foreign keys to the same parent model
  1412. ---------------------------------------------------------------------------
  1413. It is sometimes possible to have more than one foreign key to the same model.
  1414. Take this model for instance::
  1415. from django.db import models
  1416. class Friendship(models.Model):
  1417. to_person = models.ForeignKey(Person, related_name="friends")
  1418. from_person = models.ForeignKey(Person, related_name="from_friends")
  1419. If you wanted to display an inline on the ``Person`` admin add/change pages
  1420. you need to explicitly define the foreign key since it is unable to do so
  1421. automatically::
  1422. from django.contrib import admin
  1423. from myapp.models import Friendship
  1424. class FriendshipInline(admin.TabularInline):
  1425. model = Friendship
  1426. fk_name = "to_person"
  1427. class PersonAdmin(admin.ModelAdmin):
  1428. inlines = [
  1429. FriendshipInline,
  1430. ]
  1431. Working with many-to-many models
  1432. --------------------------------
  1433. By default, admin widgets for many-to-many relations will be displayed
  1434. on whichever model contains the actual reference to the
  1435. :class:`~django.db.models.ManyToManyField`. Depending on your ``ModelAdmin``
  1436. definition, each many-to-many field in your model will be represented by a
  1437. standard HTML ``<select multiple>``, a horizontal or vertical filter, or a
  1438. ``raw_id_admin`` widget. However, it is also possible to replace these
  1439. widgets with inlines.
  1440. Suppose we have the following models::
  1441. from django.db import models
  1442. class Person(models.Model):
  1443. name = models.CharField(max_length=128)
  1444. class Group(models.Model):
  1445. name = models.CharField(max_length=128)
  1446. members = models.ManyToManyField(Person, related_name='groups')
  1447. If you want to display many-to-many relations using an inline, you can do
  1448. so by defining an ``InlineModelAdmin`` object for the relationship::
  1449. from django.contrib import admin
  1450. class MembershipInline(admin.TabularInline):
  1451. model = Group.members.through
  1452. class PersonAdmin(admin.ModelAdmin):
  1453. inlines = [
  1454. MembershipInline,
  1455. ]
  1456. class GroupAdmin(admin.ModelAdmin):
  1457. inlines = [
  1458. MembershipInline,
  1459. ]
  1460. exclude = ('members',)
  1461. There are two features worth noting in this example.
  1462. Firstly - the ``MembershipInline`` class references ``Group.members.through``.
  1463. The ``through`` attribute is a reference to the model that manages the
  1464. many-to-many relation. This model is automatically created by Django when you
  1465. define a many-to-many field.
  1466. Secondly, the ``GroupAdmin`` must manually exclude the ``members`` field.
  1467. Django displays an admin widget for a many-to-many field on the model that
  1468. defines the relation (in this case, ``Group``). If you want to use an inline
  1469. model to represent the many-to-many relationship, you must tell Django's admin
  1470. to *not* display this widget - otherwise you will end up with two widgets on
  1471. your admin page for managing the relation.
  1472. In all other respects, the ``InlineModelAdmin`` is exactly the same as any
  1473. other. You can customize the appearance using any of the normal
  1474. ``ModelAdmin`` properties.
  1475. Working with many-to-many intermediary models
  1476. ---------------------------------------------
  1477. When you specify an intermediary model using the ``through`` argument to a
  1478. :class:`~django.db.models.ManyToManyField`, the admin will not display a
  1479. widget by default. This is because each instance of that intermediary model
  1480. requires more information than could be displayed in a single widget, and the
  1481. layout required for multiple widgets will vary depending on the intermediate
  1482. model.
  1483. However, we still want to be able to edit that information inline. Fortunately,
  1484. this is easy to do with inline admin models. Suppose we have the following
  1485. models::
  1486. from django.db import models
  1487. class Person(models.Model):
  1488. name = models.CharField(max_length=128)
  1489. class Group(models.Model):
  1490. name = models.CharField(max_length=128)
  1491. members = models.ManyToManyField(Person, through='Membership')
  1492. class Membership(models.Model):
  1493. person = models.ForeignKey(Person)
  1494. group = models.ForeignKey(Group)
  1495. date_joined = models.DateField()
  1496. invite_reason = models.CharField(max_length=64)
  1497. The first step in displaying this intermediate model in the admin is to
  1498. define an inline class for the ``Membership`` model::
  1499. class MembershipInline(admin.TabularInline):
  1500. model = Membership
  1501. extra = 1
  1502. This simple example uses the default ``InlineModelAdmin`` values for the
  1503. ``Membership`` model, and limits the extra add forms to one. This could be
  1504. customized using any of the options available to ``InlineModelAdmin`` classes.
  1505. Now create admin views for the ``Person`` and ``Group`` models::
  1506. class PersonAdmin(admin.ModelAdmin):
  1507. inlines = (MembershipInline,)
  1508. class GroupAdmin(admin.ModelAdmin):
  1509. inlines = (MembershipInline,)
  1510. Finally, register your ``Person`` and ``Group`` models with the admin site::
  1511. admin.site.register(Person, PersonAdmin)
  1512. admin.site.register(Group, GroupAdmin)
  1513. Now your admin site is set up to edit ``Membership`` objects inline from
  1514. either the ``Person`` or the ``Group`` detail pages.
  1515. .. _using-generic-relations-as-an-inline:
  1516. Using generic relations as an inline
  1517. ------------------------------------
  1518. It is possible to use an inline with generically related objects. Let's say
  1519. you have the following models::
  1520. from django.db import models
  1521. class Image(models.Model):
  1522. image = models.ImageField(upload_to="images")
  1523. content_type = models.ForeignKey(ContentType)
  1524. object_id = models.PositiveIntegerField()
  1525. content_object = generic.GenericForeignKey("content_type", "object_id")
  1526. class Product(models.Model):
  1527. name = models.CharField(max_length=100)
  1528. If you want to allow editing and creating ``Image`` instance on the ``Product``
  1529. add/change views you can use ``GenericTabularInline`` or
  1530. ``GenericStackedInline`` (both subclasses of ``GenericInlineModelAdmin``)
  1531. provided by ``django.contrib.contenttypes.generic``, they implement tabular and
  1532. stacked visual layouts for the forms representing the inline objects
  1533. respectively just like their non-generic counterparts and behave just like any
  1534. other inline. In your ``admin.py`` for this example app::
  1535. from django.contrib import admin
  1536. from django.contrib.contenttypes import generic
  1537. from myproject.myapp.models import Image, Product
  1538. class ImageInline(generic.GenericTabularInline):
  1539. model = Image
  1540. class ProductAdmin(admin.ModelAdmin):
  1541. inlines = [
  1542. ImageInline,
  1543. ]
  1544. admin.site.register(Product, ProductAdmin)
  1545. See the :doc:`contenttypes documentation </ref/contrib/contenttypes>` for more
  1546. specific information.
  1547. Overriding admin templates
  1548. ==========================
  1549. It is relatively easy to override many of the templates which the admin module
  1550. uses to generate the various pages of an admin site. You can even override a
  1551. few of these templates for a specific app, or a specific model.
  1552. Set up your projects admin template directories
  1553. -----------------------------------------------
  1554. The admin template files are located in the ``contrib/admin/templates/admin``
  1555. directory.
  1556. In order to override one or more of them, first create an ``admin`` directory
  1557. in your project's ``templates`` directory. This can be any of the directories
  1558. you specified in :setting:`TEMPLATE_DIRS`.
  1559. Within this ``admin`` directory, create sub-directories named after your app.
  1560. Within these app subdirectories create sub-directories named after your models.
  1561. Note, that the admin app will lowercase the model name when looking for the
  1562. directory, so make sure you name the directory in all lowercase if you are
  1563. going to run your app on a case-sensitive filesystem.
  1564. To override an admin template for a specific app, copy and edit the template
  1565. from the ``django/contrib/admin/templates/admin`` directory, and save it to one
  1566. of the directories you just created.
  1567. For example, if we wanted to add a tool to the change list view for all the
  1568. models in an app named ``my_app``, we would copy
  1569. ``contrib/admin/templates/admin/change_list.html`` to the
  1570. ``templates/admin/my_app/`` directory of our project, and make any necessary
  1571. changes.
  1572. If we wanted to add a tool to the change list view for only a specific model
  1573. named 'Page', we would copy that same file to the
  1574. ``templates/admin/my_app/page`` directory of our project.
  1575. Overriding vs. replacing an admin template
  1576. ------------------------------------------
  1577. Because of the modular design of the admin templates, it is usually neither
  1578. necessary nor advisable to replace an entire template. It is almost always
  1579. better to override only the section of the template which you need to change.
  1580. To continue the example above, we want to add a new link next to the
  1581. ``History`` tool for the ``Page`` model. After looking at ``change_form.html``
  1582. we determine that we only need to override the ``object-tools-items`` block.
  1583. Therefore here is our new ``change_form.html`` :
  1584. .. code-block:: html+django
  1585. {% extends "admin/change_form.html" %}
  1586. {% load i18n admin_urls %}
  1587. {% block object-tools-items %}
  1588. <li>
  1589. <a href="{% url opts|admin_urlname:'history' original.pk|admin_urlquote %}" class="historylink">{% trans "History" %}</a>
  1590. </li>
  1591. <li>
  1592. <a href="mylink/" class="historylink">My Link</a>
  1593. </li>
  1594. {% if has_absolute_url %}
  1595. <li>
  1596. <a href="{% url 'admin:view_on_site' content_type_id original.pk %}" class="viewsitelink">{% trans "View on site" %}</a>
  1597. </li>
  1598. {% endif%}
  1599. {% endblock %}
  1600. And that's it! If we placed this file in the ``templates/admin/my_app``
  1601. directory, our link would appear on the change form for all models within
  1602. my_app.
  1603. Templates which may be overridden per app or model
  1604. --------------------------------------------------
  1605. Not every template in ``contrib/admin/templates/admin`` may be overridden per
  1606. app or per model. The following can:
  1607. * ``app_index.html``
  1608. * ``change_form.html``
  1609. * ``change_list.html``
  1610. * ``delete_confirmation.html``
  1611. * ``object_history.html``
  1612. For those templates that cannot be overridden in this way, you may still
  1613. override them for your entire project. Just place the new version in your
  1614. ``templates/admin`` directory. This is particularly useful to create custom 404
  1615. and 500 pages.
  1616. .. note::
  1617. Some of the admin templates, such as ``change_list_results.html`` are used
  1618. to render custom inclusion tags. These may be overridden, but in such cases
  1619. you are probably better off creating your own version of the tag in
  1620. question and giving it a different name. That way you can use it
  1621. selectively.
  1622. Root and login templates
  1623. ------------------------
  1624. If you wish to change the index, login or logout templates, you are better off
  1625. creating your own ``AdminSite`` instance (see below), and changing the
  1626. :attr:`AdminSite.index_template` , :attr:`AdminSite.login_template` or
  1627. :attr:`AdminSite.logout_template` properties.
  1628. ``AdminSite`` objects
  1629. =====================
  1630. .. class:: AdminSite(name='admin')
  1631. A Django administrative site is represented by an instance of
  1632. ``django.contrib.admin.sites.AdminSite``; by default, an instance of
  1633. this class is created as ``django.contrib.admin.site`` and you can
  1634. register your models and ``ModelAdmin`` instances with it.
  1635. If you'd like to set up your own administrative site with custom
  1636. behavior, however, you're free to subclass ``AdminSite`` and override
  1637. or add anything you like. Then, simply create an instance of your
  1638. ``AdminSite`` subclass (the same way you'd instantiate any other
  1639. Python class), and register your models and ``ModelAdmin`` subclasses
  1640. with it instead of using the default.
  1641. When constructing an instance of an ``AdminSite``, you can provide
  1642. a unique instance name using the ``name`` argument to the constructor. This
  1643. instance name is used to identify the instance, especially when
  1644. :ref:`reversing admin URLs <admin-reverse-urls>`. If no instance name is
  1645. provided, a default instance name of ``admin`` will be used.
  1646. ``AdminSite`` attributes
  1647. ------------------------
  1648. Templates can override or extend base admin templates as described in
  1649. `Overriding Admin Templates`_.
  1650. .. attribute:: AdminSite.site_header
  1651. .. versionadded:: 1.7
  1652. The text to put at the top of each admin page, as an ``<h1>`` (a string).
  1653. By default, this is "Django administration".
  1654. .. attribute:: AdminSite.site_title
  1655. .. versionadded:: 1.7
  1656. The text to put at the end of each admin page's ``<title>`` (a string). By
  1657. default, this is "Django site admin".
  1658. .. attribute:: AdminSite.index_title
  1659. .. versionadded:: 1.7
  1660. The text to put at the top of the admin index page (a string). By default,
  1661. this is "Site administration".
  1662. .. attribute:: AdminSite.index_template
  1663. Path to a custom template that will be used by the admin site main index
  1664. view.
  1665. .. attribute:: AdminSite.app_index_template
  1666. Path to a custom template that will be used by the admin site app index view.
  1667. .. attribute:: AdminSite.login_template
  1668. Path to a custom template that will be used by the admin site login view.
  1669. .. attribute:: AdminSite.login_form
  1670. Subclass of :class:`~django.contrib.auth.forms.AuthenticationForm` that
  1671. will be used by the admin site login view.
  1672. .. attribute:: AdminSite.logout_template
  1673. Path to a custom template that will be used by the admin site logout view.
  1674. .. attribute:: AdminSite.password_change_template
  1675. Path to a custom template that will be used by the admin site password
  1676. change view.
  1677. .. attribute:: AdminSite.password_change_done_template
  1678. Path to a custom template that will be used by the admin site password
  1679. change done view.
  1680. Hooking ``AdminSite`` instances into your URLconf
  1681. -------------------------------------------------
  1682. The last step in setting up the Django admin is to hook your ``AdminSite``
  1683. instance into your URLconf. Do this by pointing a given URL at the
  1684. ``AdminSite.urls`` method.
  1685. In this example, we register the default ``AdminSite`` instance
  1686. ``django.contrib.admin.site`` at the URL ``/admin/`` ::
  1687. # urls.py
  1688. from django.conf.urls import patterns, include
  1689. from django.contrib import admin
  1690. admin.autodiscover()
  1691. urlpatterns = patterns('',
  1692. (r'^admin/', include(admin.site.urls)),
  1693. )
  1694. Above we used ``admin.autodiscover()`` to automatically load the
  1695. :setting:`INSTALLED_APPS` admin.py modules.
  1696. In this example, we register the ``AdminSite`` instance
  1697. ``myproject.admin.admin_site`` at the URL ``/myadmin/`` ::
  1698. # urls.py
  1699. from django.conf.urls import patterns, include
  1700. from myproject.admin import admin_site
  1701. urlpatterns = patterns('',
  1702. (r'^myadmin/', include(admin_site.urls)),
  1703. )
  1704. There is really no need to use autodiscover when using your own ``AdminSite``
  1705. instance since you will likely be importing all the per-app admin.py modules
  1706. in your ``myproject.admin`` module.
  1707. Multiple admin sites in the same URLconf
  1708. ----------------------------------------
  1709. It's easy to create multiple instances of the admin site on the same
  1710. Django-powered Web site. Just create multiple instances of ``AdminSite`` and
  1711. root each one at a different URL.
  1712. In this example, the URLs ``/basic-admin/`` and ``/advanced-admin/`` feature
  1713. separate versions of the admin site -- using the ``AdminSite`` instances
  1714. ``myproject.admin.basic_site`` and ``myproject.admin.advanced_site``,
  1715. respectively::
  1716. # urls.py
  1717. from django.conf.urls import patterns, include
  1718. from myproject.admin import basic_site, advanced_site
  1719. urlpatterns = patterns('',
  1720. (r'^basic-admin/', include(basic_site.urls)),
  1721. (r'^advanced-admin/', include(advanced_site.urls)),
  1722. )
  1723. ``AdminSite`` instances take a single argument to their constructor, their
  1724. name, which can be anything you like. This argument becomes the prefix to the
  1725. URL names for the purposes of :ref:`reversing them<admin-reverse-urls>`. This
  1726. is only necessary if you are using more than one ``AdminSite``.
  1727. Adding views to admin sites
  1728. ---------------------------
  1729. Just like :class:`ModelAdmin`, :class:`AdminSite` provides a
  1730. :meth:`~django.contrib.admin.ModelAdmin.get_urls()` method
  1731. that can be overridden to define additional views for the site. To add
  1732. a new view to your admin site, extend the base
  1733. :meth:`~django.contrib.admin.ModelAdmin.get_urls()` method to include
  1734. a pattern for your new view.
  1735. .. note::
  1736. Any view you render that uses the admin templates, or extends the base
  1737. admin template, should provide the ``current_app`` argument to
  1738. :class:`~django.template.RequestContext` or
  1739. :class:`~django.template.Context` when rendering the template. It should
  1740. be set to either ``self.name`` if your view is on an ``AdminSite`` or
  1741. ``self.admin_site.name`` if your view is on a ``ModelAdmin``.
  1742. .. _auth_password_reset:
  1743. Adding a password-reset feature
  1744. -------------------------------
  1745. You can add a password-reset feature to the admin site by adding a few lines to
  1746. your URLconf. Specifically, add these four patterns:
  1747. .. code-block:: python
  1748. url(r'^admin/password_reset/$', 'django.contrib.auth.views.password_reset', name='admin_password_reset'),
  1749. url(r'^admin/password_reset/done/$', 'django.contrib.auth.views.password_reset_done', name='password_reset_done'),
  1750. url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>.+)/$', 'django.contrib.auth.views.password_reset_confirm', name='password_reset_confirm'),
  1751. url(r'^reset/done/$', 'django.contrib.auth.views.password_reset_complete', name='password_reset_complete'),
  1752. .. versionchanged:: 1.6
  1753. The pattern for :func:`~django.contrib.auth.views.password_reset_confirm`
  1754. changed as the ``uid`` is now base 64 encoded.
  1755. (This assumes you've added the admin at ``admin/`` and requires that you put
  1756. the URLs starting with ``^admin/`` before the line that includes the admin app
  1757. itself).
  1758. The presence of the ``admin_password_reset`` named URL will cause a "forgotten
  1759. your password?" link to appear on the default admin log-in page under the
  1760. password box.
  1761. .. _admin-reverse-urls:
  1762. Reversing admin URLs
  1763. ====================
  1764. When an :class:`AdminSite` is deployed, the views provided by that site are
  1765. accessible using Django's :ref:`URL reversing system <naming-url-patterns>`.
  1766. The :class:`AdminSite` provides the following named URL patterns:
  1767. ========================= ======================== ==================================
  1768. Page URL name Parameters
  1769. ========================= ======================== ==================================
  1770. Index ``index``
  1771. Logout ``logout``
  1772. Password change ``password_change``
  1773. Password change done ``password_change_done``
  1774. i18n javascript ``jsi18n``
  1775. Application index page ``app_list`` ``app_label``
  1776. Redirect to object's page ``view_on_site`` ``content_type_id``, ``object_id``
  1777. ========================= ======================== ==================================
  1778. Each :class:`ModelAdmin` instance provides an additional set of named URLs:
  1779. ====================== =============================================== =============
  1780. Page URL name Parameters
  1781. ====================== =============================================== =============
  1782. Changelist ``{{ app_label }}_{{ model_name }}_changelist``
  1783. Add ``{{ app_label }}_{{ model_name }}_add``
  1784. History ``{{ app_label }}_{{ model_name }}_history`` ``object_id``
  1785. Delete ``{{ app_label }}_{{ model_name }}_delete`` ``object_id``
  1786. Change ``{{ app_label }}_{{ model_name }}_change`` ``object_id``
  1787. ====================== =============================================== =============
  1788. These named URLs are registered with the application namespace ``admin``, and
  1789. with an instance namespace corresponding to the name of the Site instance.
  1790. So - if you wanted to get a reference to the Change view for a particular
  1791. ``Choice`` object (from the polls application) in the default admin, you would
  1792. call::
  1793. >>> from django.core import urlresolvers
  1794. >>> c = Choice.objects.get(...)
  1795. >>> change_url = urlresolvers.reverse('admin:polls_choice_change', args=(c.id,))
  1796. This will find the first registered instance of the admin application
  1797. (whatever the instance name), and resolve to the view for changing
  1798. ``poll.Choice`` instances in that instance.
  1799. If you want to find a URL in a specific admin instance, provide the name of
  1800. that instance as a ``current_app`` hint to the reverse call. For example,
  1801. if you specifically wanted the admin view from the admin instance named
  1802. ``custom``, you would need to call::
  1803. >>> change_url = urlresolvers.reverse('admin:polls_choice_change',
  1804. ... args=(c.id,), current_app='custom')
  1805. For more details, see the documentation on :ref:`reversing namespaced URLs
  1806. <topics-http-reversing-url-namespaces>`.
  1807. To allow easier reversing of the admin urls in templates, Django provides an
  1808. ``admin_urlname`` filter which takes an action as argument:
  1809. .. code-block:: html+django
  1810. {% load admin_urls %}
  1811. <a href="{% url opts|admin_urlname:'add' %}">Add user</a>
  1812. <a href="{% url opts|admin_urlname:'delete' user.pk %}">Delete this user</a>
  1813. The action in the examples above match the last part of the URL names for
  1814. :class:`ModelAdmin` instances described above. The ``opts`` variable can be any
  1815. object which has an ``app_label`` and ``model_name`` attributes and is usually
  1816. supplied by the admin views for the current model.