index.txt 104 KB

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