index.txt 130 KB

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