index.txt 115 KB

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