2
0

index.txt 135 KB

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