index.txt 128 KB

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