index.txt 108 KB

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