index.txt 111 KB

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