index.txt 131 KB

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