index.txt 134 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526
  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 from your models to provide a quick, model-centric interface
  8. where trusted users can manage content on your site. The admin's recommended
  9. use is limited to an organization's internal management tool. It's not intended
  10. for building your entire front end around.
  11. The admin has many hooks for customization, but beware of trying to use those
  12. hooks exclusively. If you need to provide a more process-centric interface
  13. that abstracts away the implementation details of database tables and fields,
  14. then it's probably time to write your own views.
  15. In this document we discuss how to activate, use, and customize Django's admin
  16. interface.
  17. Overview
  18. ========
  19. The admin is enabled in the default project template used by
  20. :djadmin:`startproject`.
  21. If you're not using the default project template, here are the requirements:
  22. #. Add ``'django.contrib.admin'`` and its dependencies -
  23. :mod:`django.contrib.auth`, :mod:`django.contrib.contenttypes`,
  24. :mod:`django.contrib.messages`, and :mod:`django.contrib.sessions` - to your
  25. :setting:`INSTALLED_APPS` setting.
  26. #. Configure a :class:`~django.template.backends.django.DjangoTemplates`
  27. backend in your :setting:`TEMPLATES` setting with
  28. ``django.template.context_processors.request``,
  29. ``django.contrib.auth.context_processors.auth``, and
  30. ``django.contrib.messages.context_processors.messages`` in
  31. the ``'context_processors'`` option of :setting:`OPTIONS
  32. <TEMPLATES-OPTIONS>`.
  33. #. If you've customized the :setting:`MIDDLEWARE` setting,
  34. :class:`django.contrib.sessions.middleware.SessionMiddleware`,
  35. :class:`django.contrib.auth.middleware.AuthenticationMiddleware`, and
  36. :class:`django.contrib.messages.middleware.MessageMiddleware` must be
  37. included.
  38. #. :ref:`Hook the admin's URLs into your URLconf
  39. <hooking-adminsite-to-urlconf>`.
  40. After you've taken these steps, you'll be able to use the admin site by
  41. visiting the URL you hooked it into (``/admin/``, by default).
  42. If you need to create a user to login with, use the :djadmin:`createsuperuser`
  43. command. By default, logging in to the admin requires that the user has the
  44. :attr:`~.User.is_staff` attribute set to ``True``.
  45. Finally, determine which of your application's models should be editable in the
  46. admin interface. For each of those models, register them with the admin as
  47. described in :class:`ModelAdmin`.
  48. Other topics
  49. ------------
  50. .. toctree::
  51. :maxdepth: 1
  52. actions
  53. filters
  54. admindocs
  55. javascript
  56. .. seealso::
  57. For information about serving the static files (images, JavaScript, and
  58. CSS) associated with the admin in production, see :ref:`serving-files`.
  59. Having problems? Try :doc:`/faq/admin`.
  60. ``ModelAdmin`` objects
  61. ======================
  62. .. class:: ModelAdmin
  63. The ``ModelAdmin`` class is the representation of a model in the admin
  64. interface. Usually, these are stored in a file named ``admin.py`` in your
  65. application. Let's take a look at an example of the ``ModelAdmin``::
  66. from django.contrib import admin
  67. from myapp.models import Author
  68. class AuthorAdmin(admin.ModelAdmin):
  69. pass
  70. admin.site.register(Author, AuthorAdmin)
  71. .. admonition:: Do you need a ``ModelAdmin`` object at all?
  72. In the preceding example, the ``ModelAdmin`` class doesn't define any
  73. custom values (yet). As a result, the default admin interface will be
  74. provided. If you are happy with the default admin interface, you don't
  75. need to define a ``ModelAdmin`` object at all -- you can register the
  76. model class without providing a ``ModelAdmin`` description. The
  77. preceding example could be simplified to::
  78. from django.contrib import admin
  79. from myapp.models import Author
  80. admin.site.register(Author)
  81. The ``register`` decorator
  82. --------------------------
  83. .. function:: register(*models, site=django.contrib.admin.sites.site)
  84. There is also a decorator for registering your ``ModelAdmin`` classes::
  85. from django.contrib import admin
  86. from .models import Author
  87. @admin.register(Author)
  88. class AuthorAdmin(admin.ModelAdmin):
  89. pass
  90. It's given one or more model classes to register with the ``ModelAdmin``.
  91. If you're using a custom :class:`AdminSite`, pass it using the ``site`` keyword
  92. argument::
  93. from django.contrib import admin
  94. from .models import Author, Editor, Reader
  95. from myproject.admin_site import custom_admin_site
  96. @admin.register(Author, Reader, Editor, site=custom_admin_site)
  97. class PersonAdmin(admin.ModelAdmin):
  98. pass
  99. You can't use this decorator if you have to reference your model admin
  100. class in its ``__init__()`` method, e.g.
  101. ``super(PersonAdmin, self).__init__(*args, **kwargs)``. You can use
  102. ``super().__init__(*args, **kwargs)``.
  103. Discovery of admin files
  104. ------------------------
  105. When you put ``'django.contrib.admin'`` in your :setting:`INSTALLED_APPS`
  106. setting, Django automatically looks for an ``admin`` module in each
  107. application and imports it.
  108. .. class:: apps.AdminConfig
  109. This is the default :class:`~django.apps.AppConfig` class for the admin.
  110. It calls :func:`~django.contrib.admin.autodiscover()` when Django starts.
  111. .. class:: apps.SimpleAdminConfig
  112. This class works like :class:`~django.contrib.admin.apps.AdminConfig`,
  113. except it doesn't call :func:`~django.contrib.admin.autodiscover()`.
  114. .. attribute:: default_site
  115. A dotted import path to the default admin site's class or to a callable
  116. that returns a site instance. Defaults to
  117. ``'django.contrib.admin.sites.AdminSite'``. See
  118. :ref:`overriding-default-admin-site` for usage.
  119. .. function:: autodiscover
  120. This function attempts to import an ``admin`` module in each installed
  121. application. Such modules are expected to register models with the admin.
  122. Typically you won't need to call this function directly as
  123. :class:`~django.contrib.admin.apps.AdminConfig` calls it when Django starts.
  124. If you are using a custom ``AdminSite``, it is common to import all of the
  125. ``ModelAdmin`` subclasses into your code and register them to the custom
  126. ``AdminSite``. In that case, in order to disable auto-discovery, you should
  127. put ``'django.contrib.admin.apps.SimpleAdminConfig'`` instead of
  128. ``'django.contrib.admin'`` in your :setting:`INSTALLED_APPS` setting.
  129. ``ModelAdmin`` options
  130. ----------------------
  131. The ``ModelAdmin`` is very flexible. It has several options for dealing with
  132. customizing the interface. All options are defined on the ``ModelAdmin``
  133. subclass::
  134. from django.contrib import admin
  135. class AuthorAdmin(admin.ModelAdmin):
  136. date_hierarchy = "pub_date"
  137. .. attribute:: ModelAdmin.actions
  138. A list of actions to make available on the change list page. See
  139. :doc:`/ref/contrib/admin/actions` for details.
  140. .. attribute:: ModelAdmin.actions_on_top
  141. .. attribute:: ModelAdmin.actions_on_bottom
  142. Controls where on the page the actions bar appears. By default, the admin
  143. changelist displays actions at the top of the page (``actions_on_top = True;
  144. actions_on_bottom = False``).
  145. .. attribute:: ModelAdmin.actions_selection_counter
  146. Controls whether a selection counter is displayed next to the action dropdown.
  147. By default, the admin changelist will display it
  148. (``actions_selection_counter = True``).
  149. .. attribute:: ModelAdmin.date_hierarchy
  150. Set ``date_hierarchy`` to the name of a ``DateField`` or ``DateTimeField``
  151. in your model, and the change list page will include a date-based drilldown
  152. navigation by that field.
  153. Example::
  154. date_hierarchy = "pub_date"
  155. You can also specify a field on a related model using the ``__`` lookup,
  156. for example::
  157. date_hierarchy = "author__pub_date"
  158. This will intelligently populate itself based on available data,
  159. e.g. if all the dates are in one month, it'll show the day-level
  160. drill-down only.
  161. .. note::
  162. ``date_hierarchy`` uses :meth:`QuerySet.datetimes()
  163. <django.db.models.query.QuerySet.datetimes>` internally. Please refer
  164. to its documentation for some caveats when time zone support is
  165. enabled (:setting:`USE_TZ = True <USE_TZ>`).
  166. .. attribute:: ModelAdmin.empty_value_display
  167. This attribute overrides the default display value for record's fields that
  168. are empty (``None``, empty string, etc.). The default value is ``-`` (a
  169. dash). For example::
  170. from django.contrib import admin
  171. class AuthorAdmin(admin.ModelAdmin):
  172. empty_value_display = "-empty-"
  173. You can also override ``empty_value_display`` for all admin pages with
  174. :attr:`AdminSite.empty_value_display`, or for specific fields like this::
  175. from django.contrib import admin
  176. class AuthorAdmin(admin.ModelAdmin):
  177. list_display = ["name", "title", "view_birth_date"]
  178. @admin.display(empty_value="???")
  179. def view_birth_date(self, obj):
  180. return obj.birth_date
  181. .. attribute:: ModelAdmin.exclude
  182. This attribute, if given, should be a list of field names to exclude from
  183. the form.
  184. For example, let's consider the following model::
  185. from django.db import models
  186. class Author(models.Model):
  187. name = models.CharField(max_length=100)
  188. title = models.CharField(max_length=3)
  189. birth_date = models.DateField(blank=True, null=True)
  190. If you want a form for the ``Author`` model that includes only the ``name``
  191. and ``title`` fields, you would specify ``fields`` or ``exclude`` like
  192. this::
  193. from django.contrib import admin
  194. class AuthorAdmin(admin.ModelAdmin):
  195. fields = ["name", "title"]
  196. class AuthorAdmin(admin.ModelAdmin):
  197. exclude = ["birth_date"]
  198. Since the Author model only has three fields, ``name``, ``title``, and
  199. ``birth_date``, the forms resulting from the above declarations will
  200. contain exactly the same fields.
  201. .. attribute:: ModelAdmin.fields
  202. Use the ``fields`` option to make simple layout changes in the forms on
  203. the "add" and "change" pages such as showing only a subset of available
  204. fields, modifying their order, or grouping them into rows. For example, you
  205. could define a simpler version of the admin form for the
  206. :class:`django.contrib.flatpages.models.FlatPage` model as follows::
  207. class FlatPageAdmin(admin.ModelAdmin):
  208. fields = ["url", "title", "content"]
  209. In the above example, only the fields ``url``, ``title`` and ``content``
  210. will be displayed, sequentially, in the form. ``fields`` can contain
  211. values defined in :attr:`ModelAdmin.readonly_fields` to be displayed as
  212. read-only.
  213. For more complex layout needs, see the :attr:`~ModelAdmin.fieldsets` option.
  214. The ``fields`` option accepts the same types of values as
  215. :attr:`~ModelAdmin.list_display`, except that callables and ``__`` lookups
  216. for related fields aren't accepted. Names of model and model admin methods
  217. will only be used if they're listed in :attr:`~ModelAdmin.readonly_fields`.
  218. To display multiple fields on the same line, wrap those fields in their own
  219. tuple. In this example, the ``url`` and ``title`` fields will display on the
  220. same line and the ``content`` field will be displayed below them on its
  221. own line::
  222. class FlatPageAdmin(admin.ModelAdmin):
  223. fields = [("url", "title"), "content"]
  224. .. admonition:: Possible confusion with the ``ModelAdmin.fieldsets`` option
  225. This ``fields`` option should not be confused with the ``fields``
  226. dictionary key that is within the :attr:`~ModelAdmin.fieldsets` option,
  227. as described in the next section.
  228. If neither ``fields`` nor :attr:`~ModelAdmin.fieldsets` options are present,
  229. Django will default to displaying each field that isn't an ``AutoField`` and
  230. has ``editable=True``, in a single fieldset, in the same order as the fields
  231. are defined in the model, followed by any fields defined in
  232. :attr:`~ModelAdmin.readonly_fields`.
  233. .. attribute:: ModelAdmin.fieldsets
  234. Set ``fieldsets`` to control the layout of admin "add" and "change" pages.
  235. ``fieldsets`` is a list of 2-tuples, in which each 2-tuple represents a
  236. ``<fieldset>`` on the admin form page. (A ``<fieldset>`` is a "section" of
  237. the form.)
  238. The 2-tuples are in the format ``(name, field_options)``, where ``name``
  239. is a string representing the title of the fieldset and ``field_options`` is
  240. a dictionary of information about the fieldset, including a list of fields
  241. to be displayed in it.
  242. A full example, taken from the
  243. :class:`django.contrib.flatpages.models.FlatPage` model::
  244. from django.contrib import admin
  245. class FlatPageAdmin(admin.ModelAdmin):
  246. fieldsets = [
  247. (
  248. None,
  249. {
  250. "fields": ["url", "title", "content", "sites"],
  251. },
  252. ),
  253. (
  254. "Advanced options",
  255. {
  256. "classes": ["collapse"],
  257. "fields": ["registration_required", "template_name"],
  258. },
  259. ),
  260. ]
  261. This results in an admin page that looks like:
  262. .. image:: _images/fieldsets.png
  263. If neither ``fieldsets`` nor :attr:`~ModelAdmin.fields` options are present,
  264. Django will default to displaying each field that isn't an ``AutoField`` and
  265. has ``editable=True``, in a single fieldset, in the same order as the fields
  266. are defined in the model.
  267. The ``field_options`` dictionary can have the following keys:
  268. * ``fields``
  269. A list or tuple of field names to display in this fieldset. This key is
  270. required.
  271. Example::
  272. {
  273. "fields": ["first_name", "last_name", "address", "city", "state"],
  274. }
  275. As with the :attr:`~ModelAdmin.fields` option, to display multiple
  276. fields on the same line, wrap those fields in their own tuple. In this
  277. example, the ``first_name`` and ``last_name`` fields will display on
  278. the same line::
  279. {
  280. "fields": [("first_name", "last_name"), "address", "city", "state"],
  281. }
  282. ``fields`` can contain values defined in
  283. :attr:`~ModelAdmin.readonly_fields` to be displayed as read-only.
  284. If you add the name of a callable to ``fields``, the same rule applies
  285. as with the :attr:`~ModelAdmin.fields` option: the callable must be
  286. listed in :attr:`~ModelAdmin.readonly_fields`.
  287. * ``classes``
  288. A list or tuple containing extra CSS classes to apply to the fieldset.
  289. This can include any custom CSS class defined in the project, as well
  290. as any of the CSS classes provided by Django. Within the default admin
  291. site CSS stylesheet, two particularly useful classes are defined:
  292. ``collapse`` and ``wide``.
  293. Example::
  294. {
  295. "classes": ["wide", "collapse"],
  296. }
  297. Fieldsets with the ``wide`` style will be given extra horizontal
  298. space in the admin interface.
  299. Fieldsets with a name and the ``collapse`` style will be initially
  300. collapsed, using an expandable widget with a toggle for switching
  301. their visibility.
  302. * ``description``
  303. A string of optional extra text to be displayed at the top of each
  304. fieldset, under the heading of the fieldset.
  305. Note that this value is *not* HTML-escaped when it's displayed in
  306. the admin interface. This lets you include HTML if you so desire.
  307. Alternatively you can use plain text and
  308. :func:`django.utils.html.escape` to escape any HTML special
  309. characters.
  310. .. admonition:: :class:`~django.contrib.admin.TabularInline` has limited
  311. support for ``fieldsets``
  312. Using ``fieldsets`` with :class:`~django.contrib.admin.TabularInline`
  313. has limited functionality. You can specify which fields will be
  314. displayed and their order within the ``TabularInline`` layout by
  315. defining ``fields`` in the ``field_options`` dictionary.
  316. All other features are not supported. This includes the use of ``name``
  317. to define a title for a group of fields.
  318. .. attribute:: ModelAdmin.filter_horizontal
  319. By default, a :class:`~django.db.models.ManyToManyField` is displayed in
  320. the admin site with a ``<select multiple>``. However, multiple-select boxes
  321. can be difficult to use when selecting many items. Adding a
  322. :class:`~django.db.models.ManyToManyField` to this list will instead use
  323. a nifty unobtrusive JavaScript "filter" interface that allows searching
  324. within the options. The unselected and selected options appear in two boxes
  325. side by side. See :attr:`~ModelAdmin.filter_vertical` to use a vertical
  326. interface.
  327. .. attribute:: ModelAdmin.filter_vertical
  328. Same as :attr:`~ModelAdmin.filter_horizontal`, but uses a vertical display
  329. of the filter interface with the box of unselected options appearing above
  330. the box of selected options.
  331. .. attribute:: ModelAdmin.form
  332. By default a ``ModelForm`` is dynamically created for your model. It is
  333. used to create the form presented on both the add/change pages. You can
  334. easily provide your own ``ModelForm`` to override any default form behavior
  335. on the add/change pages. Alternatively, you can customize the default
  336. form rather than specifying an entirely new one by using the
  337. :meth:`ModelAdmin.get_form` method.
  338. For an example see the section :ref:`admin-custom-validation`.
  339. .. admonition:: Omit the ``Meta.model`` attribute
  340. If you define the ``Meta.model`` attribute on a
  341. :class:`~django.forms.ModelForm`, you must also define the
  342. ``Meta.fields`` attribute (or the ``Meta.exclude`` attribute). However,
  343. since the admin has its own way of defining fields, the ``Meta.fields``
  344. attribute will be ignored.
  345. If the ``ModelForm`` is only going to be used for the admin, the easiest
  346. solution is to omit the ``Meta.model`` attribute, since ``ModelAdmin``
  347. will provide the correct model to use. Alternatively, you can set
  348. ``fields = []`` in the ``Meta`` class to satisfy the validation on the
  349. ``ModelForm``.
  350. .. admonition:: ``ModelAdmin.exclude`` takes precedence
  351. If your ``ModelForm`` and ``ModelAdmin`` both define an ``exclude``
  352. option then ``ModelAdmin`` takes precedence::
  353. from django import forms
  354. from django.contrib import admin
  355. from myapp.models import Person
  356. class PersonForm(forms.ModelForm):
  357. class Meta:
  358. model = Person
  359. exclude = ["name"]
  360. class PersonAdmin(admin.ModelAdmin):
  361. exclude = ["age"]
  362. form = PersonForm
  363. In the above example, the "age" field will be excluded but the "name"
  364. field will be included in the generated form.
  365. .. attribute:: ModelAdmin.formfield_overrides
  366. This provides a quick-and-dirty way to override some of the
  367. :class:`~django.forms.Field` options for use in the admin.
  368. ``formfield_overrides`` is a dictionary mapping a field class to a dict of
  369. arguments to pass to the field at construction time.
  370. Since that's a bit abstract, let's look at a concrete example. The most
  371. common use of ``formfield_overrides`` is to add a custom widget for a
  372. certain type of field. So, imagine we've written a ``RichTextEditorWidget``
  373. that we'd like to use for large text fields instead of the default
  374. ``<textarea>``. Here's how we'd do that::
  375. from django.contrib import admin
  376. from django.db import models
  377. # Import our custom widget and our model from where they're defined
  378. from myapp.models import MyModel
  379. from myapp.widgets import RichTextEditorWidget
  380. class MyModelAdmin(admin.ModelAdmin):
  381. formfield_overrides = {
  382. models.TextField: {"widget": RichTextEditorWidget},
  383. }
  384. Note that the key in the dictionary is the actual field class, *not* a
  385. string. The value is another dictionary; these arguments will be passed to
  386. the form field's ``__init__()`` method. See :doc:`/ref/forms/api` for
  387. details.
  388. .. warning::
  389. If you want to use a custom widget with a relation field (i.e.
  390. :class:`~django.db.models.ForeignKey` or
  391. :class:`~django.db.models.ManyToManyField`), make sure you haven't
  392. included that field's name in ``raw_id_fields``, ``radio_fields``, or
  393. ``autocomplete_fields``.
  394. ``formfield_overrides`` won't let you change the widget on relation
  395. fields that have ``raw_id_fields``, ``radio_fields``, or
  396. ``autocomplete_fields`` set. That's because ``raw_id_fields``,
  397. ``radio_fields``, and ``autocomplete_fields`` imply custom widgets of
  398. their own.
  399. .. attribute:: ModelAdmin.inlines
  400. See :class:`InlineModelAdmin` objects below as well as
  401. :meth:`ModelAdmin.get_formsets_with_inlines`.
  402. .. attribute:: ModelAdmin.list_display
  403. Set ``list_display`` to control which fields are displayed on the change
  404. list page of the admin.
  405. Example::
  406. list_display = ["first_name", "last_name"]
  407. If you don't set ``list_display``, the admin site will display a single
  408. column that displays the ``__str__()`` representation of each object.
  409. There are five types of values that can be used in ``list_display``. All
  410. but the simplest may use the :func:`~django.contrib.admin.display`
  411. decorator, which is used to customize how the field is presented:
  412. * The name of a model field. For example::
  413. class PersonAdmin(admin.ModelAdmin):
  414. list_display = ["first_name", "last_name"]
  415. * The name of a related field, using the ``__`` notation. For example::
  416. class PersonAdmin(admin.ModelAdmin):
  417. list_display = ["city__name"]
  418. * A callable that accepts one argument, the model instance. For example::
  419. @admin.display(description="Name")
  420. def upper_case_name(obj):
  421. return f"{obj.first_name} {obj.last_name}".upper()
  422. class PersonAdmin(admin.ModelAdmin):
  423. list_display = [upper_case_name]
  424. * A string representing a ``ModelAdmin`` method that accepts one argument,
  425. the model instance. For example::
  426. class PersonAdmin(admin.ModelAdmin):
  427. list_display = ["upper_case_name"]
  428. @admin.display(description="Name")
  429. def upper_case_name(self, obj):
  430. return f"{obj.first_name} {obj.last_name}".upper()
  431. * A string representing a model attribute or method (without any required
  432. arguments). For example::
  433. from django.contrib import admin
  434. from django.db import models
  435. class Person(models.Model):
  436. name = models.CharField(max_length=50)
  437. birthday = models.DateField()
  438. @admin.display(description="Birth decade")
  439. def decade_born_in(self):
  440. decade = self.birthday.year // 10 * 10
  441. return f"{decade}’s"
  442. class PersonAdmin(admin.ModelAdmin):
  443. list_display = ["name", "decade_born_in"]
  444. A few special cases to note about ``list_display``:
  445. * If the field is a ``ForeignKey``, Django will display the
  446. ``__str__()`` of the related object.
  447. * ``ManyToManyField`` fields aren't supported, because that would
  448. entail executing a separate SQL statement for each row in the table.
  449. If you want to do this nonetheless, give your model a custom method,
  450. and add that method's name to ``list_display``. (See below for more
  451. on custom methods in ``list_display``.)
  452. * If the field is a ``BooleanField``, Django will display a pretty "yes",
  453. "no", or "unknown" icon instead of ``True``, ``False``, or ``None``.
  454. * If the string given is a method of the model, ``ModelAdmin`` or a
  455. callable, Django will HTML-escape the output by default. To escape
  456. user input and allow your own unescaped tags, use
  457. :func:`~django.utils.html.format_html`.
  458. Here's a full example model::
  459. from django.contrib import admin
  460. from django.db import models
  461. from django.utils.html import format_html
  462. class Person(models.Model):
  463. first_name = models.CharField(max_length=50)
  464. last_name = models.CharField(max_length=50)
  465. color_code = models.CharField(max_length=6)
  466. @admin.display
  467. def colored_name(self):
  468. return format_html(
  469. '<span style="color: #{};">{} {}</span>',
  470. self.color_code,
  471. self.first_name,
  472. self.last_name,
  473. )
  474. class PersonAdmin(admin.ModelAdmin):
  475. list_display = ["first_name", "last_name", "colored_name"]
  476. * As some examples have already demonstrated, when using a callable, a
  477. model method, or a ``ModelAdmin`` method, you can customize the column's
  478. title by wrapping the callable with the
  479. :func:`~django.contrib.admin.display` decorator and passing the
  480. ``description`` argument.
  481. * If the value of a field is ``None``, an empty string, or an iterable
  482. without elements, Django will display ``-`` (a dash). You can override
  483. this with :attr:`AdminSite.empty_value_display`::
  484. from django.contrib import admin
  485. admin.site.empty_value_display = "(None)"
  486. You can also use :attr:`ModelAdmin.empty_value_display`::
  487. class PersonAdmin(admin.ModelAdmin):
  488. empty_value_display = "unknown"
  489. Or on a field level::
  490. class PersonAdmin(admin.ModelAdmin):
  491. list_display = ["name", "birth_date_view"]
  492. @admin.display(empty_value="unknown")
  493. def birth_date_view(self, obj):
  494. return obj.birth_date
  495. * If the string given is a method of the model, ``ModelAdmin`` or a
  496. callable that returns ``True``, ``False``, or ``None``, Django will
  497. display a pretty "yes", "no", or "unknown" icon if you wrap the method
  498. with the :func:`~django.contrib.admin.display` decorator passing the
  499. ``boolean`` argument with the value set to ``True``::
  500. from django.contrib import admin
  501. from django.db import models
  502. class Person(models.Model):
  503. first_name = models.CharField(max_length=50)
  504. birthday = models.DateField()
  505. @admin.display(boolean=True)
  506. def born_in_fifties(self):
  507. return 1950 <= self.birthday.year < 1960
  508. class PersonAdmin(admin.ModelAdmin):
  509. list_display = ["name", "born_in_fifties"]
  510. * The ``__str__()`` method is just as valid in ``list_display`` as any
  511. other model method, so it's perfectly OK to do this::
  512. list_display = ["__str__", "some_other_field"]
  513. * Usually, elements of ``list_display`` that aren't actual database
  514. fields can't be used in sorting (because Django does all the sorting
  515. at the database level).
  516. However, if an element of ``list_display`` represents a certain database
  517. field, you can indicate this fact by using the
  518. :func:`~django.contrib.admin.display` decorator on the method, passing
  519. the ``ordering`` argument::
  520. from django.contrib import admin
  521. from django.db import models
  522. from django.utils.html import format_html
  523. class Person(models.Model):
  524. first_name = models.CharField(max_length=50)
  525. color_code = models.CharField(max_length=6)
  526. @admin.display(ordering="first_name")
  527. def colored_first_name(self):
  528. return format_html(
  529. '<span style="color: #{};">{}</span>',
  530. self.color_code,
  531. self.first_name,
  532. )
  533. class PersonAdmin(admin.ModelAdmin):
  534. list_display = ["first_name", "colored_first_name"]
  535. The above will tell Django to order by the ``first_name`` field when
  536. trying to sort by ``colored_first_name`` in the admin.
  537. To indicate descending order with the ``ordering`` argument you can use a
  538. hyphen prefix on the field name. Using the above example, this would look
  539. like::
  540. @admin.display(ordering="-first_name")
  541. def colored_first_name(self): ...
  542. The ``ordering`` argument supports query lookups to sort by values on
  543. related models. This example includes an "author first name" column in
  544. the list display and allows sorting it by first name::
  545. class Blog(models.Model):
  546. title = models.CharField(max_length=255)
  547. author = models.ForeignKey(Person, on_delete=models.CASCADE)
  548. class BlogAdmin(admin.ModelAdmin):
  549. list_display = ["title", "author", "author_first_name"]
  550. @admin.display(ordering="author__first_name")
  551. def author_first_name(self, obj):
  552. return obj.author.first_name
  553. :doc:`Query expressions </ref/models/expressions>` may be used with the
  554. ``ordering`` argument::
  555. from django.db.models import Value
  556. from django.db.models.functions import Concat
  557. class Person(models.Model):
  558. first_name = models.CharField(max_length=50)
  559. last_name = models.CharField(max_length=50)
  560. @admin.display(ordering=Concat("first_name", Value(" "), "last_name"))
  561. def full_name(self):
  562. return self.first_name + " " + self.last_name
  563. * Elements of ``list_display`` can also be properties
  564. ::
  565. class Person(models.Model):
  566. first_name = models.CharField(max_length=50)
  567. last_name = models.CharField(max_length=50)
  568. @property
  569. @admin.display(
  570. ordering="last_name",
  571. description="Full name of the person",
  572. boolean=False,
  573. )
  574. def full_name(self):
  575. return self.first_name + " " + self.last_name
  576. class PersonAdmin(admin.ModelAdmin):
  577. list_display = ["full_name"]
  578. Note that ``@property`` must be above ``@display``. If you're using the
  579. old way -- setting the display-related attributes directly rather than
  580. using the :func:`~django.contrib.admin.display` decorator -- be aware
  581. that the ``property()`` function and **not** the ``@property`` decorator
  582. must be used::
  583. def my_property(self):
  584. return self.first_name + " " + self.last_name
  585. my_property.short_description = "Full name of the person"
  586. my_property.admin_order_field = "last_name"
  587. my_property.boolean = False
  588. full_name = property(my_property)
  589. * The field names in ``list_display`` will also appear as CSS classes in
  590. the HTML output, in the form of ``column-<field_name>`` on each ``<th>``
  591. element. This can be used to set column widths in a CSS file for example.
  592. * Django will try to interpret every element of ``list_display`` in this
  593. order:
  594. * A field of the model or from a related field.
  595. * A callable.
  596. * A string representing a ``ModelAdmin`` attribute.
  597. * A string representing a model attribute.
  598. For example if you have ``first_name`` as a model field and
  599. as a ``ModelAdmin`` attribute, the model field will be used.
  600. .. attribute:: ModelAdmin.list_display_links
  601. Use ``list_display_links`` to control if and which fields in
  602. :attr:`list_display` should be linked to the "change" page for an object.
  603. By default, the change list page will link the first column -- the first
  604. field specified in ``list_display`` -- to the change page for each item.
  605. But ``list_display_links`` lets you change this:
  606. * Set it to ``None`` to get no links at all.
  607. * Set it to a list or tuple of fields (in the same format as
  608. ``list_display``) whose columns you want converted to links.
  609. You can specify one or many fields. As long as the fields appear in
  610. ``list_display``, Django doesn't care how many (or how few) fields are
  611. linked. The only requirement is that if you want to use
  612. ``list_display_links`` in this fashion, you must define ``list_display``.
  613. In this example, the ``first_name`` and ``last_name`` fields will be
  614. linked on the change list page::
  615. class PersonAdmin(admin.ModelAdmin):
  616. list_display = ["first_name", "last_name", "birthday"]
  617. list_display_links = ["first_name", "last_name"]
  618. In this example, the change list page grid will have no links::
  619. class AuditEntryAdmin(admin.ModelAdmin):
  620. list_display = ["timestamp", "message"]
  621. list_display_links = None
  622. .. _admin-list-editable:
  623. .. attribute:: ModelAdmin.list_editable
  624. Set ``list_editable`` to a list of field names on the model which will
  625. allow editing on the change list page. That is, fields listed in
  626. ``list_editable`` will be displayed as form widgets on the change list
  627. page, allowing users to edit and save multiple rows at once.
  628. .. note::
  629. ``list_editable`` interacts with a couple of other options in
  630. particular ways; you should note the following rules:
  631. * Any field in ``list_editable`` must also be in ``list_display``.
  632. You can't edit a field that's not displayed!
  633. * The same field can't be listed in both ``list_editable`` and
  634. ``list_display_links`` -- a field can't be both a form and
  635. a link.
  636. You'll get a validation error if either of these rules are broken.
  637. .. attribute:: ModelAdmin.list_filter
  638. Set ``list_filter`` to activate filters in the right sidebar of the change
  639. list page of the admin.
  640. At it's simplest ``list_filter`` takes a list or tuple of field names to
  641. activate filtering upon, but several more advanced options as available.
  642. See :ref:`modeladmin-list-filters` for the details.
  643. .. attribute:: ModelAdmin.list_max_show_all
  644. Set ``list_max_show_all`` to control how many items can appear on a "Show
  645. all" admin change list page. The admin will display a "Show all" link on the
  646. change list only if the total result count is less than or equal to this
  647. setting. By default, this is set to ``200``.
  648. .. attribute:: ModelAdmin.list_per_page
  649. Set ``list_per_page`` to control how many items appear on each paginated
  650. admin change list page. By default, this is set to ``100``.
  651. .. attribute:: ModelAdmin.list_select_related
  652. Set ``list_select_related`` to tell Django to use
  653. :meth:`~django.db.models.query.QuerySet.select_related` in retrieving
  654. the list of objects on the admin change list page. This can save you a
  655. bunch of database queries.
  656. The value should be either a boolean, a list or a tuple. Default is
  657. ``False``.
  658. When value is ``True``, ``select_related()`` will always be called. When
  659. value is set to ``False``, Django will look at ``list_display`` and call
  660. ``select_related()`` if any ``ForeignKey`` is present.
  661. If you need more fine-grained control, use a tuple (or list) as value for
  662. ``list_select_related``. Empty tuple will prevent Django from calling
  663. ``select_related`` at all. Any other tuple will be passed directly to
  664. ``select_related`` as parameters. For example::
  665. class ArticleAdmin(admin.ModelAdmin):
  666. list_select_related = ["author", "category"]
  667. will call ``select_related('author', 'category')``.
  668. If you need to specify a dynamic value based on the request, you can
  669. implement a :meth:`~ModelAdmin.get_list_select_related` method.
  670. .. note::
  671. ``ModelAdmin`` ignores this attribute when
  672. :meth:`~django.db.models.query.QuerySet.select_related` was already
  673. called on the changelist's ``QuerySet``.
  674. .. attribute:: ModelAdmin.ordering
  675. Set ``ordering`` to specify how lists of objects should be ordered in the
  676. Django admin views. This should be a list or tuple in the same format as a
  677. model's :attr:`~django.db.models.Options.ordering` parameter.
  678. If this isn't provided, the Django admin will use the model's default
  679. ordering.
  680. If you need to specify a dynamic order (for example depending on user or
  681. language) you can implement a :meth:`~ModelAdmin.get_ordering` method.
  682. .. admonition:: Performance considerations with ordering and sorting
  683. To ensure a deterministic ordering of results, the changelist adds
  684. ``pk`` to the ordering if it can't find a single or unique together set
  685. of fields that provide total ordering.
  686. For example, if the default ordering is by a non-unique ``name`` field,
  687. then the changelist is sorted by ``name`` and ``pk``. This could
  688. perform poorly if you have a lot of rows and don't have an index on
  689. ``name`` and ``pk``.
  690. .. attribute:: ModelAdmin.paginator
  691. The paginator class to be used for pagination. By default,
  692. :class:`django.core.paginator.Paginator` is used. If the custom paginator
  693. class doesn't have the same constructor interface as
  694. :class:`django.core.paginator.Paginator`, you will also need to
  695. provide an implementation for :meth:`ModelAdmin.get_paginator`.
  696. .. attribute:: ModelAdmin.prepopulated_fields
  697. Set ``prepopulated_fields`` to a dictionary mapping field names to the
  698. fields it should prepopulate from::
  699. class ArticleAdmin(admin.ModelAdmin):
  700. prepopulated_fields = {"slug": ["title"]}
  701. When set, the given fields will use a bit of JavaScript to populate from
  702. the fields assigned. The main use for this functionality is to
  703. automatically generate the value for ``SlugField`` fields from one or more
  704. other fields. The generated value is produced by concatenating the values
  705. of the source fields, and then by transforming that result into a valid
  706. slug (e.g. substituting dashes for spaces and lowercasing ASCII letters).
  707. Prepopulated fields aren't modified by JavaScript after a value has been
  708. saved. It's usually undesired that slugs change (which would cause an
  709. object's URL to change if the slug is used in it).
  710. ``prepopulated_fields`` doesn't accept ``DateTimeField``, ``ForeignKey``,
  711. ``OneToOneField``, and ``ManyToManyField`` fields.
  712. .. attribute:: ModelAdmin.preserve_filters
  713. By default, applied filters are preserved on the list view after creating,
  714. editing, or deleting an object. You can have filters cleared by setting
  715. this attribute to ``False``.
  716. .. attribute:: ModelAdmin.show_facets
  717. Controls whether facet counts are displayed for filters in the admin
  718. changelist. Defaults to :attr:`.ShowFacets.ALLOW`.
  719. When displayed, facet counts update in line with currently applied filters.
  720. .. class:: ShowFacets
  721. Enum of allowed values for :attr:`.ModelAdmin.show_facets`.
  722. .. attribute:: ALWAYS
  723. Always show facet counts.
  724. .. attribute:: ALLOW
  725. Show facet counts when the ``_facets`` query string parameter is
  726. provided.
  727. .. attribute:: NEVER
  728. Never show facet counts.
  729. Set ``show_facets`` to the desired :class:`.ShowFacets` value. For example,
  730. to always show facet counts without needing to provide the query
  731. parameter::
  732. from django.contrib import admin
  733. class MyModelAdmin(admin.ModelAdmin):
  734. ...
  735. # Have facets always shown for this model admin.
  736. show_facets = admin.ShowFacets.ALWAYS
  737. .. admonition:: Performance considerations with facets
  738. Enabling facet filters will increase the number of queries on the admin
  739. changelist page in line with the number of filters. These queries may
  740. cause performance problems, especially for large datasets. In these
  741. cases it may be appropriate to set ``show_facets`` to
  742. :attr:`.ShowFacets.NEVER` to disable faceting entirely.
  743. .. attribute:: ModelAdmin.radio_fields
  744. By default, Django's admin uses a select-box interface (<select>) for
  745. fields that are ``ForeignKey`` or have ``choices`` set. If a field is
  746. present in ``radio_fields``, Django will use a radio-button interface
  747. instead. Assuming ``group`` is a ``ForeignKey`` on the ``Person`` model::
  748. class PersonAdmin(admin.ModelAdmin):
  749. radio_fields = {"group": admin.VERTICAL}
  750. You have the choice of using ``HORIZONTAL`` or ``VERTICAL`` from the
  751. ``django.contrib.admin`` module.
  752. Don't include a field in ``radio_fields`` unless it's a ``ForeignKey`` or has
  753. ``choices`` set.
  754. .. attribute:: ModelAdmin.autocomplete_fields
  755. ``autocomplete_fields`` is a list of ``ForeignKey`` and/or
  756. ``ManyToManyField`` fields you would like to change to `Select2
  757. <https://select2.org/>`_ autocomplete inputs.
  758. By default, the admin uses a select-box interface (``<select>``) for
  759. those fields. Sometimes you don't want to incur the overhead of selecting
  760. all the related instances to display in the dropdown.
  761. The Select2 input looks similar to the default input but comes with a
  762. search feature that loads the options asynchronously. This is faster and
  763. more user-friendly if the related model has many instances.
  764. You must define :attr:`~ModelAdmin.search_fields` on the related object's
  765. ``ModelAdmin`` because the autocomplete search uses it.
  766. To avoid unauthorized data disclosure, users must have the ``view`` or
  767. ``change`` permission to the related object in order to use autocomplete.
  768. Ordering and pagination of the results are controlled by the related
  769. ``ModelAdmin``'s :meth:`~ModelAdmin.get_ordering` and
  770. :meth:`~ModelAdmin.get_paginator` methods.
  771. In the following example, ``ChoiceAdmin`` has an autocomplete field for the
  772. ``ForeignKey`` to the ``Question``. The results are filtered by the
  773. ``question_text`` field and ordered by the ``date_created`` field::
  774. class QuestionAdmin(admin.ModelAdmin):
  775. ordering = ["date_created"]
  776. search_fields = ["question_text"]
  777. class ChoiceAdmin(admin.ModelAdmin):
  778. autocomplete_fields = ["question"]
  779. .. admonition:: Performance considerations for large datasets
  780. Ordering using :attr:`ModelAdmin.ordering` may cause performance
  781. problems as sorting on a large queryset will be slow.
  782. Also, if your search fields include fields that aren't indexed by the
  783. database, you might encounter poor performance on extremely large
  784. tables.
  785. For those cases, it's a good idea to write your own
  786. :func:`ModelAdmin.get_search_results` implementation using a
  787. full-text indexed search.
  788. You may also want to change the ``Paginator`` on very large tables
  789. as the default paginator always performs a ``count()`` query.
  790. For example, you could override the default implementation of the
  791. ``Paginator.count`` property.
  792. .. attribute:: ModelAdmin.raw_id_fields
  793. By default, Django's admin uses a select-box interface (<select>) for
  794. fields that are ``ForeignKey``. Sometimes you don't want to incur the
  795. overhead of having to select all the related instances to display in the
  796. drop-down.
  797. ``raw_id_fields`` is a list of fields you would like to change
  798. into an ``Input`` widget for either a ``ForeignKey`` or
  799. ``ManyToManyField``::
  800. class ArticleAdmin(admin.ModelAdmin):
  801. raw_id_fields = ["newspaper"]
  802. The ``raw_id_fields`` ``Input`` widget should contain a primary key if the
  803. field is a ``ForeignKey`` or a comma separated list of values if the field
  804. is a ``ManyToManyField``. The ``raw_id_fields`` widget shows a magnifying
  805. glass button next to the field which allows users to search for and select
  806. a value:
  807. .. image:: _images/raw_id_fields.png
  808. .. attribute:: ModelAdmin.readonly_fields
  809. By default the admin shows all fields as editable. Any fields in this
  810. option (which should be a ``list`` or ``tuple``) will display its data
  811. as-is and non-editable; they are also excluded from the
  812. :class:`~django.forms.ModelForm` used for creating and editing. Note that
  813. when specifying :attr:`ModelAdmin.fields` or :attr:`ModelAdmin.fieldsets`
  814. the read-only fields must be present to be shown (they are ignored
  815. otherwise).
  816. If ``readonly_fields`` is used without defining explicit ordering through
  817. :attr:`ModelAdmin.fields` or :attr:`ModelAdmin.fieldsets` they will be
  818. added last after all editable fields.
  819. A read-only field can not only display data from a model's field, it can
  820. also display the output of a model's method or a method of the
  821. ``ModelAdmin`` class itself. This is very similar to the way
  822. :attr:`ModelAdmin.list_display` behaves. This provides a way to use the
  823. admin interface to provide feedback on the status of the objects being
  824. edited, for example::
  825. from django.contrib import admin
  826. from django.utils.html import format_html_join
  827. from django.utils.safestring import mark_safe
  828. class PersonAdmin(admin.ModelAdmin):
  829. readonly_fields = ["address_report"]
  830. # description functions like a model field's verbose_name
  831. @admin.display(description="Address")
  832. def address_report(self, instance):
  833. # assuming get_full_address() returns a list of strings
  834. # for each line of the address and you want to separate each
  835. # line by a linebreak
  836. return format_html_join(
  837. mark_safe("<br>"),
  838. "{}",
  839. ((line,) for line in instance.get_full_address()),
  840. ) or mark_safe("<span class='errors'>I can't determine this address.</span>")
  841. .. attribute:: ModelAdmin.save_as
  842. Set ``save_as`` to enable a "save as new" feature on admin change forms.
  843. Normally, objects have three save options: "Save", "Save and continue
  844. editing", and "Save and add another". If ``save_as`` is ``True``, "Save
  845. and add another" will be replaced by a "Save as new" button that creates a
  846. new object (with a new ID) rather than updating the existing object.
  847. By default, ``save_as`` is set to ``False``.
  848. .. attribute:: ModelAdmin.save_as_continue
  849. When :attr:`save_as=True <save_as>`, the default redirect after saving the
  850. new object is to the change view for that object. If you set
  851. ``save_as_continue=False``, the redirect will be to the changelist view.
  852. By default, ``save_as_continue`` is set to ``True``.
  853. .. attribute:: ModelAdmin.save_on_top
  854. Set ``save_on_top`` to add save buttons across the top of your admin change
  855. forms.
  856. Normally, the save buttons appear only at the bottom of the forms. If you
  857. set ``save_on_top``, the buttons will appear both on the top and the
  858. bottom.
  859. By default, ``save_on_top`` is set to ``False``.
  860. .. attribute:: ModelAdmin.search_fields
  861. Set ``search_fields`` to enable a search box on the admin change list page.
  862. This should be set to a list of field names that will be searched whenever
  863. somebody submits a search query in that text box.
  864. These fields should be some kind of text field, such as ``CharField`` or
  865. ``TextField``. You can also perform a related lookup on a ``ForeignKey`` or
  866. ``ManyToManyField`` with the lookup API "follow" notation::
  867. search_fields = ["foreign_key__related_fieldname"]
  868. For example, if you have a blog entry with an author, the following
  869. definition would enable searching blog entries by the email address of the
  870. author::
  871. search_fields = ["user__email"]
  872. When somebody does a search in the admin search box, Django splits the
  873. search query into words and returns all objects that contain each of the
  874. words, case-insensitive (using the :lookup:`icontains` lookup), where each
  875. word must be in at least one of ``search_fields``. For example, if
  876. ``search_fields`` is set to ``['first_name', 'last_name']`` and a user
  877. searches for ``john lennon``, Django will do the equivalent of this SQL
  878. ``WHERE`` clause:
  879. .. code-block:: sql
  880. WHERE (first_name ILIKE '%john%' OR last_name ILIKE '%john%')
  881. AND (first_name ILIKE '%lennon%' OR last_name ILIKE '%lennon%')
  882. The search query can contain quoted phrases with spaces. For example, if a
  883. user searches for ``"john winston"`` or ``'john winston'``, Django will do
  884. the equivalent of this SQL ``WHERE`` clause:
  885. .. code-block:: sql
  886. WHERE (first_name ILIKE '%john winston%' OR last_name ILIKE '%john winston%')
  887. If you don't want to use ``icontains`` as the lookup, you can use any
  888. lookup by appending it the field. For example, you could use :lookup:`exact`
  889. by setting ``search_fields`` to ``['first_name__exact']``.
  890. Some (older) shortcuts for specifying a field lookup are also available.
  891. You can prefix a field in ``search_fields`` with the following characters
  892. and it's equivalent to adding ``__<lookup>`` to the field:
  893. ====== ====================
  894. Prefix Lookup
  895. ====== ====================
  896. ^ :lookup:`istartswith`
  897. = :lookup:`iexact`
  898. @ :lookup:`search`
  899. None :lookup:`icontains`
  900. ====== ====================
  901. If you need to customize search you can use
  902. :meth:`ModelAdmin.get_search_results` to provide additional or alternate
  903. search behavior.
  904. .. attribute:: ModelAdmin.search_help_text
  905. Set ``search_help_text`` to specify a descriptive text for the search box
  906. which will be displayed below it.
  907. .. attribute:: ModelAdmin.show_full_result_count
  908. Set ``show_full_result_count`` to control whether the full count of objects
  909. should be displayed on a filtered admin page (e.g. ``99 results (103 total)``).
  910. If this option is set to ``False``, a text like ``99 results (Show all)``
  911. is displayed instead.
  912. The default of ``show_full_result_count=True`` generates a query to perform
  913. a full count on the table which can be expensive if the table contains a
  914. large number of rows.
  915. .. attribute:: ModelAdmin.sortable_by
  916. By default, the change list page allows sorting by all model fields (and
  917. callables that use the ``ordering`` argument to the
  918. :func:`~django.contrib.admin.display` decorator or have the
  919. ``admin_order_field`` attribute) specified in :attr:`list_display`.
  920. If you want to disable sorting for some columns, set ``sortable_by`` to
  921. a collection (e.g. ``list``, ``tuple``, or ``set``) of the subset of
  922. :attr:`list_display` that you want to be sortable. An empty collection
  923. disables sorting for all columns.
  924. If you need to specify this list dynamically, implement a
  925. :meth:`~ModelAdmin.get_sortable_by` method instead.
  926. .. attribute:: ModelAdmin.view_on_site
  927. Set ``view_on_site`` to control whether or not to display the "View on site" link.
  928. This link should bring you to a URL where you can display the saved object.
  929. This value can be either a boolean flag or a callable. If ``True`` (the
  930. default), the object's :meth:`~django.db.models.Model.get_absolute_url`
  931. method will be used to generate the url.
  932. If your model has a :meth:`~django.db.models.Model.get_absolute_url` method
  933. but you don't want the "View on site" button to appear, you only need to set
  934. ``view_on_site`` to ``False``::
  935. from django.contrib import admin
  936. class PersonAdmin(admin.ModelAdmin):
  937. view_on_site = False
  938. In case it is a callable, it accepts the model instance as a parameter.
  939. For example::
  940. from django.contrib import admin
  941. from django.urls import reverse
  942. class PersonAdmin(admin.ModelAdmin):
  943. def view_on_site(self, obj):
  944. url = reverse("person-detail", kwargs={"slug": obj.slug})
  945. return "https://example.com" + url
  946. Custom template options
  947. ~~~~~~~~~~~~~~~~~~~~~~~
  948. The :ref:`admin-overriding-templates` section describes how to override or extend
  949. the default admin templates. Use the following options to override the default
  950. templates used by the :class:`ModelAdmin` views:
  951. .. attribute:: ModelAdmin.add_form_template
  952. Path to a custom template, used by :meth:`add_view`.
  953. .. attribute:: ModelAdmin.change_form_template
  954. Path to a custom template, used by :meth:`change_view`.
  955. .. attribute:: ModelAdmin.change_list_template
  956. Path to a custom template, used by :meth:`changelist_view`.
  957. .. attribute:: ModelAdmin.delete_confirmation_template
  958. Path to a custom template, used by :meth:`delete_view` for displaying a
  959. confirmation page when deleting one or more objects.
  960. .. attribute:: ModelAdmin.delete_selected_confirmation_template
  961. Path to a custom template, used by the ``delete_selected`` action method
  962. for displaying a confirmation page when deleting one or more objects. See
  963. the :doc:`actions documentation</ref/contrib/admin/actions>`.
  964. .. attribute:: ModelAdmin.object_history_template
  965. Path to a custom template, used by :meth:`history_view`.
  966. .. attribute:: ModelAdmin.popup_response_template
  967. Path to a custom template, used by :meth:`response_add`,
  968. :meth:`response_change`, and :meth:`response_delete`.
  969. .. _model-admin-methods:
  970. ``ModelAdmin`` methods
  971. ----------------------
  972. .. warning::
  973. When overriding :meth:`ModelAdmin.save_model` and
  974. :meth:`ModelAdmin.delete_model`, your code must save/delete the
  975. object. They aren't meant for veto purposes, rather they allow you to
  976. perform extra operations.
  977. .. method:: ModelAdmin.save_model(request, obj, form, change)
  978. The ``save_model`` method is given the ``HttpRequest``, a model instance,
  979. a ``ModelForm`` instance, and a boolean value based on whether it is adding
  980. or changing the object. Overriding this method allows doing pre- or
  981. post-save operations. Call ``super().save_model()`` to save the object
  982. using :meth:`.Model.save`.
  983. For example to attach ``request.user`` to the object prior to saving::
  984. from django.contrib import admin
  985. class ArticleAdmin(admin.ModelAdmin):
  986. def save_model(self, request, obj, form, change):
  987. obj.user = request.user
  988. super().save_model(request, obj, form, change)
  989. .. method:: ModelAdmin.delete_model(request, obj)
  990. The ``delete_model`` method is given the ``HttpRequest`` and a model
  991. instance. Overriding this method allows doing pre- or post-delete
  992. operations. Call ``super().delete_model()`` to delete the object using
  993. :meth:`.Model.delete`.
  994. .. method:: ModelAdmin.delete_queryset(request, queryset)
  995. The ``delete_queryset()`` method is given the ``HttpRequest`` and a
  996. ``QuerySet`` of objects to be deleted. Override this method to customize
  997. the deletion process for the "delete selected objects" :doc:`action
  998. <actions>`.
  999. .. method:: ModelAdmin.save_formset(request, form, formset, change)
  1000. The ``save_formset`` method is given the ``HttpRequest``, the parent
  1001. ``ModelForm`` instance and a boolean value based on whether it is adding or
  1002. changing the parent object.
  1003. For example, to attach ``request.user`` to each changed formset
  1004. model instance::
  1005. class ArticleAdmin(admin.ModelAdmin):
  1006. def save_formset(self, request, form, formset, change):
  1007. instances = formset.save(commit=False)
  1008. for obj in formset.deleted_objects:
  1009. obj.delete()
  1010. for instance in instances:
  1011. instance.user = request.user
  1012. instance.save()
  1013. formset.save_m2m()
  1014. See also :ref:`saving-objects-in-the-formset`.
  1015. .. warning::
  1016. All hooks that return a ``ModelAdmin`` property return the property itself
  1017. rather than a copy of its value. Dynamically modifying the value can lead
  1018. to surprising results.
  1019. Let's take :meth:`ModelAdmin.get_readonly_fields` as an example::
  1020. class PersonAdmin(admin.ModelAdmin):
  1021. readonly_fields = ["name"]
  1022. def get_readonly_fields(self, request, obj=None):
  1023. readonly = super().get_readonly_fields(request, obj)
  1024. if not request.user.is_superuser:
  1025. readonly.append("age") # Edits the class attribute.
  1026. return readonly
  1027. This results in ``readonly_fields`` becoming
  1028. ``["name", "age", "age", ...]``, even for a superuser, as ``"age"`` is added
  1029. each time non-superuser visits the page.
  1030. .. method:: ModelAdmin.get_ordering(request)
  1031. The ``get_ordering`` method takes a ``request`` as parameter and
  1032. is expected to return a ``list`` or ``tuple`` for ordering similar
  1033. to the :attr:`ordering` attribute. For example::
  1034. class PersonAdmin(admin.ModelAdmin):
  1035. def get_ordering(self, request):
  1036. if request.user.is_superuser:
  1037. return ["name", "rank"]
  1038. else:
  1039. return ["name"]
  1040. .. method:: ModelAdmin.get_search_results(request, queryset, search_term)
  1041. The ``get_search_results`` method modifies the list of objects displayed
  1042. into those that match the provided search term. It accepts the request, a
  1043. queryset that applies the current filters, and the user-provided search term.
  1044. It returns a tuple containing a queryset modified to implement the search, and
  1045. a boolean indicating if the results may contain duplicates.
  1046. The default implementation searches the fields named in :attr:`ModelAdmin.search_fields`.
  1047. This method may be overridden with your own custom search method. For
  1048. example, you might wish to search by an integer field, or use an external
  1049. tool such as `Solr`_ or `Haystack`_. You must establish if the queryset
  1050. changes implemented by your search method may introduce duplicates into the
  1051. results, and return ``True`` in the second element of the return value.
  1052. For example, to search by ``name`` and ``age``, you could use::
  1053. class PersonAdmin(admin.ModelAdmin):
  1054. list_display = ["name", "age"]
  1055. search_fields = ["name"]
  1056. def get_search_results(self, request, queryset, search_term):
  1057. queryset, may_have_duplicates = super().get_search_results(
  1058. request,
  1059. queryset,
  1060. search_term,
  1061. )
  1062. try:
  1063. search_term_as_int = int(search_term)
  1064. except ValueError:
  1065. pass
  1066. else:
  1067. queryset |= self.model.objects.filter(age=search_term_as_int)
  1068. return queryset, may_have_duplicates
  1069. This implementation is more efficient than ``search_fields =
  1070. ('name', '=age')`` which results in a string comparison for the numeric
  1071. field, for example ``... OR UPPER("polls_choice"."votes"::text) = UPPER('4')``
  1072. on PostgreSQL.
  1073. .. _Solr: https://solr.apache.org
  1074. .. _Haystack: https://haystacksearch.org
  1075. .. method:: ModelAdmin.save_related(request, form, formsets, change)
  1076. The ``save_related`` method is given the ``HttpRequest``, the parent
  1077. ``ModelForm`` instance, the list of inline formsets and a boolean value
  1078. based on whether the parent is being added or changed. Here you can do any
  1079. pre- or post-save operations for objects related to the parent. Note
  1080. that at this point the parent object and its form have already been saved.
  1081. .. method:: ModelAdmin.get_autocomplete_fields(request)
  1082. The ``get_autocomplete_fields()`` method is given the ``HttpRequest`` and is
  1083. expected to return a ``list`` or ``tuple`` of field names that will be
  1084. displayed with an autocomplete widget as described above in the
  1085. :attr:`ModelAdmin.autocomplete_fields` section.
  1086. .. method:: ModelAdmin.get_readonly_fields(request, obj=None)
  1087. The ``get_readonly_fields`` method is given the ``HttpRequest`` and the
  1088. ``obj`` being edited (or ``None`` on an add form) and is expected to return
  1089. a ``list`` or ``tuple`` of field names that will be displayed as read-only,
  1090. as described above in the :attr:`ModelAdmin.readonly_fields` section.
  1091. .. method:: ModelAdmin.get_prepopulated_fields(request, obj=None)
  1092. The ``get_prepopulated_fields`` method is given the ``HttpRequest`` and the
  1093. ``obj`` being edited (or ``None`` on an add form) and is expected to return
  1094. a ``dictionary``, as described above in the :attr:`ModelAdmin.prepopulated_fields`
  1095. section.
  1096. .. method:: ModelAdmin.get_list_display(request)
  1097. The ``get_list_display`` method is given the ``HttpRequest`` and is
  1098. expected to return a ``list`` or ``tuple`` of field names that will be
  1099. displayed on the changelist view as described above in the
  1100. :attr:`ModelAdmin.list_display` section.
  1101. .. method:: ModelAdmin.get_list_display_links(request, list_display)
  1102. The ``get_list_display_links`` method is given the ``HttpRequest`` and
  1103. the ``list`` or ``tuple`` returned by :meth:`ModelAdmin.get_list_display`.
  1104. It is expected to return either ``None`` or a ``list`` or ``tuple`` of field
  1105. names on the changelist that will be linked to the change view, as described
  1106. in the :attr:`ModelAdmin.list_display_links` section.
  1107. .. method:: ModelAdmin.get_exclude(request, obj=None)
  1108. The ``get_exclude`` method is given the ``HttpRequest`` and the ``obj``
  1109. being edited (or ``None`` on an add form) and is expected to return a list
  1110. of fields, as described in :attr:`ModelAdmin.exclude`.
  1111. .. method:: ModelAdmin.get_fields(request, obj=None)
  1112. The ``get_fields`` method is given the ``HttpRequest`` and the ``obj``
  1113. being edited (or ``None`` on an add form) and is expected to return a list
  1114. of fields, as described above in the :attr:`ModelAdmin.fields` section.
  1115. .. method:: ModelAdmin.get_fieldsets(request, obj=None)
  1116. The ``get_fieldsets`` method is given the ``HttpRequest`` and the ``obj``
  1117. being edited (or ``None`` on an add form) and is expected to return a list
  1118. of 2-tuples, in which each 2-tuple represents a ``<fieldset>`` on the
  1119. admin form page, as described above in the :attr:`ModelAdmin.fieldsets` section.
  1120. .. method:: ModelAdmin.get_list_filter(request)
  1121. The ``get_list_filter`` method is given the ``HttpRequest`` and is expected
  1122. to return the same kind of sequence type as for the
  1123. :attr:`~ModelAdmin.list_filter` attribute.
  1124. .. method:: ModelAdmin.get_list_select_related(request)
  1125. The ``get_list_select_related`` method is given the ``HttpRequest`` and
  1126. should return a boolean or list as :attr:`ModelAdmin.list_select_related`
  1127. does.
  1128. .. method:: ModelAdmin.get_search_fields(request)
  1129. The ``get_search_fields`` method is given the ``HttpRequest`` and is expected
  1130. to return the same kind of sequence type as for the
  1131. :attr:`~ModelAdmin.search_fields` attribute.
  1132. .. method:: ModelAdmin.get_sortable_by(request)
  1133. The ``get_sortable_by()`` method is passed the ``HttpRequest`` and is
  1134. expected to return a collection (e.g. ``list``, ``tuple``, or ``set``) of
  1135. field names that will be sortable in the change list page.
  1136. Its default implementation returns :attr:`sortable_by` if it's set,
  1137. otherwise it defers to :meth:`get_list_display`.
  1138. For example, to prevent one or more columns from being sortable::
  1139. class PersonAdmin(admin.ModelAdmin):
  1140. def get_sortable_by(self, request):
  1141. return {*self.get_list_display(request)} - {"rank"}
  1142. .. method:: ModelAdmin.get_inline_instances(request, obj=None)
  1143. The ``get_inline_instances`` method is given the ``HttpRequest`` and the
  1144. ``obj`` being edited (or ``None`` on an add form) and is expected to return
  1145. a ``list`` or ``tuple`` of :class:`~django.contrib.admin.InlineModelAdmin`
  1146. objects, as described below in the :class:`~django.contrib.admin.InlineModelAdmin`
  1147. section. For example, the following would return inlines without the default
  1148. filtering based on add, change, delete, and view permissions::
  1149. class MyModelAdmin(admin.ModelAdmin):
  1150. inlines = [MyInline]
  1151. def get_inline_instances(self, request, obj=None):
  1152. return [inline(self.model, self.admin_site) for inline in self.inlines]
  1153. If you override this method, make sure that the returned inlines are
  1154. instances of the classes defined in :attr:`inlines` or you might encounter
  1155. a "Bad Request" error when adding related objects.
  1156. .. method:: ModelAdmin.get_inlines(request, obj)
  1157. The ``get_inlines`` method is given the ``HttpRequest`` and the
  1158. ``obj`` being edited (or ``None`` on an add form) and is expected to return
  1159. an iterable of inlines. You can override this method to dynamically add
  1160. inlines based on the request or model instance instead of specifying them
  1161. in :attr:`ModelAdmin.inlines`.
  1162. .. method:: ModelAdmin.get_urls()
  1163. The ``get_urls`` method on a ``ModelAdmin`` returns the URLs to be used for
  1164. that ModelAdmin in the same way as a URLconf. Therefore you can extend
  1165. them as documented in :doc:`/topics/http/urls`, using the
  1166. ``AdminSite.admin_view()`` wrapper on your views::
  1167. from django.contrib import admin
  1168. from django.template.response import TemplateResponse
  1169. from django.urls import path
  1170. class MyModelAdmin(admin.ModelAdmin):
  1171. def get_urls(self):
  1172. urls = super().get_urls()
  1173. my_urls = [path("my_view/", self.admin_site.admin_view(self.my_view))]
  1174. return my_urls + urls
  1175. def my_view(self, request):
  1176. # ...
  1177. context = dict(
  1178. # Include common variables for rendering the admin template.
  1179. self.admin_site.each_context(request),
  1180. # Anything else you want in the context...
  1181. key=value,
  1182. )
  1183. return TemplateResponse(request, "sometemplate.html", context)
  1184. If you want to use the admin layout, extend from ``admin/base_site.html``:
  1185. .. code-block:: html+django
  1186. {% extends "admin/base_site.html" %}
  1187. {% block content %}
  1188. ...
  1189. {% endblock %}
  1190. .. note::
  1191. Notice how the ``self.my_view`` function is wrapped in
  1192. ``self.admin_site.admin_view``. This is important, since it ensures two
  1193. things:
  1194. #. Permission checks are run, ensuring only active staff users can
  1195. access the view.
  1196. #. The :func:`django.views.decorators.cache.never_cache` decorator is
  1197. applied to prevent caching, ensuring the returned information is
  1198. up-to-date.
  1199. .. note::
  1200. Notice that the custom patterns are included *before* the regular admin
  1201. URLs: the admin URL patterns are very permissive and will match nearly
  1202. anything, so you'll usually want to prepend your custom URLs to the
  1203. built-in ones.
  1204. In this example, ``my_view`` will be accessed at
  1205. ``/admin/myapp/mymodel/my_view/`` (assuming the admin URLs are included
  1206. at ``/admin/``.)
  1207. If the page is cacheable, but you still want the permission check to be
  1208. performed, you can pass a ``cacheable=True`` argument to
  1209. ``AdminSite.admin_view()``::
  1210. path("my_view/", self.admin_site.admin_view(self.my_view, cacheable=True))
  1211. ``ModelAdmin`` views have ``model_admin`` attributes. Other
  1212. ``AdminSite`` views have ``admin_site`` attributes.
  1213. .. method:: ModelAdmin.get_form(request, obj=None, **kwargs)
  1214. Returns a :class:`~django.forms.ModelForm` class for use in the admin add
  1215. and change views, see :meth:`add_view` and :meth:`change_view`.
  1216. The base implementation uses :func:`~django.forms.models.modelform_factory`
  1217. to subclass :attr:`~form`, modified by attributes such as :attr:`~fields`
  1218. and :attr:`~exclude`. So, for example, if you wanted to offer additional
  1219. fields to superusers, you could swap in a different base form like so::
  1220. class MyModelAdmin(admin.ModelAdmin):
  1221. def get_form(self, request, obj=None, **kwargs):
  1222. if request.user.is_superuser:
  1223. kwargs["form"] = MySuperuserForm
  1224. return super().get_form(request, obj, **kwargs)
  1225. You may also return a custom :class:`~django.forms.ModelForm` class
  1226. directly.
  1227. .. method:: ModelAdmin.get_formsets_with_inlines(request, obj=None)
  1228. Yields (``FormSet``, :class:`InlineModelAdmin`) pairs for use in admin add
  1229. and change views.
  1230. For example if you wanted to display a particular inline only in the change
  1231. view, you could override ``get_formsets_with_inlines`` as follows::
  1232. class MyModelAdmin(admin.ModelAdmin):
  1233. inlines = [MyInline, SomeOtherInline]
  1234. def get_formsets_with_inlines(self, request, obj=None):
  1235. for inline in self.get_inline_instances(request, obj):
  1236. # hide MyInline in the add view
  1237. if not isinstance(inline, MyInline) or obj is not None:
  1238. yield inline.get_formset(request, obj), inline
  1239. .. method:: ModelAdmin.formfield_for_foreignkey(db_field, request, **kwargs)
  1240. The ``formfield_for_foreignkey`` method on a ``ModelAdmin`` allows you to
  1241. override the default formfield for a foreign keys field. For example, to
  1242. return a subset of objects for this foreign key field based on the user::
  1243. class MyModelAdmin(admin.ModelAdmin):
  1244. def formfield_for_foreignkey(self, db_field, request, **kwargs):
  1245. if db_field.name == "car":
  1246. kwargs["queryset"] = Car.objects.filter(owner=request.user)
  1247. return super().formfield_for_foreignkey(db_field, request, **kwargs)
  1248. This uses the ``HttpRequest`` instance to filter the ``Car`` foreign key
  1249. field to only display the cars owned by the ``User`` instance.
  1250. For more complex filters, you can use ``ModelForm.__init__()`` method to
  1251. filter based on an ``instance`` of your model (see
  1252. :ref:`fields-which-handle-relationships`). For example::
  1253. class CountryAdminForm(forms.ModelForm):
  1254. def __init__(self, *args, **kwargs):
  1255. super().__init__(*args, **kwargs)
  1256. self.fields["capital"].queryset = self.instance.cities.all()
  1257. class CountryAdmin(admin.ModelAdmin):
  1258. form = CountryAdminForm
  1259. .. method:: ModelAdmin.formfield_for_manytomany(db_field, request, **kwargs)
  1260. Like the ``formfield_for_foreignkey`` method, the
  1261. ``formfield_for_manytomany`` method can be overridden to change the
  1262. default formfield for a many to many field. For example, if an owner can
  1263. own multiple cars and cars can belong to multiple owners -- a many to
  1264. many relationship -- you could filter the ``Car`` foreign key field to
  1265. only display the cars owned by the ``User``::
  1266. class MyModelAdmin(admin.ModelAdmin):
  1267. def formfield_for_manytomany(self, db_field, request, **kwargs):
  1268. if db_field.name == "cars":
  1269. kwargs["queryset"] = Car.objects.filter(owner=request.user)
  1270. return super().formfield_for_manytomany(db_field, request, **kwargs)
  1271. .. method:: ModelAdmin.formfield_for_choice_field(db_field, request, **kwargs)
  1272. Like the ``formfield_for_foreignkey`` and ``formfield_for_manytomany``
  1273. methods, the ``formfield_for_choice_field`` method can be overridden to
  1274. change the default formfield for a field that has declared choices. For
  1275. example, if the choices available to a superuser should be different than
  1276. those available to regular staff, you could proceed as follows::
  1277. class MyModelAdmin(admin.ModelAdmin):
  1278. def formfield_for_choice_field(self, db_field, request, **kwargs):
  1279. if db_field.name == "status":
  1280. kwargs["choices"] = [
  1281. ("accepted", "Accepted"),
  1282. ("denied", "Denied"),
  1283. ]
  1284. if request.user.is_superuser:
  1285. kwargs["choices"].append(("ready", "Ready for deployment"))
  1286. return super().formfield_for_choice_field(db_field, request, **kwargs)
  1287. .. admonition:: ``choices`` limitations
  1288. Any ``choices`` attribute set on the formfield will be limited to the
  1289. form field only. If the corresponding field on the model has choices
  1290. set, the choices provided to the form must be a valid subset of those
  1291. choices, otherwise the form submission will fail with
  1292. a :exc:`~django.core.exceptions.ValidationError` when the model itself
  1293. is validated before saving.
  1294. .. method:: ModelAdmin.get_changelist(request, **kwargs)
  1295. Returns the ``Changelist`` class to be used for listing. By default,
  1296. ``django.contrib.admin.views.main.ChangeList`` is used. By inheriting this
  1297. class you can change the behavior of the listing.
  1298. .. method:: ModelAdmin.get_changelist_form(request, **kwargs)
  1299. Returns a :class:`~django.forms.ModelForm` class for use in the ``Formset``
  1300. on the changelist page. To use a custom form, for example::
  1301. from django import forms
  1302. class MyForm(forms.ModelForm):
  1303. pass
  1304. class MyModelAdmin(admin.ModelAdmin):
  1305. def get_changelist_form(self, request, **kwargs):
  1306. return MyForm
  1307. .. admonition:: Omit the ``Meta.model`` attribute
  1308. If you define the ``Meta.model`` attribute on a
  1309. :class:`~django.forms.ModelForm`, you must also define the
  1310. ``Meta.fields`` attribute (or the ``Meta.exclude`` attribute). However,
  1311. ``ModelAdmin`` ignores this value, overriding it with the
  1312. :attr:`ModelAdmin.list_editable` attribute. The easiest solution is to
  1313. omit the ``Meta.model`` attribute, since ``ModelAdmin`` will provide the
  1314. correct model to use.
  1315. .. method:: ModelAdmin.get_changelist_formset(request, **kwargs)
  1316. Returns a :ref:`ModelFormSet <model-formsets>` class for use on the
  1317. changelist page if :attr:`~ModelAdmin.list_editable` is used. To use a
  1318. custom formset, for example::
  1319. from django.forms import BaseModelFormSet
  1320. class MyAdminFormSet(BaseModelFormSet):
  1321. pass
  1322. class MyModelAdmin(admin.ModelAdmin):
  1323. def get_changelist_formset(self, request, **kwargs):
  1324. kwargs["formset"] = MyAdminFormSet
  1325. return super().get_changelist_formset(request, **kwargs)
  1326. .. method:: ModelAdmin.lookup_allowed(lookup, value, request)
  1327. The objects in the changelist page can be filtered with lookups from the
  1328. URL's query string. This is how :attr:`list_filter` works, for example. The
  1329. lookups are similar to what's used in :meth:`.QuerySet.filter` (e.g.
  1330. ``user__email=user@example.com``). Since the lookups in the query string
  1331. can be manipulated by the user, they must be sanitized to prevent
  1332. unauthorized data exposure.
  1333. The ``lookup_allowed()`` method is given a lookup path from the query string
  1334. (e.g. ``'user__email'``), the corresponding value
  1335. (e.g. ``'user@example.com'``), and the request, and returns a boolean
  1336. indicating whether filtering the changelist's ``QuerySet`` using the
  1337. parameters is permitted. If ``lookup_allowed()`` returns ``False``,
  1338. ``DisallowedModelAdminLookup``
  1339. (subclass of :exc:`~django.core.exceptions.SuspiciousOperation`) is raised.
  1340. By default, ``lookup_allowed()`` allows access to a model's local fields,
  1341. field paths used in :attr:`~ModelAdmin.list_filter` (but not paths from
  1342. :meth:`~ModelAdmin.get_list_filter`), and lookups required for
  1343. :attr:`~django.db.models.ForeignKey.limit_choices_to` to function
  1344. correctly in :attr:`~django.contrib.admin.ModelAdmin.raw_id_fields`.
  1345. Override this method to customize the lookups permitted for your
  1346. :class:`~django.contrib.admin.ModelAdmin` subclass.
  1347. .. method:: ModelAdmin.has_view_permission(request, obj=None)
  1348. Should return ``True`` if viewing ``obj`` is permitted, ``False`` otherwise.
  1349. If obj is ``None``, should return ``True`` or ``False`` to indicate whether
  1350. viewing of objects of this type is permitted in general (e.g., ``False``
  1351. will be interpreted as meaning that the current user is not permitted to
  1352. view any object of this type).
  1353. The default implementation returns ``True`` if the user has either the
  1354. "change" or "view" permission.
  1355. .. method:: ModelAdmin.has_add_permission(request)
  1356. Should return ``True`` if adding an object is permitted, ``False``
  1357. otherwise.
  1358. .. method:: ModelAdmin.has_change_permission(request, obj=None)
  1359. Should return ``True`` if editing ``obj`` is permitted, ``False``
  1360. otherwise. If ``obj`` is ``None``, should return ``True`` or ``False`` to
  1361. indicate whether editing of objects of this type is permitted in general
  1362. (e.g., ``False`` will be interpreted as meaning that the current user is
  1363. not permitted to edit any object of this type).
  1364. .. method:: ModelAdmin.has_delete_permission(request, obj=None)
  1365. Should return ``True`` if deleting ``obj`` is permitted, ``False``
  1366. otherwise. If ``obj`` is ``None``, should return ``True`` or ``False`` to
  1367. indicate whether deleting objects of this type is permitted in general
  1368. (e.g., ``False`` will be interpreted as meaning that the current user is
  1369. not permitted to delete any object of this type).
  1370. .. method:: ModelAdmin.has_module_permission(request)
  1371. Should return ``True`` if displaying the module on the admin index page and
  1372. accessing the module's index page is permitted, ``False`` otherwise.
  1373. Uses :meth:`User.has_module_perms()
  1374. <django.contrib.auth.models.User.has_module_perms>` by default. Overriding
  1375. it does not restrict access to the view, add, change, or delete views,
  1376. :meth:`~ModelAdmin.has_view_permission`,
  1377. :meth:`~ModelAdmin.has_add_permission`,
  1378. :meth:`~ModelAdmin.has_change_permission`, and
  1379. :meth:`~ModelAdmin.has_delete_permission` should be used for that.
  1380. .. method:: ModelAdmin.get_queryset(request)
  1381. The ``get_queryset`` method on a ``ModelAdmin`` returns a
  1382. :class:`~django.db.models.query.QuerySet` of all model instances that
  1383. can be edited by the admin site. One use case for overriding this method
  1384. is to show objects owned by the logged-in user::
  1385. class MyModelAdmin(admin.ModelAdmin):
  1386. def get_queryset(self, request):
  1387. qs = super().get_queryset(request)
  1388. if request.user.is_superuser:
  1389. return qs
  1390. return qs.filter(author=request.user)
  1391. .. method:: ModelAdmin.message_user(request, message, level=messages.INFO, extra_tags='', fail_silently=False)
  1392. Sends a message to the user using the :mod:`django.contrib.messages`
  1393. backend. See the :ref:`custom ModelAdmin example <custom-admin-action>`.
  1394. Keyword arguments allow you to change the message level, add extra CSS
  1395. tags, or fail silently if the ``contrib.messages`` framework is not
  1396. installed. These keyword arguments match those for
  1397. :func:`django.contrib.messages.add_message`, see that function's
  1398. documentation for more details. One difference is that the level may be
  1399. passed as a string label in addition to integer/constant.
  1400. .. method:: ModelAdmin.get_paginator(request, queryset, per_page, orphans=0, allow_empty_first_page=True)
  1401. Returns an instance of the paginator to use for this view. By default,
  1402. instantiates an instance of :attr:`paginator`.
  1403. .. method:: ModelAdmin.response_add(request, obj, post_url_continue=None)
  1404. Determines the :class:`~django.http.HttpResponse` for the
  1405. :meth:`add_view` stage.
  1406. ``response_add`` is called after the admin form is submitted and
  1407. just after the object and all the related instances have
  1408. been created and saved. You can override it to change the default behavior
  1409. after the object has been created.
  1410. .. method:: ModelAdmin.response_change(request, obj)
  1411. Determines the :class:`~django.http.HttpResponse` for the
  1412. :meth:`change_view` stage.
  1413. ``response_change`` is called after the admin form is submitted and
  1414. just after the object and all the related instances have
  1415. been saved. You can override it to change the default
  1416. behavior after the object has been changed.
  1417. .. method:: ModelAdmin.response_delete(request, obj_display, obj_id)
  1418. Determines the :class:`~django.http.HttpResponse` for the
  1419. :meth:`delete_view` stage.
  1420. ``response_delete`` is called after the object has been
  1421. deleted. You can override it to change the default
  1422. behavior after the object has been deleted.
  1423. ``obj_display`` is a string with the name of the deleted
  1424. object.
  1425. ``obj_id`` is the serialized identifier used to retrieve the object to be
  1426. deleted.
  1427. .. method:: ModelAdmin.get_formset_kwargs(request, obj, inline, prefix)
  1428. A hook for customizing the keyword arguments passed to the constructor of a
  1429. formset. For example, to pass ``request`` to formset forms::
  1430. class MyModelAdmin(admin.ModelAdmin):
  1431. def get_formset_kwargs(self, request, obj, inline, prefix):
  1432. return {
  1433. **super().get_formset_kwargs(request, obj, inline, prefix),
  1434. "form_kwargs": {"request": request},
  1435. }
  1436. You can also use it to set ``initial`` for formset forms.
  1437. .. method:: ModelAdmin.get_changeform_initial_data(request)
  1438. A hook for the initial data on admin change forms. By default, fields are
  1439. given initial values from ``GET`` parameters. For instance,
  1440. ``?name=initial_value`` will set the ``name`` field's initial value to be
  1441. ``initial_value``.
  1442. This method should return a dictionary in the form
  1443. ``{'fieldname': 'fieldval'}``::
  1444. def get_changeform_initial_data(self, request):
  1445. return {"name": "custom_initial_value"}
  1446. .. method:: ModelAdmin.get_deleted_objects(objs, request)
  1447. A hook for customizing the deletion process of the :meth:`delete_view` and
  1448. the "delete selected" :doc:`action <actions>`.
  1449. The ``objs`` argument is a homogeneous iterable of objects (a ``QuerySet``
  1450. or a list of model instances) to be deleted, and ``request`` is the
  1451. :class:`~django.http.HttpRequest`.
  1452. This method must return a 4-tuple of
  1453. ``(deleted_objects, model_count, perms_needed, protected)``.
  1454. ``deleted_objects`` is a list of strings representing all the objects that
  1455. will be deleted. If there are any related objects to be deleted, the list
  1456. is nested and includes those related objects. The list is formatted in the
  1457. template using the :tfilter:`unordered_list` filter.
  1458. ``model_count`` is a dictionary mapping each model's
  1459. :attr:`~django.db.models.Options.verbose_name_plural` to the number of
  1460. objects that will be deleted.
  1461. ``perms_needed`` is a set of :attr:`~django.db.models.Options.verbose_name`\s
  1462. of the models that the user doesn't have permission to delete.
  1463. ``protected`` is a list of strings representing of all the protected
  1464. related objects that can't be deleted. The list is displayed in the
  1465. template.
  1466. Other methods
  1467. ~~~~~~~~~~~~~
  1468. .. method:: ModelAdmin.add_view(request, form_url='', extra_context=None)
  1469. Django view for the model instance addition page. See note below.
  1470. .. method:: ModelAdmin.change_view(request, object_id, form_url='', extra_context=None)
  1471. Django view for the model instance editing page. See note below.
  1472. .. method:: ModelAdmin.changelist_view(request, extra_context=None)
  1473. Django view for the model instances change list/actions page. See note
  1474. below.
  1475. .. method:: ModelAdmin.delete_view(request, object_id, extra_context=None)
  1476. Django view for the model instance(s) deletion confirmation page. See note
  1477. below.
  1478. .. method:: ModelAdmin.history_view(request, object_id, extra_context=None)
  1479. Django view for the page that shows the modification history for a given
  1480. model instance.
  1481. Unlike the hook-type ``ModelAdmin`` methods detailed in the previous section,
  1482. these five methods are in reality designed to be invoked as Django views from
  1483. the admin application URL dispatching handler to render the pages that deal
  1484. with model instances CRUD operations. As a result, completely overriding these
  1485. methods will significantly change the behavior of the admin application.
  1486. One common reason for overriding these methods is to augment the context data
  1487. that is provided to the template that renders the view. In the following
  1488. example, the change view is overridden so that the rendered template is
  1489. provided some extra mapping data that would not otherwise be available::
  1490. class MyModelAdmin(admin.ModelAdmin):
  1491. # A template for a very customized change view:
  1492. change_form_template = "admin/myapp/extras/openstreetmap_change_form.html"
  1493. def get_osm_info(self):
  1494. # ...
  1495. pass
  1496. def change_view(self, request, object_id, form_url="", extra_context=None):
  1497. extra_context = extra_context or {}
  1498. extra_context["osm_data"] = self.get_osm_info()
  1499. return super().change_view(
  1500. request,
  1501. object_id,
  1502. form_url,
  1503. extra_context=extra_context,
  1504. )
  1505. These views return :class:`~django.template.response.TemplateResponse`
  1506. instances which allow you to easily customize the response data before
  1507. rendering. For more details, see the :doc:`TemplateResponse documentation
  1508. </ref/template-response>`.
  1509. .. _modeladmin-asset-definitions:
  1510. ``ModelAdmin`` asset definitions
  1511. --------------------------------
  1512. There are times where you would like add a bit of CSS and/or JavaScript to
  1513. the add/change views. This can be accomplished by using a ``Media`` inner class
  1514. on your ``ModelAdmin``::
  1515. class ArticleAdmin(admin.ModelAdmin):
  1516. class Media:
  1517. css = {
  1518. "all": ["my_styles.css"],
  1519. }
  1520. js = ["my_code.js"]
  1521. The :doc:`staticfiles app </ref/contrib/staticfiles>` prepends
  1522. :setting:`STATIC_URL` (or :setting:`MEDIA_URL` if :setting:`STATIC_URL` is
  1523. ``None``) to any asset paths. The same rules apply as :ref:`regular asset
  1524. definitions on forms <form-asset-paths>`.
  1525. .. _contrib-admin-jquery:
  1526. jQuery
  1527. ~~~~~~
  1528. Django admin JavaScript makes use of the `jQuery`_ library.
  1529. To avoid conflicts with user-supplied scripts or libraries, Django's jQuery
  1530. (version 3.7.1) is namespaced as ``django.jQuery``. If you want to use jQuery
  1531. in your own admin JavaScript without including a second copy, you can use the
  1532. ``django.jQuery`` object on changelist and add/edit views. Also, your own admin
  1533. forms or widgets depending on ``django.jQuery`` must specify
  1534. ``js=['admin/js/jquery.init.js', …]`` when :ref:`declaring form media assets
  1535. <assets-as-a-static-definition>`.
  1536. The :class:`ModelAdmin` class requires jQuery by default, so there is no need
  1537. to add jQuery to your ``ModelAdmin``’s list of media resources unless you have
  1538. a specific need. For example, if you require the jQuery library to be in the
  1539. global namespace (for example when using third-party jQuery plugins) or if you
  1540. need a newer version of jQuery, you will have to include your own copy.
  1541. Django provides both uncompressed and 'minified' versions of jQuery, as
  1542. ``jquery.js`` and ``jquery.min.js`` respectively.
  1543. :class:`ModelAdmin` and :class:`InlineModelAdmin` have a ``media`` property
  1544. that returns a list of ``Media`` objects which store paths to the JavaScript
  1545. files for the forms and/or formsets. If :setting:`DEBUG` is ``True`` it will
  1546. return the uncompressed versions of the various JavaScript files, including
  1547. ``jquery.js``; if not, it will return the 'minified' versions.
  1548. .. _jQuery: https://jquery.com
  1549. .. _admin-custom-validation:
  1550. Adding custom validation to the admin
  1551. -------------------------------------
  1552. You can also add custom validation of data in the admin. The automatic admin
  1553. interface reuses :mod:`django.forms`, and the ``ModelAdmin`` class gives you
  1554. the ability to define your own form::
  1555. class ArticleAdmin(admin.ModelAdmin):
  1556. form = MyArticleAdminForm
  1557. ``MyArticleAdminForm`` can be defined anywhere as long as you import where
  1558. needed. Now within your form you can add your own custom validation for
  1559. any field::
  1560. class MyArticleAdminForm(forms.ModelForm):
  1561. def clean_name(self):
  1562. # do something that validates your data
  1563. return self.cleaned_data["name"]
  1564. It is important you use a ``ModelForm`` here otherwise things can break. See
  1565. the :doc:`forms </ref/forms/index>` documentation on :doc:`custom validation
  1566. </ref/forms/validation>` and, more specifically, the
  1567. :ref:`model form validation notes <overriding-modelform-clean-method>` for more
  1568. information.
  1569. .. _admin-inlines:
  1570. ``InlineModelAdmin`` objects
  1571. ============================
  1572. .. class:: InlineModelAdmin
  1573. .. class:: TabularInline
  1574. .. class:: StackedInline
  1575. The admin interface has the ability to edit models on the same page as a
  1576. parent model. These are called inlines. Suppose you have these two models::
  1577. from django.db import models
  1578. class Author(models.Model):
  1579. name = models.CharField(max_length=100)
  1580. class Book(models.Model):
  1581. author = models.ForeignKey(Author, on_delete=models.CASCADE)
  1582. title = models.CharField(max_length=100)
  1583. You can edit the books authored by an author on the author page. You add
  1584. inlines to a model by specifying them in a ``ModelAdmin.inlines``::
  1585. from django.contrib import admin
  1586. from myapp.models import Author, Book
  1587. class BookInline(admin.TabularInline):
  1588. model = Book
  1589. class AuthorAdmin(admin.ModelAdmin):
  1590. inlines = [
  1591. BookInline,
  1592. ]
  1593. admin.site.register(Author, AuthorAdmin)
  1594. Django provides two subclasses of ``InlineModelAdmin`` and they are:
  1595. * :class:`~django.contrib.admin.TabularInline`
  1596. * :class:`~django.contrib.admin.StackedInline`
  1597. The difference between these two is merely the template used to render
  1598. them.
  1599. ``InlineModelAdmin`` options
  1600. -----------------------------
  1601. ``InlineModelAdmin`` shares many of the same features as ``ModelAdmin``, and
  1602. adds some of its own (the shared features are actually defined in the
  1603. ``BaseModelAdmin`` superclass). The shared features are:
  1604. - :attr:`~InlineModelAdmin.form`
  1605. - :attr:`~ModelAdmin.fieldsets`
  1606. - :attr:`~ModelAdmin.fields`
  1607. - :attr:`~ModelAdmin.formfield_overrides`
  1608. - :attr:`~ModelAdmin.exclude`
  1609. - :attr:`~ModelAdmin.filter_horizontal`
  1610. - :attr:`~ModelAdmin.filter_vertical`
  1611. - :attr:`~ModelAdmin.ordering`
  1612. - :attr:`~ModelAdmin.prepopulated_fields`
  1613. - :meth:`~ModelAdmin.get_fieldsets`
  1614. - :meth:`~ModelAdmin.get_queryset`
  1615. - :attr:`~ModelAdmin.radio_fields`
  1616. - :attr:`~ModelAdmin.readonly_fields`
  1617. - :attr:`~InlineModelAdmin.raw_id_fields`
  1618. - :meth:`~ModelAdmin.formfield_for_choice_field`
  1619. - :meth:`~ModelAdmin.formfield_for_foreignkey`
  1620. - :meth:`~ModelAdmin.formfield_for_manytomany`
  1621. - :meth:`~ModelAdmin.has_module_permission`
  1622. The ``InlineModelAdmin`` class adds or customizes:
  1623. .. attribute:: InlineModelAdmin.model
  1624. The model which the inline is using. This is required.
  1625. .. attribute:: InlineModelAdmin.fk_name
  1626. The name of the foreign key on the model. In most cases this will be dealt
  1627. with automatically, but ``fk_name`` must be specified explicitly if there
  1628. are more than one foreign key to the same parent model.
  1629. .. attribute:: InlineModelAdmin.formset
  1630. This defaults to :class:`~django.forms.models.BaseInlineFormSet`. Using
  1631. your own formset can give you many possibilities of customization. Inlines
  1632. are built around :ref:`model formsets <model-formsets>`.
  1633. .. attribute:: InlineModelAdmin.form
  1634. The value for ``form`` defaults to ``ModelForm``. This is what is passed
  1635. through to :func:`~django.forms.models.inlineformset_factory` when
  1636. creating the formset for this inline.
  1637. .. warning::
  1638. When writing custom validation for ``InlineModelAdmin`` forms, be cautious
  1639. of writing validation that relies on features of the parent model. If the
  1640. parent model fails to validate, it may be left in an inconsistent state as
  1641. described in the warning in :ref:`validation-on-modelform`.
  1642. .. attribute:: InlineModelAdmin.classes
  1643. A list or tuple containing extra CSS classes to apply to the fieldset that
  1644. is rendered for the inlines. Defaults to ``None``. As with classes
  1645. configured in :attr:`~ModelAdmin.fieldsets`, inlines with a ``collapse``
  1646. class will be initially collapsed using an expandable widget.
  1647. .. attribute:: InlineModelAdmin.extra
  1648. This controls the number of extra forms the formset will display in
  1649. addition to the initial forms. Defaults to 3. See the
  1650. :doc:`formsets documentation </topics/forms/formsets>` for more
  1651. information.
  1652. For users with JavaScript-enabled browsers, an "Add another" link is
  1653. provided to enable any number of additional inlines to be added in addition
  1654. to those provided as a result of the ``extra`` argument.
  1655. The dynamic link will not appear if the number of currently displayed forms
  1656. exceeds ``max_num``, or if the user does not have JavaScript enabled.
  1657. :meth:`InlineModelAdmin.get_extra` also allows you to customize the number
  1658. of extra forms.
  1659. .. attribute:: InlineModelAdmin.max_num
  1660. This controls the maximum number of forms to show in the inline. This
  1661. doesn't directly correlate to the number of objects, but can if the value
  1662. is small enough. See :ref:`model-formsets-max-num` for more information.
  1663. :meth:`InlineModelAdmin.get_max_num` also allows you to customize the
  1664. maximum number of extra forms.
  1665. .. attribute:: InlineModelAdmin.min_num
  1666. This controls the minimum number of forms to show in the inline.
  1667. See :func:`~django.forms.models.modelformset_factory` for more information.
  1668. :meth:`InlineModelAdmin.get_min_num` also allows you to customize the
  1669. minimum number of displayed forms.
  1670. .. attribute:: InlineModelAdmin.raw_id_fields
  1671. By default, Django's admin uses a select-box interface (<select>) for
  1672. fields that are ``ForeignKey``. Sometimes you don't want to incur the
  1673. overhead of having to select all the related instances to display in the
  1674. drop-down.
  1675. ``raw_id_fields`` is a list of fields you would like to change into an
  1676. ``Input`` widget for either a ``ForeignKey`` or ``ManyToManyField``::
  1677. class BookInline(admin.TabularInline):
  1678. model = Book
  1679. raw_id_fields = ["pages"]
  1680. .. attribute:: InlineModelAdmin.template
  1681. The template used to render the inline on the page.
  1682. .. attribute:: InlineModelAdmin.verbose_name
  1683. An override to the :attr:`~django.db.models.Options.verbose_name` from the
  1684. model's inner ``Meta`` class.
  1685. .. attribute:: InlineModelAdmin.verbose_name_plural
  1686. An override to the :attr:`~django.db.models.Options.verbose_name_plural`
  1687. from the model's inner ``Meta`` class. If this isn't given and the
  1688. :attr:`.InlineModelAdmin.verbose_name` is defined, Django will use
  1689. :attr:`.InlineModelAdmin.verbose_name` + ``'s'``.
  1690. .. attribute:: InlineModelAdmin.can_delete
  1691. Specifies whether or not inline objects can be deleted in the inline.
  1692. Defaults to ``True``.
  1693. .. attribute:: InlineModelAdmin.show_change_link
  1694. Specifies whether or not inline objects that can be changed in the
  1695. admin have a link to the change form. Defaults to ``False``.
  1696. .. method:: InlineModelAdmin.get_formset(request, obj=None, **kwargs)
  1697. Returns a :class:`~django.forms.models.BaseInlineFormSet` class for use in
  1698. admin add/change views. ``obj`` is the parent object being edited or
  1699. ``None`` when adding a new parent. See the example for
  1700. :class:`ModelAdmin.get_formsets_with_inlines`.
  1701. .. method:: InlineModelAdmin.get_extra(request, obj=None, **kwargs)
  1702. Returns the number of extra inline forms to use. By default, returns the
  1703. :attr:`InlineModelAdmin.extra` attribute.
  1704. Override this method to programmatically determine the number of extra
  1705. inline forms. For example, this may be based on the model instance
  1706. (passed as the keyword argument ``obj``)::
  1707. class BinaryTreeAdmin(admin.TabularInline):
  1708. model = BinaryTree
  1709. def get_extra(self, request, obj=None, **kwargs):
  1710. extra = 2
  1711. if obj:
  1712. return extra - obj.binarytree_set.count()
  1713. return extra
  1714. .. method:: InlineModelAdmin.get_max_num(request, obj=None, **kwargs)
  1715. Returns the maximum number of extra inline forms to use. By default,
  1716. returns the :attr:`InlineModelAdmin.max_num` attribute.
  1717. Override this method to programmatically determine the maximum number of
  1718. inline forms. For example, this may be based on the model instance
  1719. (passed as the keyword argument ``obj``)::
  1720. class BinaryTreeAdmin(admin.TabularInline):
  1721. model = BinaryTree
  1722. def get_max_num(self, request, obj=None, **kwargs):
  1723. max_num = 10
  1724. if obj and obj.parent:
  1725. return max_num - 5
  1726. return max_num
  1727. .. method:: InlineModelAdmin.get_min_num(request, obj=None, **kwargs)
  1728. Returns the minimum number of inline forms to use. By default,
  1729. returns the :attr:`InlineModelAdmin.min_num` attribute.
  1730. Override this method to programmatically determine the minimum number of
  1731. inline forms. For example, this may be based on the model instance
  1732. (passed as the keyword argument ``obj``).
  1733. .. method:: InlineModelAdmin.has_add_permission(request, obj)
  1734. Should return ``True`` if adding an inline object is permitted, ``False``
  1735. otherwise. ``obj`` is the parent object being edited or ``None`` when
  1736. adding a new parent.
  1737. .. method:: InlineModelAdmin.has_change_permission(request, obj=None)
  1738. Should return ``True`` if editing an inline object is permitted, ``False``
  1739. otherwise. ``obj`` is the parent object being edited.
  1740. .. method:: InlineModelAdmin.has_delete_permission(request, obj=None)
  1741. Should return ``True`` if deleting an inline object is permitted, ``False``
  1742. otherwise. ``obj`` is the parent object being edited.
  1743. .. note::
  1744. The ``obj`` argument passed to ``InlineModelAdmin`` methods is the parent
  1745. object being edited or ``None`` when adding a new parent.
  1746. Working with a model with two or more foreign keys to the same parent model
  1747. ---------------------------------------------------------------------------
  1748. It is sometimes possible to have more than one foreign key to the same model.
  1749. Take this model for instance::
  1750. from django.db import models
  1751. class Person(models.Model):
  1752. name = models.CharField(max_length=128)
  1753. class Friendship(models.Model):
  1754. to_person = models.ForeignKey(
  1755. Person, on_delete=models.CASCADE, related_name="friends"
  1756. )
  1757. from_person = models.ForeignKey(
  1758. Person, on_delete=models.CASCADE, related_name="from_friends"
  1759. )
  1760. If you wanted to display an inline on the ``Person`` admin add/change pages
  1761. you need to explicitly define the foreign key since it is unable to do so
  1762. automatically::
  1763. from django.contrib import admin
  1764. from myapp.models import Friendship, Person
  1765. class FriendshipInline(admin.TabularInline):
  1766. model = Friendship
  1767. fk_name = "to_person"
  1768. class PersonAdmin(admin.ModelAdmin):
  1769. inlines = [
  1770. FriendshipInline,
  1771. ]
  1772. admin.site.register(Person, PersonAdmin)
  1773. Working with many-to-many models
  1774. --------------------------------
  1775. By default, admin widgets for many-to-many relations will be displayed
  1776. on whichever model contains the actual reference to the
  1777. :class:`~django.db.models.ManyToManyField`. Depending on your ``ModelAdmin``
  1778. definition, each many-to-many field in your model will be represented by a
  1779. standard HTML ``<select multiple>``, a horizontal or vertical filter, or a
  1780. ``raw_id_fields`` widget. However, it is also possible to replace these
  1781. widgets with inlines.
  1782. Suppose we have the following models::
  1783. from django.db import models
  1784. class Person(models.Model):
  1785. name = models.CharField(max_length=128)
  1786. class Group(models.Model):
  1787. name = models.CharField(max_length=128)
  1788. members = models.ManyToManyField(Person, related_name="groups")
  1789. If you want to display many-to-many relations using an inline, you can do
  1790. so by defining an ``InlineModelAdmin`` object for the relationship::
  1791. from django.contrib import admin
  1792. from myapp.models import Group
  1793. class MembershipInline(admin.TabularInline):
  1794. model = Group.members.through
  1795. class GroupAdmin(admin.ModelAdmin):
  1796. inlines = [
  1797. MembershipInline,
  1798. ]
  1799. exclude = ["members"]
  1800. admin.site.register(Group, GroupAdmin)
  1801. There are two features worth noting in this example.
  1802. Firstly - the ``MembershipInline`` class references ``Group.members.through``.
  1803. The ``through`` attribute is a reference to the model that manages the
  1804. many-to-many relation. This model is automatically created by Django when you
  1805. define a many-to-many field.
  1806. Secondly, the ``GroupAdmin`` must manually exclude the ``members`` field.
  1807. Django displays an admin widget for a many-to-many field on the model that
  1808. defines the relation (in this case, ``Group``). If you want to use an inline
  1809. model to represent the many-to-many relationship, you must tell Django's admin
  1810. to *not* display this widget - otherwise you will end up with two widgets on
  1811. your admin page for managing the relation.
  1812. Note that when using this technique the
  1813. :data:`~django.db.models.signals.m2m_changed` signals aren't triggered. This
  1814. is because as far as the admin is concerned, ``through`` is just a model with
  1815. two foreign key fields rather than a many-to-many relation.
  1816. In all other respects, the ``InlineModelAdmin`` is exactly the same as any
  1817. other. You can customize the appearance using any of the normal
  1818. ``ModelAdmin`` properties.
  1819. Working with many-to-many intermediary models
  1820. ---------------------------------------------
  1821. When you specify an intermediary model using the ``through`` argument to a
  1822. :class:`~django.db.models.ManyToManyField`, the admin will not display a
  1823. widget by default. This is because each instance of that intermediary model
  1824. requires more information than could be displayed in a single widget, and the
  1825. layout required for multiple widgets will vary depending on the intermediate
  1826. model.
  1827. However, we still want to be able to edit that information inline. Fortunately,
  1828. we can do this with inline admin models. Suppose we have the following models::
  1829. from django.db import models
  1830. class Person(models.Model):
  1831. name = models.CharField(max_length=128)
  1832. class Group(models.Model):
  1833. name = models.CharField(max_length=128)
  1834. members = models.ManyToManyField(Person, through="Membership")
  1835. class Membership(models.Model):
  1836. person = models.ForeignKey(Person, on_delete=models.CASCADE)
  1837. group = models.ForeignKey(Group, on_delete=models.CASCADE)
  1838. date_joined = models.DateField()
  1839. invite_reason = models.CharField(max_length=64)
  1840. The first step in displaying this intermediate model in the admin is to
  1841. define an inline class for the ``Membership`` model::
  1842. class MembershipInline(admin.TabularInline):
  1843. model = Membership
  1844. extra = 1
  1845. This example uses the default ``InlineModelAdmin`` values for the
  1846. ``Membership`` model, and limits the extra add forms to one. This could be
  1847. customized using any of the options available to ``InlineModelAdmin`` classes.
  1848. Now create admin views for the ``Person`` and ``Group`` models::
  1849. class PersonAdmin(admin.ModelAdmin):
  1850. inlines = [MembershipInline]
  1851. class GroupAdmin(admin.ModelAdmin):
  1852. inlines = [MembershipInline]
  1853. Finally, register your ``Person`` and ``Group`` models with the admin site::
  1854. admin.site.register(Person, PersonAdmin)
  1855. admin.site.register(Group, GroupAdmin)
  1856. Now your admin site is set up to edit ``Membership`` objects inline from
  1857. either the ``Person`` or the ``Group`` detail pages.
  1858. .. _using-generic-relations-as-an-inline:
  1859. Using generic relations as an inline
  1860. ------------------------------------
  1861. It is possible to use an inline with generically related objects. Let's say
  1862. you have the following models::
  1863. from django.contrib.contenttypes.fields import GenericForeignKey
  1864. from django.db import models
  1865. class Image(models.Model):
  1866. image = models.ImageField(upload_to="images")
  1867. content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
  1868. object_id = models.PositiveIntegerField()
  1869. content_object = GenericForeignKey("content_type", "object_id")
  1870. class Product(models.Model):
  1871. name = models.CharField(max_length=100)
  1872. If you want to allow editing and creating an ``Image`` instance on the
  1873. ``Product``, add/change views you can use
  1874. :class:`~django.contrib.contenttypes.admin.GenericTabularInline`
  1875. or :class:`~django.contrib.contenttypes.admin.GenericStackedInline` (both
  1876. subclasses of :class:`~django.contrib.contenttypes.admin.GenericInlineModelAdmin`)
  1877. provided by :mod:`~django.contrib.contenttypes.admin`. They implement tabular
  1878. and stacked visual layouts for the forms representing the inline objects,
  1879. respectively, just like their non-generic counterparts. They behave just like
  1880. any other inline. In your ``admin.py`` for this example app::
  1881. from django.contrib import admin
  1882. from django.contrib.contenttypes.admin import GenericTabularInline
  1883. from myapp.models import Image, Product
  1884. class ImageInline(GenericTabularInline):
  1885. model = Image
  1886. class ProductAdmin(admin.ModelAdmin):
  1887. inlines = [
  1888. ImageInline,
  1889. ]
  1890. admin.site.register(Product, ProductAdmin)
  1891. See the :doc:`contenttypes documentation </ref/contrib/contenttypes>` for more
  1892. specific information.
  1893. .. _admin-overriding-templates:
  1894. Overriding admin templates
  1895. ==========================
  1896. You can override many of the templates which the admin module uses to generate
  1897. the various pages of an admin site. You can even override a few of these
  1898. templates for a specific app, or a specific model.
  1899. Set up your projects admin template directories
  1900. -----------------------------------------------
  1901. The admin template files are located in the
  1902. :source:`django/contrib/admin/templates/admin` directory.
  1903. In order to override one or more of them, first create an ``admin`` directory
  1904. in your project's ``templates`` directory. This can be any of the directories
  1905. you specified in the :setting:`DIRS <TEMPLATES-DIRS>` option of the
  1906. ``DjangoTemplates`` backend in the :setting:`TEMPLATES` setting. If you have
  1907. customized the ``'loaders'`` option, be sure
  1908. ``'django.template.loaders.filesystem.Loader'`` appears before
  1909. ``'django.template.loaders.app_directories.Loader'`` so that your custom
  1910. templates will be found by the template loading system before those that are
  1911. included with :mod:`django.contrib.admin`.
  1912. Within this ``admin`` directory, create sub-directories named after your app.
  1913. Within these app subdirectories create sub-directories named after your models.
  1914. Note, that the admin app will lowercase the model name when looking for the
  1915. directory, so make sure you name the directory in all lowercase if you are
  1916. going to run your app on a case-sensitive filesystem.
  1917. To override an admin template for a specific app, copy and edit the template
  1918. from the :source:`django/contrib/admin/templates/admin` directory, and save it to one
  1919. of the directories you just created.
  1920. For example, if we wanted to add a tool to the change list view for all the
  1921. models in an app named ``my_app``, we would copy
  1922. ``contrib/admin/templates/admin/change_list.html`` to the
  1923. ``templates/admin/my_app/`` directory of our project, and make any necessary
  1924. changes.
  1925. If we wanted to add a tool to the change list view for only a specific model
  1926. named 'Page', we would copy that same file to the
  1927. ``templates/admin/my_app/page`` directory of our project.
  1928. Overriding vs. replacing an admin template
  1929. ------------------------------------------
  1930. Because of the modular design of the admin templates, it is usually neither
  1931. necessary nor advisable to replace an entire template. It is almost always
  1932. better to override only the section of the template which you need to change.
  1933. To continue the example above, we want to add a new link next to the
  1934. ``History`` tool for the ``Page`` model. After looking at ``change_form.html``
  1935. we determine that we only need to override the ``object-tools-items`` block.
  1936. Therefore here is our new ``change_form.html`` :
  1937. .. code-block:: html+django
  1938. {% extends "admin/change_form.html" %}
  1939. {% load i18n admin_urls %}
  1940. {% block object-tools-items %}
  1941. <li>
  1942. <a href="{% url opts|admin_urlname:'history' original.pk|admin_urlquote %}" class="historylink">{% translate "History" %}</a>
  1943. </li>
  1944. <li>
  1945. <a href="mylink/" class="historylink">My Link</a>
  1946. </li>
  1947. {% if has_absolute_url %}
  1948. <li>
  1949. <a href="{% url 'admin:view_on_site' content_type_id original.pk %}" class="viewsitelink">{% translate "View on site" %}</a>
  1950. </li>
  1951. {% endif %}
  1952. {% endblock %}
  1953. And that's it! If we placed this file in the ``templates/admin/my_app``
  1954. directory, our link would appear on the change form for all models within
  1955. my_app.
  1956. .. _admin-templates-overridden-per-app-or-model:
  1957. Templates which may be overridden per app or model
  1958. --------------------------------------------------
  1959. Not every template in ``contrib/admin/templates/admin`` may be overridden per
  1960. app or per model. The following can:
  1961. * ``actions.html``
  1962. * ``app_index.html``
  1963. * ``change_form.html``
  1964. * ``change_form_object_tools.html``
  1965. * ``change_list.html``
  1966. * ``change_list_object_tools.html``
  1967. * ``change_list_results.html``
  1968. * ``date_hierarchy.html``
  1969. * ``delete_confirmation.html``
  1970. * ``object_history.html``
  1971. * ``pagination.html``
  1972. * ``popup_response.html``
  1973. * ``prepopulated_fields_js.html``
  1974. * ``search_form.html``
  1975. * ``submit_line.html``
  1976. For those templates that cannot be overridden in this way, you may still
  1977. override them for your entire project by placing the new version in your
  1978. ``templates/admin`` directory. This is particularly useful to create custom 404
  1979. and 500 pages.
  1980. .. note::
  1981. Some of the admin templates, such as ``change_list_results.html`` are used
  1982. to render custom inclusion tags. These may be overridden, but in such cases
  1983. you are probably better off creating your own version of the tag in
  1984. question and giving it a different name. That way you can use it
  1985. selectively.
  1986. Root and login templates
  1987. ------------------------
  1988. If you wish to change the index, login or logout templates, you are better off
  1989. creating your own ``AdminSite`` instance (see below), and changing the
  1990. :attr:`AdminSite.index_template` , :attr:`AdminSite.login_template` or
  1991. :attr:`AdminSite.logout_template` properties.
  1992. .. _admin-theming:
  1993. Theming support
  1994. ===============
  1995. The admin uses CSS variables to define colors and fonts. This allows changing
  1996. themes without having to override many individual CSS rules. For example, if
  1997. you preferred purple instead of blue you could add a ``admin/base.html``
  1998. template override to your project:
  1999. .. code-block:: html+django
  2000. {% extends 'admin/base.html' %}
  2001. {% block extrastyle %}{{ block.super }}
  2002. <style>
  2003. html[data-theme="light"], :root {
  2004. --primary: #9774d5;
  2005. --secondary: #785cab;
  2006. --link-fg: #7c449b;
  2007. --link-selected-fg: #8f5bb2;
  2008. }
  2009. </style>
  2010. {% endblock %}
  2011. The list of CSS variables are defined at
  2012. :source:`django/contrib/admin/static/admin/css/base.css`.
  2013. Dark mode variables, respecting the `prefers-color-scheme`_ media query, are
  2014. defined at :source:`django/contrib/admin/static/admin/css/dark_mode.css`. This is
  2015. linked to the document in ``{% block dark-mode-vars %}``.
  2016. .. _prefers-color-scheme: https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme
  2017. .. _extrabody:
  2018. ``extrabody`` block
  2019. ===================
  2020. .. versionadded:: 5.2
  2021. You can add custom HTML, JavaScript, or other content to appear just before the
  2022. closing ``</body>`` tag of templates that extend ``admin/base.html`` by
  2023. extending the ``extrabody`` block. For example, if you want an alert to appear
  2024. on page load you could add a ``admin/base.html`` template override to your
  2025. project:
  2026. .. code-block:: html+django
  2027. {% extends 'admin/base.html' %}
  2028. {% block extrabody %}
  2029. {{ block.super }}
  2030. <script>
  2031. document.addEventListener('DOMContentLoaded', function() {
  2032. window.alert('Welcome!');
  2033. });
  2034. </script>
  2035. {% endblock extrabody %}
  2036. ``AdminSite`` objects
  2037. =====================
  2038. .. class:: AdminSite(name='admin')
  2039. A Django administrative site is represented by an instance of
  2040. ``django.contrib.admin.sites.AdminSite``; by default, an instance of
  2041. this class is created as ``django.contrib.admin.site`` and you can
  2042. register your models and ``ModelAdmin`` instances with it.
  2043. If you want to customize the default admin site, you can :ref:`override it
  2044. <overriding-default-admin-site>`.
  2045. When constructing an instance of an ``AdminSite``, you can provide
  2046. a unique instance name using the ``name`` argument to the constructor. This
  2047. instance name is used to identify the instance, especially when
  2048. :ref:`reversing admin URLs <admin-reverse-urls>`. If no instance name is
  2049. provided, a default instance name of ``admin`` will be used.
  2050. See :ref:`customizing-adminsite` for an example of customizing the
  2051. :class:`AdminSite` class.
  2052. .. data:: django.contrib.admin.sites.all_sites
  2053. A :class:`~weakref.WeakSet` contains all admin site instances.
  2054. ``AdminSite`` attributes
  2055. ------------------------
  2056. Templates can override or extend base admin templates as described in
  2057. :ref:`admin-overriding-templates`.
  2058. .. attribute:: AdminSite.site_header
  2059. The text to put at the top of each admin page, as a ``<div>`` (a string).
  2060. By default, this is "Django administration".
  2061. .. attribute:: AdminSite.site_title
  2062. The text to put at the end of each admin page's ``<title>`` (a string). By
  2063. default, this is "Django site admin".
  2064. .. attribute:: AdminSite.site_url
  2065. The URL for the "View site" link at the top of each admin page. By default,
  2066. ``site_url`` is ``/``. Set it to ``None`` to remove the link.
  2067. For sites running on a subpath, the :meth:`each_context` method checks if
  2068. the current request has ``request.META['SCRIPT_NAME']`` set and uses that
  2069. value if ``site_url`` isn't set to something other than ``/``.
  2070. .. attribute:: AdminSite.index_title
  2071. The text to put at the top of the admin index page (a string). By default,
  2072. this is "Site administration".
  2073. .. attribute:: AdminSite.index_template
  2074. Path to a custom template that will be used by the admin site main index
  2075. view.
  2076. .. attribute:: AdminSite.app_index_template
  2077. Path to a custom template that will be used by the admin site app index view.
  2078. .. attribute:: AdminSite.empty_value_display
  2079. The string to use for displaying empty values in the admin site's change
  2080. list. Defaults to a dash. The value can also be overridden on a per
  2081. ``ModelAdmin`` basis and on a custom field within a ``ModelAdmin`` by
  2082. setting an ``empty_value_display`` attribute on the field. See
  2083. :attr:`ModelAdmin.empty_value_display` for examples.
  2084. .. attribute:: AdminSite.enable_nav_sidebar
  2085. A boolean value that determines whether to show the navigation sidebar
  2086. on larger screens. By default, it is set to ``True``.
  2087. .. attribute:: AdminSite.final_catch_all_view
  2088. A boolean value that determines whether to add a final catch-all view to
  2089. the admin that redirects unauthenticated users to the login page. By
  2090. default, it is set to ``True``.
  2091. .. warning::
  2092. Setting this to ``False`` is not recommended as the view protects
  2093. against a potential model enumeration privacy issue.
  2094. .. attribute:: AdminSite.login_template
  2095. Path to a custom template that will be used by the admin site login view.
  2096. .. attribute:: AdminSite.login_form
  2097. Subclass of :class:`~django.contrib.auth.forms.AuthenticationForm` that
  2098. will be used by the admin site login view.
  2099. .. attribute:: AdminSite.logout_template
  2100. Path to a custom template that will be used by the admin site logout view.
  2101. .. attribute:: AdminSite.password_change_form
  2102. .. versionadded:: 6.0
  2103. Subclass of :class:`~django.contrib.auth.forms.PasswordChangeForm` that
  2104. will be used by the admin site password change view.
  2105. .. attribute:: AdminSite.password_change_template
  2106. Path to a custom template that will be used by the admin site password
  2107. change view.
  2108. .. attribute:: AdminSite.password_change_done_template
  2109. Path to a custom template that will be used by the admin site password
  2110. change done view.
  2111. ``AdminSite`` methods
  2112. ---------------------
  2113. .. method:: AdminSite.each_context(request)
  2114. Returns a dictionary of variables to put in the template context for
  2115. every page in the admin site.
  2116. Includes the following variables and values by default:
  2117. * ``site_header``: :attr:`AdminSite.site_header`
  2118. * ``site_title``: :attr:`AdminSite.site_title`
  2119. * ``site_url``: :attr:`AdminSite.site_url`
  2120. * ``has_permission``: :meth:`AdminSite.has_permission`
  2121. * ``available_apps``: a list of applications from the :doc:`application registry
  2122. </ref/applications/>` available for the current user. Each entry in the
  2123. list is a dict representing an application with the following keys:
  2124. * ``app_label``: the application label
  2125. * ``app_url``: the URL of the application index in the admin
  2126. * ``has_module_perms``: a boolean indicating if displaying and accessing of
  2127. the module's index page is permitted for the current user
  2128. * ``models``: a list of the models available in the application
  2129. Each model is a dict with the following keys:
  2130. * ``model``: the model class
  2131. * ``object_name``: class name of the model
  2132. * ``name``: plural name of the model
  2133. * ``perms``: a ``dict`` tracking ``add``, ``change``, ``delete``, and
  2134. ``view`` permissions
  2135. * ``admin_url``: admin changelist URL for the model
  2136. * ``add_url``: admin URL to add a new model instance
  2137. * ``is_popup``: whether the current page is displayed in a popup window
  2138. * ``is_nav_sidebar_enabled``: :attr:`AdminSite.enable_nav_sidebar`
  2139. * ``log_entries``: :meth:`.AdminSite.get_log_entries`
  2140. .. method:: AdminSite.get_app_list(request, app_label=None)
  2141. Returns a list of applications from the :doc:`application registry
  2142. </ref/applications/>` available for the current user. You can optionally
  2143. pass an ``app_label`` argument to get details for a single app. Each entry
  2144. in the list is a dictionary representing an application with the following
  2145. keys:
  2146. * ``app_label``: the application label
  2147. * ``app_url``: the URL of the application index in the admin
  2148. * ``has_module_perms``: a boolean indicating if displaying and accessing of
  2149. the module's index page is permitted for the current user
  2150. * ``models``: a list of the models available in the application
  2151. * ``name``: name of the application
  2152. Each model is a dictionary with the following keys:
  2153. * ``model``: the model class
  2154. * ``object_name``: class name of the model
  2155. * ``name``: plural name of the model
  2156. * ``perms``: a ``dict`` tracking ``add``, ``change``, ``delete``, and
  2157. ``view`` permissions
  2158. * ``admin_url``: admin changelist URL for the model
  2159. * ``add_url``: admin URL to add a new model instance
  2160. Lists of applications and models are sorted alphabetically by their names.
  2161. You can override this method to change the default order on the admin index
  2162. page.
  2163. .. method:: AdminSite.has_permission(request)
  2164. Returns ``True`` if the user for the given ``HttpRequest`` has permission
  2165. to view at least one page in the admin site. Defaults to requiring both
  2166. :attr:`User.is_active <django.contrib.auth.models.User.is_active>` and
  2167. :attr:`User.is_staff <django.contrib.auth.models.User.is_staff>` to be
  2168. ``True``.
  2169. .. method:: AdminSite.register(model_or_iterable, admin_class=None, **options)
  2170. Registers the given model class (or iterable of classes) with the given
  2171. ``admin_class``. ``admin_class`` defaults to
  2172. :class:`~django.contrib.admin.ModelAdmin` (the default admin options). If
  2173. keyword arguments are given -- e.g. ``list_display`` -- they'll be applied
  2174. as options to the admin class.
  2175. Raises :class:`~django.core.exceptions.ImproperlyConfigured` if a model is
  2176. abstract. and ``django.contrib.admin.exceptions.AlreadyRegistered`` if a
  2177. model is already registered.
  2178. .. method:: AdminSite.unregister(model_or_iterable)
  2179. Unregisters the given model class (or iterable of classes).
  2180. Raises ``django.contrib.admin.exceptions.NotRegistered`` if a model isn't
  2181. already registered.
  2182. .. method:: AdminSite.get_model_admin(model)
  2183. Returns an admin class for the given model class. Raises
  2184. ``django.contrib.admin.exceptions.NotRegistered`` if a model isn't registered.
  2185. .. method:: AdminSite.get_log_entries(request)
  2186. Returns a queryset for the related
  2187. :class:`~django.contrib.admin.models.LogEntry` instances, shown on the site
  2188. index page. This method can be overridden to filter the log entries by
  2189. other criteria.
  2190. .. _hooking-adminsite-to-urlconf:
  2191. Hooking ``AdminSite`` instances into your URLconf
  2192. -------------------------------------------------
  2193. The last step in setting up the Django admin is to hook your ``AdminSite``
  2194. instance into your URLconf. Do this by pointing a given URL at the
  2195. ``AdminSite.urls`` method. It is not necessary to use
  2196. :func:`~django.urls.include()`.
  2197. In this example, we register the default ``AdminSite`` instance
  2198. ``django.contrib.admin.site`` at the URL ``/admin/`` ::
  2199. # urls.py
  2200. from django.contrib import admin
  2201. from django.urls import path
  2202. urlpatterns = [
  2203. path("admin/", admin.site.urls),
  2204. ]
  2205. .. _customizing-adminsite:
  2206. Customizing the :class:`AdminSite` class
  2207. ----------------------------------------
  2208. If you'd like to set up your own admin site with custom behavior, you're free
  2209. to subclass ``AdminSite`` and override or add anything you like. Then, create
  2210. an instance of your ``AdminSite`` subclass (the same way you'd instantiate any
  2211. other Python class) and register your models and ``ModelAdmin`` subclasses with
  2212. it instead of with the default site. Finally, update :file:`myproject/urls.py`
  2213. to reference your :class:`AdminSite` subclass.
  2214. .. code-block:: python
  2215. :caption: ``myapp/admin.py``
  2216. from django.contrib import admin
  2217. from .models import MyModel
  2218. class MyAdminSite(admin.AdminSite):
  2219. site_header = "Monty Python administration"
  2220. admin_site = MyAdminSite(name="myadmin")
  2221. admin_site.register(MyModel)
  2222. .. code-block:: python
  2223. :caption: ``myproject/urls.py``
  2224. from django.urls import path
  2225. from myapp.admin import admin_site
  2226. urlpatterns = [
  2227. path("myadmin/", admin_site.urls),
  2228. ]
  2229. Note that you may not want autodiscovery of ``admin`` modules when using your
  2230. own ``AdminSite`` instance since you will likely be importing all the per-app
  2231. ``admin`` modules in your ``myproject.admin`` module. This means you need to
  2232. put ``'django.contrib.admin.apps.SimpleAdminConfig'`` instead of
  2233. ``'django.contrib.admin'`` in your :setting:`INSTALLED_APPS` setting.
  2234. .. _overriding-default-admin-site:
  2235. Overriding the default admin site
  2236. ---------------------------------
  2237. You can override the default ``django.contrib.admin.site`` by setting the
  2238. :attr:`~.SimpleAdminConfig.default_site` attribute of a custom ``AppConfig``
  2239. to the dotted import path of either a ``AdminSite`` subclass or a callable that
  2240. returns a site instance.
  2241. .. code-block:: python
  2242. :caption: ``myproject/admin.py``
  2243. from django.contrib import admin
  2244. class MyAdminSite(admin.AdminSite): ...
  2245. .. code-block:: python
  2246. :caption: ``myproject/apps.py``
  2247. from django.contrib.admin.apps import AdminConfig
  2248. class MyAdminConfig(AdminConfig):
  2249. default_site = "myproject.admin.MyAdminSite"
  2250. .. code-block:: python
  2251. :caption: ``myproject/settings.py``
  2252. INSTALLED_APPS = [
  2253. # ...
  2254. "myproject.apps.MyAdminConfig", # replaces 'django.contrib.admin'
  2255. # ...
  2256. ]
  2257. .. _multiple-admin-sites:
  2258. Multiple admin sites in the same URLconf
  2259. ----------------------------------------
  2260. You can create multiple instances of the admin site on the same Django-powered
  2261. website. Create multiple instances of ``AdminSite`` and place each one at a
  2262. different URL.
  2263. In this example, the URLs ``/basic-admin/`` and ``/advanced-admin/`` feature
  2264. separate versions of the admin site -- using the ``AdminSite`` instances
  2265. ``myproject.admin.basic_site`` and ``myproject.admin.advanced_site``,
  2266. respectively::
  2267. # urls.py
  2268. from django.urls import path
  2269. from myproject.admin import advanced_site, basic_site
  2270. urlpatterns = [
  2271. path("basic-admin/", basic_site.urls),
  2272. path("advanced-admin/", advanced_site.urls),
  2273. ]
  2274. ``AdminSite`` instances take a single argument to their constructor, their
  2275. name, which can be anything you like. This argument becomes the prefix to the
  2276. URL names for the purposes of :ref:`reversing them<admin-reverse-urls>`. This
  2277. is only necessary if you are using more than one ``AdminSite``.
  2278. Adding views to admin sites
  2279. ---------------------------
  2280. Just like :class:`ModelAdmin`, :class:`AdminSite` provides a
  2281. :meth:`~django.contrib.admin.ModelAdmin.get_urls()` method
  2282. that can be overridden to define additional views for the site. To add
  2283. a new view to your admin site, extend the base
  2284. :meth:`~django.contrib.admin.ModelAdmin.get_urls()` method to include
  2285. a pattern for your new view.
  2286. .. note::
  2287. Any view you render that uses the admin templates, or extends the base
  2288. admin template, should set ``request.current_app`` before rendering the
  2289. template. It should be set to either ``self.name`` if your view is on an
  2290. ``AdminSite`` or ``self.admin_site.name`` if your view is on a
  2291. ``ModelAdmin``.
  2292. .. _auth_password_reset:
  2293. Adding a password reset feature
  2294. -------------------------------
  2295. You can add a password reset feature to the admin site by adding a few lines to
  2296. your URLconf. Specifically, add these four patterns::
  2297. from django.contrib import admin
  2298. from django.contrib.auth import views as auth_views
  2299. path(
  2300. "admin/password_reset/",
  2301. auth_views.PasswordResetView.as_view(
  2302. extra_context={"site_header": admin.site.site_header}
  2303. ),
  2304. name="admin_password_reset",
  2305. ),
  2306. path(
  2307. "admin/password_reset/done/",
  2308. auth_views.PasswordResetDoneView.as_view(
  2309. extra_context={"site_header": admin.site.site_header}
  2310. ),
  2311. name="password_reset_done",
  2312. ),
  2313. path(
  2314. "reset/<uidb64>/<token>/",
  2315. auth_views.PasswordResetConfirmView.as_view(
  2316. extra_context={"site_header": admin.site.site_header}
  2317. ),
  2318. name="password_reset_confirm",
  2319. ),
  2320. path(
  2321. "reset/done/",
  2322. auth_views.PasswordResetCompleteView.as_view(
  2323. extra_context={"site_header": admin.site.site_header}
  2324. ),
  2325. name="password_reset_complete",
  2326. ),
  2327. (This assumes you've added the admin at ``admin/`` and requires that you put
  2328. the URLs starting with ``^admin/`` before the line that includes the admin app
  2329. itself).
  2330. The presence of the ``admin_password_reset`` named URL will cause a "forgotten
  2331. your password?" link to appear on the default admin log-in page under the
  2332. password box.
  2333. ``LogEntry`` objects
  2334. ====================
  2335. .. class:: models.LogEntry
  2336. The ``LogEntry`` class tracks additions, changes, and deletions of objects
  2337. done through the admin interface.
  2338. .. currentmodule:: django.contrib.admin.models
  2339. ``LogEntry`` attributes
  2340. -----------------------
  2341. .. attribute:: LogEntry.action_time
  2342. The date and time of the action.
  2343. .. attribute:: LogEntry.user
  2344. The user (an :setting:`AUTH_USER_MODEL` instance) who performed the
  2345. action.
  2346. .. attribute:: LogEntry.content_type
  2347. The :class:`~django.contrib.contenttypes.models.ContentType` of the
  2348. modified object.
  2349. .. attribute:: LogEntry.object_id
  2350. The textual representation of the modified object's primary key.
  2351. .. attribute:: LogEntry.object_repr
  2352. The object`s ``repr()`` after the modification.
  2353. .. attribute:: LogEntry.action_flag
  2354. The type of action logged: ``ADDITION``, ``CHANGE``, ``DELETION``.
  2355. For example, to get a list of all additions done through the admin::
  2356. from django.contrib.admin.models import ADDITION, LogEntry
  2357. LogEntry.objects.filter(action_flag=ADDITION)
  2358. .. attribute:: LogEntry.change_message
  2359. The detailed description of the modification. In the case of an edit, for
  2360. example, the message contains a list of the edited fields. The Django admin
  2361. site formats this content as a JSON structure, so that
  2362. :meth:`get_change_message` can recompose a message translated in the current
  2363. user language. Custom code might set this as a plain string though. You are
  2364. advised to use the :meth:`get_change_message` method to retrieve this value
  2365. instead of accessing it directly.
  2366. ``LogEntry`` methods
  2367. --------------------
  2368. .. method:: LogEntry.get_edited_object()
  2369. A shortcut that returns the referenced object.
  2370. .. method:: LogEntry.get_change_message()
  2371. Formats and translates :attr:`change_message` into the current user
  2372. language. Messages created before Django 1.10 will always be displayed in
  2373. the language in which they were logged.
  2374. .. currentmodule:: django.contrib.admin
  2375. .. _admin-reverse-urls:
  2376. Reversing admin URLs
  2377. ====================
  2378. When an :class:`AdminSite` is deployed, the views provided by that site are
  2379. accessible using Django's :ref:`URL reversing system <naming-url-patterns>`.
  2380. The :class:`AdminSite` provides the following named URL patterns:
  2381. ========================= ======================== ==================================
  2382. Page URL name Parameters
  2383. ========================= ======================== ==================================
  2384. Index ``index``
  2385. Login ``login``
  2386. Logout ``logout``
  2387. Password change ``password_change``
  2388. Password change done ``password_change_done``
  2389. i18n JavaScript ``jsi18n``
  2390. Application index page ``app_list`` ``app_label``
  2391. Redirect to object's page ``view_on_site`` ``content_type_id``, ``object_id``
  2392. ========================= ======================== ==================================
  2393. Each :class:`ModelAdmin` instance provides an additional set of named URLs:
  2394. ====================== =============================================== =============
  2395. Page URL name Parameters
  2396. ====================== =============================================== =============
  2397. Changelist ``{{ app_label }}_{{ model_name }}_changelist``
  2398. Add ``{{ app_label }}_{{ model_name }}_add``
  2399. History ``{{ app_label }}_{{ model_name }}_history`` ``object_id``
  2400. Delete ``{{ app_label }}_{{ model_name }}_delete`` ``object_id``
  2401. Change ``{{ app_label }}_{{ model_name }}_change`` ``object_id``
  2402. ====================== =============================================== =============
  2403. The ``UserAdmin`` provides a named URL:
  2404. ====================== =============================================== =============
  2405. Page URL name Parameters
  2406. ====================== =============================================== =============
  2407. Password change ``auth_user_password_change`` ``user_id``
  2408. ====================== =============================================== =============
  2409. These named URLs are registered with the application namespace ``admin``, and
  2410. with an instance namespace corresponding to the name of the Site instance.
  2411. So - if you wanted to get a reference to the Change view for a particular
  2412. ``Choice`` object (from the polls application) in the default admin, you would
  2413. call:
  2414. .. code-block:: pycon
  2415. >>> from django.urls import reverse
  2416. >>> c = Choice.objects.get(...)
  2417. >>> change_url = reverse("admin:polls_choice_change", args=(c.id,))
  2418. This will find the first registered instance of the admin application
  2419. (whatever the instance name), and resolve to the view for changing
  2420. ``poll.Choice`` instances in that instance.
  2421. If you want to find a URL in a specific admin instance, provide the name of
  2422. that instance as a ``current_app`` hint to the reverse call. For example,
  2423. if you specifically wanted the admin view from the admin instance named
  2424. ``custom``, you would need to call:
  2425. .. code-block:: pycon
  2426. >>> change_url = reverse("admin:polls_choice_change", args=(c.id,), current_app="custom")
  2427. For more details, see the documentation on :ref:`reversing namespaced URLs
  2428. <topics-http-reversing-url-namespaces>`.
  2429. To allow easier reversing of the admin urls in templates, Django provides an
  2430. ``admin_urlname`` filter which takes an action as argument:
  2431. .. code-block:: html+django
  2432. {% load admin_urls %}
  2433. <a href="{% url opts|admin_urlname:'add' %}">Add user</a>
  2434. <a href="{% url opts|admin_urlname:'delete' user.pk %}">Delete this user</a>
  2435. The action in the examples above match the last part of the URL names for
  2436. :class:`ModelAdmin` instances described above. The ``opts`` variable can be any
  2437. object which has an ``app_label`` and ``model_name`` attributes and is usually
  2438. supplied by the admin views for the current model.
  2439. The ``display`` decorator
  2440. =========================
  2441. .. function:: display(*, boolean=None, ordering=None, description=None, empty_value=None)
  2442. This decorator can be used for setting specific attributes on custom
  2443. display functions that can be used with
  2444. :attr:`~django.contrib.admin.ModelAdmin.list_display` or
  2445. :attr:`~django.contrib.admin.ModelAdmin.readonly_fields`::
  2446. @admin.display(
  2447. boolean=True,
  2448. ordering="-publish_date",
  2449. description="Is Published?",
  2450. )
  2451. def is_published(self, obj):
  2452. return obj.publish_date is not None
  2453. This is equivalent to setting some attributes (with the original, longer
  2454. names) on the function directly::
  2455. def is_published(self, obj):
  2456. return obj.publish_date is not None
  2457. is_published.boolean = True
  2458. is_published.admin_order_field = "-publish_date"
  2459. is_published.short_description = "Is Published?"
  2460. Also note that the ``empty_value`` decorator parameter maps to the
  2461. ``empty_value_display`` attribute assigned directly to the function. It
  2462. cannot be used in conjunction with ``boolean`` -- they are mutually
  2463. exclusive.
  2464. Use of this decorator is not compulsory to make a display function, but it
  2465. can be useful to use it without arguments as a marker in your source to
  2466. identify the purpose of the function::
  2467. @admin.display
  2468. def published_year(self, obj):
  2469. return obj.publish_date.year
  2470. In this case it will add no attributes to the function.
  2471. .. currentmodule:: django.contrib.admin.views.decorators
  2472. The ``staff_member_required`` decorator
  2473. =======================================
  2474. .. function:: staff_member_required(redirect_field_name='next', login_url='admin:login')
  2475. This decorator is used on the admin views that require authorization. A
  2476. view decorated with this function will have the following behavior:
  2477. * If the user is logged in, is a staff member (``User.is_staff=True``), and
  2478. is active (``User.is_active=True``), execute the view normally.
  2479. * Otherwise, the request will be redirected to the URL specified by the
  2480. ``login_url`` parameter, with the originally requested path in a query
  2481. string variable specified by ``redirect_field_name``. For example:
  2482. ``/admin/login/?next=/admin/polls/question/3/``.
  2483. Example usage::
  2484. from django.contrib.admin.views.decorators import staff_member_required
  2485. @staff_member_required
  2486. def my_view(request): ...