index.txt 107 KB

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