index.txt 117 KB

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