index.txt 127 KB

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