index.txt 131 KB

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