index.txt 100 KB

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