index.txt 117 KB

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