index.txt 102 KB

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