index.txt 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885
  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. There are seven steps in activating the Django admin site:
  14. 1. Add ``'django.contrib.admin'`` to your :setting:`INSTALLED_APPS`
  15. setting.
  16. 2. Admin has three dependencies - :mod:`django.contrib.auth`,
  17. :mod:`django.contrib.contenttypes` and :mod:`django.contrib.messages`.
  18. If these applications are not in your :setting:`INSTALLED_APPS` list,
  19. add them.
  20. 3. Add ``django.contrib.messages.context_processors.messages`` to
  21. :setting:`TEMPLATE_CONTEXT_PROCESSORS` and
  22. :class:`~django.contrib.messages.middleware.MessageMiddleware` to
  23. :setting:`MIDDLEWARE_CLASSES`.
  24. 4. Determine which of your application's models should be editable in the
  25. admin interface.
  26. 5. For each of those models, optionally create a ``ModelAdmin`` class that
  27. encapsulates the customized admin functionality and options for that
  28. particular model.
  29. 6. Instantiate an ``AdminSite`` and tell it about each of your models and
  30. ``ModelAdmin`` classes.
  31. 7. Hook the ``AdminSite`` instance into your URLconf.
  32. Other topics
  33. ------------
  34. .. toctree::
  35. :maxdepth: 1
  36. actions
  37. admindocs
  38. .. seealso::
  39. For information about serving the media files (images, JavaScript, and CSS)
  40. associated with the admin in production, see :ref:`serving-media-files`.
  41. ``ModelAdmin`` objects
  42. ======================
  43. .. class:: ModelAdmin
  44. The ``ModelAdmin`` class is the representation of a model in the admin
  45. interface. These are stored in a file named ``admin.py`` in your
  46. application. Let's take a look at a very simple example of
  47. the ``ModelAdmin``::
  48. from django.contrib import admin
  49. from myproject.myapp.models import Author
  50. class AuthorAdmin(admin.ModelAdmin):
  51. pass
  52. admin.site.register(Author, AuthorAdmin)
  53. .. admonition:: Do you need a ``ModelAdmin`` object at all?
  54. In the preceding example, the ``ModelAdmin`` class doesn't define any
  55. custom values (yet). As a result, the default admin interface will be
  56. provided. If you are happy with the default admin interface, you don't
  57. need to define a ``ModelAdmin`` object at all -- you can register the
  58. model class without providing a ``ModelAdmin`` description. The
  59. preceding example could be simplified to::
  60. from django.contrib import admin
  61. from myproject.myapp.models import Author
  62. admin.site.register(Author)
  63. ``ModelAdmin`` options
  64. ----------------------
  65. The ``ModelAdmin`` is very flexible. It has several options for dealing with
  66. customizing the interface. All options are defined on the ``ModelAdmin``
  67. subclass::
  68. class AuthorAdmin(admin.ModelAdmin):
  69. date_hierarchy = 'pub_date'
  70. .. attribute:: ModelAdmin.actions
  71. A list of actions to make available on the change list page. See
  72. :doc:`/ref/contrib/admin/actions` for details.
  73. .. attribute:: ModelAdmin.actions_on_top
  74. .. attribute:: ModelAdmin.actions_on_bottom
  75. Controls where on the page the actions bar appears. By default, the admin
  76. changelist displays actions at the top of the page (``actions_on_top = True;
  77. actions_on_bottom = False``).
  78. .. attribute:: ModelAdmin.actions_selection_counter
  79. .. versionadded:: 1.2
  80. Controls whether a selection counter is display next to the action dropdown.
  81. By default, the admin changelist will display it
  82. (``actions_selection_counter = True``).
  83. .. attribute:: ModelAdmin.date_hierarchy
  84. Set ``date_hierarchy`` to the name of a ``DateField`` or ``DateTimeField``
  85. in your model, and the change list page will include a date-based drilldown
  86. navigation by that field.
  87. Example::
  88. date_hierarchy = 'pub_date'
  89. .. versionadded:: 1.3
  90. This will intelligently populate itself based on available data,
  91. e.g. if all the dates are in one month, it'll show the day-level
  92. drill-down only.
  93. .. attribute:: ModelAdmin.exclude
  94. This attribute, if given, should be a list of field names to exclude from
  95. the form.
  96. For example, let's consider the following model::
  97. class Author(models.Model):
  98. name = models.CharField(max_length=100)
  99. title = models.CharField(max_length=3)
  100. birth_date = models.DateField(blank=True, null=True)
  101. If you want a form for the ``Author`` model that includes only the ``name``
  102. and ``title`` fields, you would specify ``fields`` or ``exclude`` like
  103. this::
  104. class AuthorAdmin(admin.ModelAdmin):
  105. fields = ('name', 'title')
  106. class AuthorAdmin(admin.ModelAdmin):
  107. exclude = ('birth_date',)
  108. Since the Author model only has three fields, ``name``, ``title``, and
  109. ``birth_date``, the forms resulting from the above declarations will
  110. contain exactly the same fields.
  111. .. attribute:: ModelAdmin.fields
  112. If you need to achieve simple changes in the layout of fields in the forms
  113. of the "add" and "change" pages like only showing a subset of the available
  114. fields, modifying their order or grouping them in rows you can use the
  115. ``fields`` option (for more complex layout needs see the
  116. :attr:`~ModelAdmin.fieldsets` option described in the next section). For
  117. example, you could define a simpler version of the admin form for the
  118. ``django.contrib.flatpages.FlatPage`` model as follows::
  119. class FlatPageAdmin(admin.ModelAdmin):
  120. fields = ('url', 'title', 'content')
  121. In the above example, only the fields ``url``, ``title`` and ``content``
  122. will be displayed, sequentially, in the form.
  123. .. versionadded:: 1.2
  124. ``fields`` can contain values defined in :attr:`ModelAdmin.readonly_fields`
  125. to be displayed as read-only.
  126. .. versionadded:: 1.4
  127. To display multiple fields on the same line, wrap those fields in their own
  128. tuple. In this example, the ``url`` and ``title`` fields will display on the
  129. same line and the ``content`` field will be displayed below them in its
  130. own line::
  131. class FlatPageAdmin(admin.ModelAdmin):
  132. fields = (('url', 'title'), 'content')
  133. .. admonition:: Note
  134. This ``fields`` option should not be confused with the ``fields``
  135. dictionary key that is within the :attr:`~ModelAdmin.fieldsets` option,
  136. as described in the next section.
  137. If neither ``fields`` nor :attr:`~ModelAdmin.fieldsets` options are present,
  138. Django will default to displaying each field that isn't an ``AutoField`` and
  139. has ``editable=True``, in a single fieldset, in the same order as the fields
  140. are defined in the model.
  141. .. attribute:: ModelAdmin.fieldsets
  142. Set ``fieldsets`` to control the layout of admin "add" and "change" pages.
  143. ``fieldsets`` is a list of two-tuples, in which each two-tuple represents a
  144. ``<fieldset>`` on the admin form page. (A ``<fieldset>`` is a "section" of
  145. the form.)
  146. The two-tuples are in the format ``(name, field_options)``, where ``name``
  147. is a string representing the title of the fieldset and ``field_options`` is
  148. a dictionary of information about the fieldset, including a list of fields
  149. to be displayed in it.
  150. A full example, taken from the :class:`django.contrib.flatpages.FlatPage`
  151. model::
  152. class FlatPageAdmin(admin.ModelAdmin):
  153. fieldsets = (
  154. (None, {
  155. 'fields': ('url', 'title', 'content', 'sites')
  156. }),
  157. ('Advanced options', {
  158. 'classes': ('collapse',),
  159. 'fields': ('enable_comments', 'registration_required', 'template_name')
  160. }),
  161. )
  162. This results in an admin page that looks like:
  163. .. image:: _images/flatfiles_admin.png
  164. If neither ``fieldsets`` nor :attr:`~ModelAdmin.fields` options are present,
  165. Django will default to displaying each field that isn't an ``AutoField`` and
  166. has ``editable=True``, in a single fieldset, in the same order as the fields
  167. are defined in the model.
  168. The ``field_options`` dictionary can have the following keys:
  169. * ``fields``
  170. A tuple of field names to display in this fieldset. This key is
  171. required.
  172. Example::
  173. {
  174. 'fields': ('first_name', 'last_name', 'address', 'city', 'state'),
  175. }
  176. Just like with the :attr:`~ModelAdmin.fields` option, to display
  177. multiple fields on the same line, wrap those fields in their own
  178. tuple. In this example, the ``first_name`` and ``last_name`` fields
  179. will display on the same line::
  180. {
  181. 'fields': (('first_name', 'last_name'), 'address', 'city', 'state'),
  182. }
  183. .. versionadded:: 1.2
  184. ``fields`` can contain values defined in
  185. :attr:`~ModelAdmin.readonly_fields` to be displayed as read-only.
  186. * ``classes``
  187. A list containing extra CSS classes to apply to the fieldset.
  188. Example::
  189. {
  190. 'classes': ['wide', 'extrapretty'],
  191. }
  192. Two useful classes defined by the default admin site stylesheet are
  193. ``collapse`` and ``wide``. Fieldsets with the ``collapse`` style
  194. will be initially collapsed in the admin and replaced with a small
  195. "click to expand" link. Fieldsets with the ``wide`` style will be
  196. given extra horizontal space.
  197. * ``description``
  198. A string of optional extra text to be displayed at the top of each
  199. fieldset, under the heading of the fieldset.
  200. Note that this value is *not* HTML-escaped when it's displayed in
  201. the admin interface. This lets you include HTML if you so desire.
  202. Alternatively you can use plain text and
  203. ``django.utils.html.escape()`` to escape any HTML special
  204. characters.
  205. .. attribute:: ModelAdmin.filter_horizontal
  206. By default, a :class:`~django.db.models.ManyToManyField` is displayed in
  207. the admin site with a ``<select multiple>``. However, multiple-select boxes
  208. can be difficult to use when selecting many items. Adding a
  209. :class:`~django.db.models.ManyToManyField` to this list will instead use
  210. a nifty unobtrusive JavaScript "filter" interface that allows searching
  211. within the options. The unselected and selected options appear in two boxes
  212. side by side. See :attr:`~ModelAdmin.filter_vertical` to use a vertical
  213. interface.
  214. .. attribute:: ModelAdmin.filter_vertical
  215. Same as :attr:`~ModelAdmin.filter_horizontal`, but uses a vertical display
  216. of the filter interface with the box of unselected options appearing above
  217. the box of selected options.
  218. .. attribute:: ModelAdmin.form
  219. By default a ``ModelForm`` is dynamically created for your model. It is
  220. used to create the form presented on both the add/change pages. You can
  221. easily provide your own ``ModelForm`` to override any default form behavior
  222. on the add/change pages.
  223. For an example see the section `Adding custom validation to the admin`_.
  224. .. attribute:: ModelAdmin.formfield_overrides
  225. This provides a quick-and-dirty way to override some of the
  226. :class:`~django.forms.Field` options for use in the admin.
  227. ``formfield_overrides`` is a dictionary mapping a field class to a dict of
  228. arguments to pass to the field at construction time.
  229. Since that's a bit abstract, let's look at a concrete example. The most
  230. common use of ``formfield_overrides`` is to add a custom widget for a
  231. certain type of field. So, imagine we've written a ``RichTextEditorWidget``
  232. that we'd like to use for large text fields instead of the default
  233. ``<textarea>``. Here's how we'd do that::
  234. from django.db import models
  235. from django.contrib import admin
  236. # Import our custom widget and our model from where they're defined
  237. from myapp.widgets import RichTextEditorWidget
  238. from myapp.models import MyModel
  239. class MyModelAdmin(admin.ModelAdmin):
  240. formfield_overrides = {
  241. models.TextField: {'widget': RichTextEditorWidget},
  242. }
  243. Note that the key in the dictionary is the actual field class, *not* a
  244. string. The value is another dictionary; these arguments will be passed to
  245. :meth:`~django.forms.Field.__init__`. See :doc:`/ref/forms/api` for
  246. details.
  247. .. warning::
  248. If you want to use a custom widget with a relation field (i.e.
  249. :class:`~django.db.models.ForeignKey` or
  250. :class:`~django.db.models.ManyToManyField`), make sure you haven't
  251. included that field's name in ``raw_id_fields`` or ``radio_fields``.
  252. ``formfield_overrides`` won't let you change the widget on relation
  253. fields that have ``raw_id_fields`` or ``radio_fields`` set. That's
  254. because ``raw_id_fields`` and ``radio_fields`` imply custom widgets of
  255. their own.
  256. .. attribute:: ModelAdmin.inlines
  257. See :class:`InlineModelAdmin` objects below.
  258. .. attribute:: ModelAdmin.list_display
  259. Set ``list_display`` to control which fields are displayed on the change
  260. list page of the admin.
  261. Example::
  262. list_display = ('first_name', 'last_name')
  263. If you don't set ``list_display``, the admin site will display a single
  264. column that displays the ``__unicode__()`` representation of each object.
  265. You have four possible values that can be used in ``list_display``:
  266. * A field of the model. For example::
  267. class PersonAdmin(admin.ModelAdmin):
  268. list_display = ('first_name', 'last_name')
  269. * A callable that accepts one parameter for the model instance. For
  270. example::
  271. def upper_case_name(obj):
  272. return ("%s %s" % (obj.first_name, obj.last_name)).upper()
  273. upper_case_name.short_description = 'Name'
  274. class PersonAdmin(admin.ModelAdmin):
  275. list_display = (upper_case_name,)
  276. * A string representing an attribute on the ``ModelAdmin``. This
  277. behaves same as the callable. For example::
  278. class PersonAdmin(admin.ModelAdmin):
  279. list_display = ('upper_case_name',)
  280. def upper_case_name(self, obj):
  281. return ("%s %s" % (obj.first_name, obj.last_name)).upper()
  282. upper_case_name.short_description = 'Name'
  283. * A string representing an attribute on the model. This behaves almost
  284. the same as the callable, but ``self`` in this context is the model
  285. instance. Here's a full model example::
  286. class Person(models.Model):
  287. name = models.CharField(max_length=50)
  288. birthday = models.DateField()
  289. def decade_born_in(self):
  290. return self.birthday.strftime('%Y')[:3] + "0's"
  291. decade_born_in.short_description = 'Birth decade'
  292. class PersonAdmin(admin.ModelAdmin):
  293. list_display = ('name', 'decade_born_in')
  294. A few special cases to note about ``list_display``:
  295. * If the field is a ``ForeignKey``, Django will display the
  296. ``__unicode__()`` of the related object.
  297. * ``ManyToManyField`` fields aren't supported, because that would
  298. entail executing a separate SQL statement for each row in the table.
  299. If you want to do this nonetheless, give your model a custom method,
  300. and add that method's name to ``list_display``. (See below for more
  301. on custom methods in ``list_display``.)
  302. * If the field is a ``BooleanField`` or ``NullBooleanField``, Django
  303. will display a pretty "on" or "off" icon instead of ``True`` or
  304. ``False``.
  305. * If the string given is a method of the model, ``ModelAdmin`` or a
  306. callable, Django will HTML-escape the output by default. If you'd
  307. rather not escape the output of the method, give the method an
  308. ``allow_tags`` attribute whose value is ``True``.
  309. Here's a full example model::
  310. class Person(models.Model):
  311. first_name = models.CharField(max_length=50)
  312. last_name = models.CharField(max_length=50)
  313. color_code = models.CharField(max_length=6)
  314. def colored_name(self):
  315. return '<span style="color: #%s;">%s %s</span>' % (self.color_code, self.first_name, self.last_name)
  316. colored_name.allow_tags = True
  317. class PersonAdmin(admin.ModelAdmin):
  318. list_display = ('first_name', 'last_name', 'colored_name')
  319. * If the string given is a method of the model, ``ModelAdmin`` or a
  320. callable that returns True or False Django will display a pretty
  321. "on" or "off" icon if you give the method a ``boolean`` attribute
  322. whose value is ``True``.
  323. Here's a full example model::
  324. class Person(models.Model):
  325. first_name = models.CharField(max_length=50)
  326. birthday = models.DateField()
  327. def born_in_fifties(self):
  328. return self.birthday.strftime('%Y')[:3] == '195'
  329. born_in_fifties.boolean = True
  330. class PersonAdmin(admin.ModelAdmin):
  331. list_display = ('name', 'born_in_fifties')
  332. * The ``__str__()`` and ``__unicode__()`` methods are just as valid in
  333. ``list_display`` as any other model method, so it's perfectly OK to
  334. do this::
  335. list_display = ('__unicode__', 'some_other_field')
  336. * Usually, elements of ``list_display`` that aren't actual database
  337. fields can't be used in sorting (because Django does all the sorting
  338. at the database level).
  339. However, if an element of ``list_display`` represents a certain
  340. database field, you can indicate this fact by setting the
  341. ``admin_order_field`` attribute of the item.
  342. For example::
  343. class Person(models.Model):
  344. first_name = models.CharField(max_length=50)
  345. color_code = models.CharField(max_length=6)
  346. def colored_first_name(self):
  347. return '<span style="color: #%s;">%s</span>' % (self.color_code, self.first_name)
  348. colored_first_name.allow_tags = True
  349. colored_first_name.admin_order_field = 'first_name'
  350. class PersonAdmin(admin.ModelAdmin):
  351. list_display = ('first_name', 'colored_first_name')
  352. The above will tell Django to order by the ``first_name`` field when
  353. trying to sort by ``colored_first_name`` in the admin.
  354. .. attribute:: ModelAdmin.list_display_links
  355. Set ``list_display_links`` to control which fields in ``list_display``
  356. should be linked to the "change" page for an object.
  357. By default, the change list page will link the first column -- the first
  358. field specified in ``list_display`` -- to the change page for each item.
  359. But ``list_display_links`` lets you change which columns are linked. Set
  360. ``list_display_links`` to a list or tuple of fields (in the same
  361. format as ``list_display``) to link.
  362. ``list_display_links`` can specify one or many fields. As long as the
  363. fields appear in ``list_display``, Django doesn't care how many (or
  364. how few) fields are linked. The only requirement is: If you want to use
  365. ``list_display_links``, you must define ``list_display``.
  366. In this example, the ``first_name`` and ``last_name`` fields will be
  367. linked on the change list page::
  368. class PersonAdmin(admin.ModelAdmin):
  369. list_display = ('first_name', 'last_name', 'birthday')
  370. list_display_links = ('first_name', 'last_name')
  371. .. _admin-list-editable:
  372. .. attribute:: ModelAdmin.list_editable
  373. Set ``list_editable`` to a list of field names on the model which will
  374. allow editing on the change list page. That is, fields listed in
  375. ``list_editable`` will be displayed as form widgets on the change list
  376. page, allowing users to edit and save multiple rows at once.
  377. .. note::
  378. ``list_editable`` interacts with a couple of other options in
  379. particular ways; you should note the following rules:
  380. * Any field in ``list_editable`` must also be in ``list_display``.
  381. You can't edit a field that's not displayed!
  382. * The same field can't be listed in both ``list_editable`` and
  383. ``list_display_links`` -- a field can't be both a form and
  384. a link.
  385. You'll get a validation error if either of these rules are broken.
  386. .. attribute:: ModelAdmin.list_filter
  387. .. versionchanged:: 1.4
  388. Set ``list_filter`` to activate filters in the right sidebar of the change
  389. list page of the admin, as illustrated in the following screenshot:
  390. .. image:: _images/users_changelist.png
  391. ``list_filter`` should be a list of elements, where each element should be
  392. of one of the following types:
  393. * a field name, where the specified field should be either a
  394. ``BooleanField``, ``CharField``, ``DateField``, ``DateTimeField``,
  395. ``IntegerField``, ``ForeignKey`` or ``ManyToManyField``, for example::
  396. class PersonAdmin(ModelAdmin):
  397. list_filter = ('is_staff', 'company')
  398. .. versionadded:: 1.3
  399. Field names in ``list_filter`` can also span relations
  400. using the ``__`` lookup, for example::
  401. class PersonAdmin(UserAdmin):
  402. list_filter = ('company__name',)
  403. * a class inheriting from :mod:`django.contrib.admin.SimpleListFilter`,
  404. which you need to provide the ``title`` and ``parameter_name``
  405. attributes to and override the ``lookups`` and ``queryset`` methods,
  406. e.g.::
  407. from django.utils.translation import ugettext_lazy as _
  408. from django.contrib.admin import SimpleListFilter
  409. class DecadeBornListFilter(SimpleListFilter):
  410. # Human-readable title which will be displayed in the
  411. # right admin sidebar just above the filter options.
  412. title = _('decade born')
  413. # Parameter for the filter that will be used in the URL query.
  414. parameter_name = 'decade'
  415. def lookups(self, request, model_admin):
  416. """
  417. Returns a list of tuples. The first element in each
  418. tuple is the coded value for the option that will
  419. appear in the URL query. The second element is the
  420. human-readable name for the option that will appear
  421. in the right sidebar.
  422. """
  423. return (
  424. ('80s', _('in the eighties')),
  425. ('90s', _('in the nineties')),
  426. )
  427. def queryset(self, request, queryset):
  428. """
  429. Returns the filtered queryset based on the value
  430. provided in the query string and retrievable via
  431. `self.value()`.
  432. """
  433. # Compare the requested value (either '80s' or 'other')
  434. # to decide how to filter the queryset.
  435. if self.value() == '80s':
  436. return queryset.filter(birthday__year__gte=1980,
  437. birthday__year__lte=1989)
  438. if self.value() == '90s':
  439. return queryset.filter(birthday__year__gte=1990,
  440. birthday__year__lte=1999)
  441. class PersonAdmin(ModelAdmin):
  442. list_filter = (DecadeBornListFilter,)
  443. .. note::
  444. As a convenience, the ``HttpRequest`` object is passed to the
  445. ``lookups`` and ``queryset`` methods, for example::
  446. class AuthDecadeBornListFilter(DecadeBornListFilter):
  447. def lookups(self, request, model_admin):
  448. if request.user.is_superuser:
  449. return super(AuthDecadeBornListFilter,
  450. self).lookups(request, model_admin)
  451. def queryset(self, request, queryset):
  452. if request.user.is_superuser:
  453. return super(AuthDecadeBornListFilter,
  454. self).queryset(request, queryset)
  455. Also as a convenience, the ``ModelAdmin`` object is passed to
  456. the ``lookups`` method, for example if you want to base the
  457. lookups on the available data::
  458. class AdvancedDecadeBornListFilter(DecadeBornListFilter):
  459. def lookups(self, request, model_admin):
  460. """
  461. Only show the lookups if there actually is
  462. anyone born in the corresponding decades.
  463. """
  464. qs = model_admin.queryset(request)
  465. if qs.filter(birthday__year__gte=1980,
  466. birthday__year__lte=1989).exists():
  467. yield ('80s', _('in the eighties'))
  468. if qs.filter(birthday__year__gte=1990,
  469. birthday__year__lte=1999).exists():
  470. yield ('90s', _('in the nineties'))
  471. * a tuple, where the first element is a field name and the second
  472. element is a class inheriting from
  473. :mod:`django.contrib.admin.FieldListFilter`, for example::
  474. from django.contrib.admin import BooleanFieldListFilter
  475. class PersonAdmin(ModelAdmin):
  476. list_filter = (
  477. ('is_staff', BooleanFieldListFilter),
  478. )
  479. .. note::
  480. The ``FieldListFilter`` API is currently considered internal
  481. and prone to refactoring.
  482. .. attribute:: ModelAdmin.list_per_page
  483. Set ``list_per_page`` to control how many items appear on each paginated
  484. admin change list page. By default, this is set to ``100``.
  485. .. attribute:: ModelAdmin.list_select_related
  486. Set ``list_select_related`` to tell Django to use
  487. :meth:`~django.db.models.QuerySet.select_related` in retrieving the list of
  488. objects on the admin change list page. This can save you a bunch of
  489. database queries.
  490. The value should be either ``True`` or ``False``. Default is ``False``.
  491. Note that Django will use :meth:`~django.db.models.QuerySet.select_related`,
  492. regardless of this setting if one of the ``list_display`` fields is a
  493. ``ForeignKey``.
  494. .. attribute:: ModelAdmin.ordering
  495. Set ``ordering`` to specify how lists of objects should be ordered in the
  496. Django admin views. This should be a list or tuple in the same format as a
  497. model's :attr:`~django.db.models.Options.ordering` parameter.
  498. If this isn't provided, the Django admin will use the model's default
  499. ordering.
  500. .. admonition:: Note
  501. Django will only honor the first element in the list/tuple; any others
  502. will be ignored.
  503. .. attribute:: ModelAdmin.paginator
  504. .. versionadded:: 1.3
  505. The paginator class to be used for pagination. By default,
  506. :class:`django.core.paginator.Paginator` is used. If the custom paginator
  507. class doesn't have the same constructor interface as
  508. :class:`django.core.paginator.Paginator`, you will also need to
  509. provide an implementation for :meth:`ModelAdmin.get_paginator`.
  510. .. attribute:: ModelAdmin.prepopulated_fields
  511. Set ``prepopulated_fields`` to a dictionary mapping field names to the
  512. fields it should prepopulate from::
  513. class ArticleAdmin(admin.ModelAdmin):
  514. prepopulated_fields = {"slug": ("title",)}
  515. When set, the given fields will use a bit of JavaScript to populate from
  516. the fields assigned. The main use for this functionality is to
  517. automatically generate the value for ``SlugField`` fields from one or more
  518. other fields. The generated value is produced by concatenating the values
  519. of the source fields, and then by transforming that result into a valid
  520. slug (e.g. substituting dashes for spaces).
  521. ``prepopulated_fields`` doesn't accept ``DateTimeField``, ``ForeignKey``,
  522. nor ``ManyToManyField`` fields.
  523. .. attribute:: ModelAdmin.radio_fields
  524. By default, Django's admin uses a select-box interface (<select>) for
  525. fields that are ``ForeignKey`` or have ``choices`` set. If a field is
  526. present in ``radio_fields``, Django will use a radio-button interface
  527. instead. Assuming ``group`` is a ``ForeignKey`` on the ``Person`` model::
  528. class PersonAdmin(admin.ModelAdmin):
  529. radio_fields = {"group": admin.VERTICAL}
  530. You have the choice of using ``HORIZONTAL`` or ``VERTICAL`` from the
  531. ``django.contrib.admin`` module.
  532. Don't include a field in ``radio_fields`` unless it's a ``ForeignKey`` or has
  533. ``choices`` set.
  534. .. attribute:: ModelAdmin.raw_id_fields
  535. By default, Django's admin uses a select-box interface (<select>) for
  536. fields that are ``ForeignKey``. Sometimes you don't want to incur the
  537. overhead of having to select all the related instances to display in the
  538. drop-down.
  539. ``raw_id_fields`` is a list of fields you would like to change
  540. into an ``Input`` widget for either a ``ForeignKey`` or
  541. ``ManyToManyField``::
  542. class ArticleAdmin(admin.ModelAdmin):
  543. raw_id_fields = ("newspaper",)
  544. .. attribute:: ModelAdmin.readonly_fields
  545. .. versionadded:: 1.2
  546. By default the admin shows all fields as editable. Any fields in this
  547. option (which should be a ``list`` or ``tuple``) will display its data
  548. as-is and non-editable. This option behaves nearly identical to
  549. :attr:`ModelAdmin.list_display`. Usage is the same, however, when you
  550. specify :attr:`ModelAdmin.fields` or :attr:`ModelAdmin.fieldsets` the
  551. read-only fields must be present to be shown (they are ignored otherwise).
  552. If ``readonly_fields`` is used without defining explicit ordering through
  553. :attr:`ModelAdmin.fields` or :attr:`ModelAdmin.fieldsets` they will be
  554. added last after all editable fields.
  555. .. attribute:: ModelAdmin.save_as
  556. Set ``save_as`` to enable a "save as" feature on admin change forms.
  557. Normally, objects have three save options: "Save", "Save and continue
  558. editing" and "Save and add another". If ``save_as`` is ``True``, "Save
  559. and add another" will be replaced by a "Save as" button.
  560. "Save as" means the object will be saved as a new object (with a new ID),
  561. rather than the old object.
  562. By default, ``save_as`` is set to ``False``.
  563. .. attribute:: ModelAdmin.save_on_top
  564. Set ``save_on_top`` to add save buttons across the top of your admin change
  565. forms.
  566. Normally, the save buttons appear only at the bottom of the forms. If you
  567. set ``save_on_top``, the buttons will appear both on the top and the
  568. bottom.
  569. By default, ``save_on_top`` is set to ``False``.
  570. .. attribute:: ModelAdmin.search_fields
  571. Set ``search_fields`` to enable a search box on the admin change list page.
  572. This should be set to a list of field names that will be searched whenever
  573. somebody submits a search query in that text box.
  574. These fields should be some kind of text field, such as ``CharField`` or
  575. ``TextField``. You can also perform a related lookup on a ``ForeignKey`` or
  576. ``ManyToManyField`` with the lookup API "follow" notation::
  577. search_fields = ['foreign_key__related_fieldname']
  578. For example, if you have a blog entry with an author, the following
  579. definition would enable search blog entries by the email address of the
  580. author::
  581. search_fields = ['user__email']
  582. When somebody does a search in the admin search box, Django splits the
  583. search query into words and returns all objects that contain each of the
  584. words, case insensitive, where each word must be in at least one of
  585. ``search_fields``. For example, if ``search_fields`` is set to
  586. ``['first_name', 'last_name']`` and a user searches for ``john lennon``,
  587. Django will do the equivalent of this SQL ``WHERE`` clause::
  588. WHERE (first_name ILIKE '%john%' OR last_name ILIKE '%john%')
  589. AND (first_name ILIKE '%lennon%' OR last_name ILIKE '%lennon%')
  590. For faster and/or more restrictive searches, prefix the field name
  591. with an operator:
  592. ``^``
  593. Matches the beginning of the field. For example, if ``search_fields``
  594. is set to ``['^first_name', '^last_name']`` and a user searches for
  595. ``john lennon``, Django will do the equivalent of this SQL ``WHERE``
  596. clause::
  597. WHERE (first_name ILIKE 'john%' OR last_name ILIKE 'john%')
  598. AND (first_name ILIKE 'lennon%' OR last_name ILIKE 'lennon%')
  599. This query is more efficient than the normal ``'%john%'`` query,
  600. because the database only needs to check the beginning of a column's
  601. data, rather than seeking through the entire column's data. Plus, if
  602. the column has an index on it, some databases may be able to use the
  603. index for this query, even though it's a ``LIKE`` query.
  604. ``=``
  605. Matches exactly, case-insensitive. For example, if
  606. ``search_fields`` is set to ``['=first_name', '=last_name']`` and
  607. a user searches for ``john lennon``, Django will do the equivalent
  608. of this SQL ``WHERE`` clause::
  609. WHERE (first_name ILIKE 'john' OR last_name ILIKE 'john')
  610. AND (first_name ILIKE 'lennon' OR last_name ILIKE 'lennon')
  611. Note that the query input is split by spaces, so, following this
  612. example, it's currently not possible to search for all records in which
  613. ``first_name`` is exactly ``'john winston'`` (containing a space).
  614. ``@``
  615. Performs a full-text match. This is like the default search method but
  616. uses an index. Currently this is only available for MySQL.
  617. Custom template options
  618. ~~~~~~~~~~~~~~~~~~~~~~~
  619. The `Overriding Admin Templates`_ section describes how to override or extend
  620. the default admin templates. Use the following options to override the default
  621. templates used by the :class:`ModelAdmin` views:
  622. .. attribute:: ModelAdmin.add_form_template
  623. .. versionadded:: 1.2
  624. Path to a custom template, used by :meth:`add_view`.
  625. .. attribute:: ModelAdmin.change_form_template
  626. Path to a custom template, used by :meth:`change_view`.
  627. .. attribute:: ModelAdmin.change_list_template
  628. Path to a custom template, used by :meth:`changelist_view`.
  629. .. attribute:: ModelAdmin.delete_confirmation_template
  630. Path to a custom template, used by :meth:`delete_view` for displaying a
  631. confirmation page when deleting one or more objects.
  632. .. attribute:: ModelAdmin.delete_selected_confirmation_template
  633. .. versionadded:: 1.2
  634. Path to a custom template, used by the :meth:`delete_selected`
  635. action method for displaying a confirmation page when deleting one
  636. or more objects. See the :doc:`actions
  637. documentation</ref/contrib/admin/actions>`.
  638. .. attribute:: ModelAdmin.object_history_template
  639. Path to a custom template, used by :meth:`history_view`.
  640. .. _model-admin-methods:
  641. ``ModelAdmin`` methods
  642. ----------------------
  643. .. warning::
  644. :meth:`ModelAdmin.save_model` and :meth:`ModelAdmin.delete_model` must
  645. save/delete the object, they are not for veto purposes, rather they allow
  646. you to perform extra operations.
  647. .. method:: ModelAdmin.save_model(self, request, obj, form, change)
  648. The ``save_model`` method is given the ``HttpRequest``, a model instance,
  649. a ``ModelForm`` instance and a boolean value based on whether it is adding
  650. or changing the object. Here you can do any pre- or post-save operations.
  651. For example to attach ``request.user`` to the object prior to saving::
  652. class ArticleAdmin(admin.ModelAdmin):
  653. def save_model(self, request, obj, form, change):
  654. obj.user = request.user
  655. obj.save()
  656. .. method:: ModelAdmin.delete_model(self, request, obj)
  657. .. versionadded:: 1.3
  658. The ``delete_model`` method is given the ``HttpRequest`` and a model
  659. instance. Use this method to do pre- or post-delete operations.
  660. .. method:: ModelAdmin.save_formset(self, request, form, formset, change)
  661. The ``save_formset`` method is given the ``HttpRequest``, the parent
  662. ``ModelForm`` instance and a boolean value based on whether it is adding or
  663. changing the parent object.
  664. For example to attach ``request.user`` to each changed formset
  665. model instance::
  666. class ArticleAdmin(admin.ModelAdmin):
  667. def save_formset(self, request, form, formset, change):
  668. instances = formset.save(commit=False)
  669. for instance in instances:
  670. instance.user = request.user
  671. instance.save()
  672. formset.save_m2m()
  673. .. method:: ModelAdmin.get_readonly_fields(self, request, obj=None)
  674. .. versionadded:: 1.2
  675. The ``get_readonly_fields`` method is given the ``HttpRequest`` and the
  676. ``obj`` being edited (or ``None`` on an add form) and is expected to return
  677. a ``list`` or ``tuple`` of field names that will be displayed as read-only,
  678. as described above in the :attr:`ModelAdmin.readonly_fields` section.
  679. .. method:: ModelAdmin.get_prepopulated_fields(self, request, obj=None)
  680. .. versionadded:: 1.4
  681. The ``get_prepopulated_fields`` method is given the ``HttpRequest`` and the
  682. ``obj`` being edited (or ``None`` on an add form) and is expected to return
  683. a ``dictionary``, as described above in the :attr:`ModelAdmin.prepopulated_fields`
  684. section.
  685. .. method:: ModelAdmin.get_urls(self)
  686. The ``get_urls`` method on a ``ModelAdmin`` returns the URLs to be used for
  687. that ModelAdmin in the same way as a URLconf. Therefore you can extend
  688. them as documented in :doc:`/topics/http/urls`::
  689. class MyModelAdmin(admin.ModelAdmin):
  690. def get_urls(self):
  691. urls = super(MyModelAdmin, self).get_urls()
  692. my_urls = patterns('',
  693. (r'^my_view/$', self.my_view)
  694. )
  695. return my_urls + urls
  696. def my_view(self, request):
  697. # custom view which should return an HttpResponse
  698. pass
  699. .. note::
  700. Notice that the custom patterns are included *before* the regular admin
  701. URLs: the admin URL patterns are very permissive and will match nearly
  702. anything, so you'll usually want to prepend your custom URLs to the
  703. built-in ones.
  704. In this example, ``my_view`` will be accessed at
  705. ``/admin/myapp/mymodel/my_view/`` (assuming the admin URLs are included
  706. at ``/admin/``.)
  707. However, the ``self.my_view`` function registered above suffers from two
  708. problems:
  709. * It will *not* perform any permission checks, so it will be accessible
  710. to the general public.
  711. * It will *not* provide any header details to prevent caching. This means
  712. if the page retrieves data from the database, and caching middleware is
  713. active, the page could show outdated information.
  714. Since this is usually not what you want, Django provides a convenience
  715. wrapper to check permissions and mark the view as non-cacheable. This
  716. wrapper is :meth:`AdminSite.admin_view` (i.e.
  717. ``self.admin_site.admin_view`` inside a ``ModelAdmin`` instance); use it
  718. like so::
  719. class MyModelAdmin(admin.ModelAdmin):
  720. def get_urls(self):
  721. urls = super(MyModelAdmin, self).get_urls()
  722. my_urls = patterns('',
  723. (r'^my_view/$', self.admin_site.admin_view(self.my_view))
  724. )
  725. return my_urls + urls
  726. Notice the wrapped view in the fifth line above::
  727. (r'^my_view/$', self.admin_site.admin_view(self.my_view))
  728. This wrapping will protect ``self.my_view`` from unauthorized access and
  729. will apply the ``django.views.decorators.cache.never_cache`` decorator to
  730. make sure it is not cached if the cache middleware is active.
  731. If the page is cacheable, but you still want the permission check to be
  732. performed, you can pass a ``cacheable=True`` argument to
  733. :meth:`AdminSite.admin_view`::
  734. (r'^my_view/$', self.admin_site.admin_view(self.my_view, cacheable=True))
  735. .. method:: ModelAdmin.formfield_for_foreignkey(self, db_field, request, **kwargs)
  736. The ``formfield_for_foreignkey`` method on a ``ModelAdmin`` allows you to
  737. override the default formfield for a foreign key field. For example, to
  738. return a subset of objects for this foreign key field based on the user::
  739. class MyModelAdmin(admin.ModelAdmin):
  740. def formfield_for_foreignkey(self, db_field, request, **kwargs):
  741. if db_field.name == "car":
  742. kwargs["queryset"] = Car.objects.filter(owner=request.user)
  743. return super(MyModelAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
  744. This uses the ``HttpRequest`` instance to filter the ``Car`` foreign key
  745. field to only display the cars owned by the ``User`` instance.
  746. .. method:: ModelAdmin.formfield_for_manytomany(self, db_field, request, **kwargs)
  747. Like the ``formfield_for_foreignkey`` method, the
  748. ``formfield_for_manytomany`` method can be overridden to change the
  749. default formfield for a many to many field. For example, if an owner can
  750. own multiple cars and cars can belong to multiple owners -- a many to
  751. many relationship -- you could filter the ``Car`` foreign key field to
  752. only display the cars owned by the ``User``::
  753. class MyModelAdmin(admin.ModelAdmin):
  754. def formfield_for_manytomany(self, db_field, request, **kwargs):
  755. if db_field.name == "cars":
  756. kwargs["queryset"] = Car.objects.filter(owner=request.user)
  757. return super(MyModelAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)
  758. .. method:: ModelAdmin.formfield_for_choice_field(self, db_field, request, **kwargs)
  759. Like the ``formfield_for_foreignkey`` and ``formfield_for_manytomany``
  760. methods, the ``formfield_for_choice_field`` method can be overridden to
  761. change the default formfield for a field that has declared choices. For
  762. example, if the choices available to a superuser should be different than
  763. those available to regular staff, you could proceed as follows::
  764. class MyModelAdmin(admin.ModelAdmin):
  765. def formfield_for_choice_field(self, db_field, request, **kwargs):
  766. if db_field.name == "status":
  767. kwargs['choices'] = (
  768. ('accepted', 'Accepted'),
  769. ('denied', 'Denied'),
  770. )
  771. if request.user.is_superuser:
  772. kwargs['choices'] += (('ready', 'Ready for deployment'),)
  773. return super(MyModelAdmin, self).formfield_for_choice_field(db_field, request, **kwargs)
  774. .. method:: ModelAdmin.has_add_permission(self, request)
  775. Should return ``True`` if adding an object is permitted, ``False``
  776. otherwise.
  777. .. method:: ModelAdmin.has_change_permission(self, request, obj=None)
  778. Should return ``True`` if editing obj is permitted, ``False`` otherwise.
  779. If obj is ``None``, should return ``True`` or ``False`` to indicate whether
  780. editing of objects of this type is permitted in general (e.g., ``False``
  781. will be interpreted as meaning that the current user is not permitted to
  782. edit any object of this type).
  783. .. method:: ModelAdmin.has_delete_permission(self, request, obj=None)
  784. Should return ``True`` if deleting obj is permitted, ``False`` otherwise.
  785. If obj is ``None``, should return ``True`` or ``False`` to indicate whether
  786. deleting objects of this type is permitted in general (e.g., ``False`` will
  787. be interpreted as meaning that the current user is not permitted to delete
  788. any object of this type).
  789. .. method:: ModelAdmin.queryset(self, request)
  790. The ``queryset`` method on a ``ModelAdmin`` returns a
  791. :class:`~django.db.models.QuerySet` of all model instances that can be
  792. edited by the admin site. One use case for overriding this method is
  793. to show objects owned by the logged-in user::
  794. class MyModelAdmin(admin.ModelAdmin):
  795. def queryset(self, request):
  796. qs = super(MyModelAdmin, self).queryset(request)
  797. if request.user.is_superuser:
  798. return qs
  799. return qs.filter(author=request.user)
  800. .. method:: ModelAdmin.message_user(request, message)
  801. Sends a message to the user. The default implementation creates a message
  802. using the :mod:`django.contrib.messages` backend. See the
  803. :ref:`custom ModelAdmin example <custom-admin-action>`.
  804. .. method:: ModelAdmin.get_paginator(queryset, per_page, orphans=0, allow_empty_first_page=True)
  805. .. versionadded:: 1.3
  806. Returns an instance of the paginator to use for this view. By default,
  807. instantiates an instance of :attr:`paginator`.
  808. Other methods
  809. ~~~~~~~~~~~~~
  810. .. method:: ModelAdmin.add_view(self, request, form_url='', extra_context=None)
  811. Django view for the model instance addition page. See note below.
  812. .. method:: ModelAdmin.change_view(self, request, object_id, extra_context=None)
  813. Django view for the model instance edition page. See note below.
  814. .. method:: ModelAdmin.changelist_view(self, request, extra_context=None)
  815. Django view for the model instances change list/actions page. See note
  816. below.
  817. .. method:: ModelAdmin.delete_view(self, request, object_id, extra_context=None)
  818. Django view for the model instance(s) deletion confirmation page. See note
  819. below.
  820. .. method:: ModelAdmin.history_view(self, request, object_id, extra_context=None)
  821. Django view for the page that shows the modification history for a given
  822. model instance.
  823. Unlike the hook-type ``ModelAdmin`` methods detailed in the previous section,
  824. these five methods are in reality designed to be invoked as Django views from
  825. the admin application URL dispatching handler to render the pages that deal
  826. with model instances CRUD operations. As a result, completely overriding these
  827. methods will significantly change the behavior of the admin application.
  828. One common reason for overriding these methods is to augment the context data
  829. that is provided to the template that renders the view. In the following
  830. example, the change view is overridden so that the rendered template is
  831. provided some extra mapping data that would not otherwise be available::
  832. class MyModelAdmin(admin.ModelAdmin):
  833. # A template for a very customized change view:
  834. change_form_template = 'admin/myapp/extras/openstreetmap_change_form.html'
  835. def get_osm_info(self):
  836. # ...
  837. pass
  838. def change_view(self, request, object_id, extra_context=None):
  839. my_context = {
  840. 'osm_data': self.get_osm_info(),
  841. }
  842. return super(MyModelAdmin, self).change_view(request, object_id,
  843. extra_context=my_context)
  844. .. versionadded:: 1.4
  845. These views now return :class:`~django.template.response.TemplateResponse`
  846. instances which allow you to easily customize the response data before
  847. rendering. For more details, see the
  848. :doc:`TemplateResponse documentation </ref/template-response>`.
  849. ``ModelAdmin`` media definitions
  850. --------------------------------
  851. There are times where you would like add a bit of CSS and/or JavaScript to
  852. the add/change views. This can be accomplished by using a Media inner class
  853. on your ``ModelAdmin``::
  854. class ArticleAdmin(admin.ModelAdmin):
  855. class Media:
  856. css = {
  857. "all": ("my_styles.css",)
  858. }
  859. js = ("my_code.js",)
  860. .. versionchanged:: 1.3
  861. The :doc:`staticfiles app </ref/contrib/staticfiles>` prepends
  862. :setting:`STATIC_URL` (or :setting:`MEDIA_URL` if :setting:`STATIC_URL` is
  863. ``None``) to any media paths. The same rules apply as :ref:`regular media
  864. definitions on forms <form-media-paths>`.
  865. Django admin Javascript makes use of the `jQuery`_ library. To avoid
  866. conflict with user scripts, Django's jQuery is namespaced as
  867. ``django.jQuery``. If you want to use jQuery in your own admin
  868. JavaScript without including a second copy, you can use the
  869. ``django.jQuery`` object on changelist and add/edit views.
  870. .. _jQuery: http://jquery.com
  871. Adding custom validation to the admin
  872. -------------------------------------
  873. Adding custom validation of data in the admin is quite easy. The automatic
  874. admin interface reuses :mod:`django.forms`, and the ``ModelAdmin`` class gives
  875. you the ability define your own form::
  876. class ArticleAdmin(admin.ModelAdmin):
  877. form = MyArticleAdminForm
  878. ``MyArticleAdminForm`` can be defined anywhere as long as you import where
  879. needed. Now within your form you can add your own custom validation for
  880. any field::
  881. class MyArticleAdminForm(forms.ModelForm):
  882. class Meta:
  883. model = Article
  884. def clean_name(self):
  885. # do something that validates your data
  886. return self.cleaned_data["name"]
  887. It is important you use a ``ModelForm`` here otherwise things can break. See
  888. the :doc:`forms </ref/forms/index>` documentation on :doc:`custom validation
  889. </ref/forms/validation>` and, more specifically, the
  890. :ref:`model form validation notes <overriding-modelform-clean-method>` for more
  891. information.
  892. .. _admin-inlines:
  893. ``InlineModelAdmin`` objects
  894. ============================
  895. .. class:: InlineModelAdmin
  896. .. class:: TabularInline
  897. .. class:: StackedInline
  898. The admin interface has the ability to edit models on the same page as a
  899. parent model. These are called inlines. Suppose you have these two models::
  900. class Author(models.Model):
  901. name = models.CharField(max_length=100)
  902. class Book(models.Model):
  903. author = models.ForeignKey(Author)
  904. title = models.CharField(max_length=100)
  905. You can edit the books authored by an author on the author page. You add
  906. inlines to a model by specifying them in a ``ModelAdmin.inlines``::
  907. class BookInline(admin.TabularInline):
  908. model = Book
  909. class AuthorAdmin(admin.ModelAdmin):
  910. inlines = [
  911. BookInline,
  912. ]
  913. Django provides two subclasses of ``InlineModelAdmin`` and they are:
  914. * :class:`~django.contrib.admin.TabularInline`
  915. * :class:`~django.contrib.admin.StackedInline`
  916. The difference between these two is merely the template used to render
  917. them.
  918. ``InlineModelAdmin`` options
  919. -----------------------------
  920. ``InlineModelAdmin`` shares many of the same features as ``ModelAdmin``, and
  921. adds some of its own (the shared features are actually defined in the
  922. ``BaseModelAdmin`` superclass). The shared features are:
  923. - :attr:`~InlineModelAdmin.form`
  924. - :attr:`~ModelAdmin.fieldsets`
  925. - :attr:`~ModelAdmin.fields`
  926. - :attr:`~ModelAdmin.exclude`
  927. - :attr:`~ModelAdmin.filter_horizontal`
  928. - :attr:`~ModelAdmin.filter_vertical`
  929. - :attr:`~ModelAdmin.prepopulated_fields`
  930. - :attr:`~ModelAdmin.radio_fields`
  931. - :attr:`~InlineModelAdmin.raw_id_fields`
  932. - :meth:`~ModelAdmin.formfield_for_foreignkey`
  933. - :meth:`~ModelAdmin.formfield_for_manytomany`
  934. .. versionadded:: 1.2
  935. - :attr:`~ModelAdmin.readonly_fields`
  936. - :attr:`~ModelAdmin.formfield_overrides`
  937. .. versionadded:: 1.3
  938. - :attr:`~ModelAdmin.ordering`
  939. - :meth:`~ModelAdmin.queryset`
  940. The ``InlineModelAdmin`` class adds:
  941. .. attribute:: InlineModelAdmin.model
  942. The model in which the inline is using. This is required.
  943. .. attribute:: InlineModelAdmin.fk_name
  944. The name of the foreign key on the model. In most cases this will be dealt
  945. with automatically, but ``fk_name`` must be specified explicitly if there
  946. are more than one foreign key to the same parent model.
  947. .. attribute:: InlineModelAdmin.formset
  948. This defaults to ``BaseInlineFormSet``. Using your own formset can give you
  949. many possibilities of customization. Inlines are built around
  950. :ref:`model formsets <model-formsets>`.
  951. .. attribute:: InlineModelAdmin.form
  952. The value for ``form`` defaults to ``ModelForm``. This is what is passed
  953. through to ``inlineformset_factory`` when creating the formset for this
  954. inline.
  955. .. _ref-contrib-admin-inline-extra:
  956. .. attribute:: InlineModelAdmin.extra
  957. This controls the number of extra forms the formset will display in
  958. addition to the initial forms. See the
  959. :doc:`formsets documentation </topics/forms/formsets>` for more
  960. information.
  961. .. versionadded:: 1.2
  962. For users with JavaScript-enabled browsers, an "Add another" link is
  963. provided to enable any number of additional inlines to be added in addition
  964. to those provided as a result of the ``extra`` argument.
  965. The dynamic link will not appear if the number of currently displayed forms
  966. exceeds ``max_num``, or if the user does not have JavaScript enabled.
  967. .. _ref-contrib-admin-inline-max-num:
  968. .. attribute:: InlineModelAdmin.max_num
  969. This controls the maximum number of forms to show in the inline. This
  970. doesn't directly correlate to the number of objects, but can if the value
  971. is small enough. See :ref:`model-formsets-max-num` for more information.
  972. .. attribute:: InlineModelAdmin.raw_id_fields
  973. By default, Django's admin uses a select-box interface (<select>) for
  974. fields that are ``ForeignKey``. Sometimes you don't want to incur the
  975. overhead of having to select all the related instances to display in the
  976. drop-down.
  977. ``raw_id_fields`` is a list of fields you would like to change into a
  978. ``Input`` widget for either a ``ForeignKey`` or ``ManyToManyField``::
  979. class BookInline(admin.TabularInline):
  980. model = Book
  981. raw_id_fields = ("pages",)
  982. .. attribute:: InlineModelAdmin.template
  983. The template used to render the inline on the page.
  984. .. attribute:: InlineModelAdmin.verbose_name
  985. An override to the ``verbose_name`` found in the model's inner ``Meta``
  986. class.
  987. .. attribute:: InlineModelAdmin.verbose_name_plural
  988. An override to the ``verbose_name_plural`` found in the model's inner
  989. ``Meta`` class.
  990. .. attribute:: InlineModelAdmin.can_delete
  991. Specifies whether or not inline objects can be deleted in the inline.
  992. Defaults to ``True``.
  993. Working with a model with two or more foreign keys to the same parent model
  994. ---------------------------------------------------------------------------
  995. It is sometimes possible to have more than one foreign key to the same model.
  996. Take this model for instance::
  997. class Friendship(models.Model):
  998. to_person = models.ForeignKey(Person, related_name="friends")
  999. from_person = models.ForeignKey(Person, related_name="from_friends")
  1000. If you wanted to display an inline on the ``Person`` admin add/change pages
  1001. you need to explicitly define the foreign key since it is unable to do so
  1002. automatically::
  1003. class FriendshipInline(admin.TabularInline):
  1004. model = Friendship
  1005. fk_name = "to_person"
  1006. class PersonAdmin(admin.ModelAdmin):
  1007. inlines = [
  1008. FriendshipInline,
  1009. ]
  1010. Working with many-to-many models
  1011. --------------------------------
  1012. .. versionadded:: 1.2
  1013. By default, admin widgets for many-to-many relations will be displayed
  1014. on whichever model contains the actual reference to the
  1015. :class:`~django.db.models.ManyToManyField`. Depending on your ``ModelAdmin``
  1016. definition, each many-to-many field in your model will be represented by a
  1017. standard HTML ``<select multiple>``, a horizontal or vertical filter, or a
  1018. ``raw_id_admin`` widget. However, it is also possible to replace these
  1019. widgets with inlines.
  1020. Suppose we have the following models::
  1021. class Person(models.Model):
  1022. name = models.CharField(max_length=128)
  1023. class Group(models.Model):
  1024. name = models.CharField(max_length=128)
  1025. members = models.ManyToManyField(Person, related_name='groups')
  1026. If you want to display many-to-many relations using an inline, you can do
  1027. so by defining an ``InlineModelAdmin`` object for the relationship::
  1028. class MembershipInline(admin.TabularInline):
  1029. model = Group.members.through
  1030. class PersonAdmin(admin.ModelAdmin):
  1031. inlines = [
  1032. MembershipInline,
  1033. ]
  1034. class GroupAdmin(admin.ModelAdmin):
  1035. inlines = [
  1036. MembershipInline,
  1037. ]
  1038. exclude = ('members',)
  1039. There are two features worth noting in this example.
  1040. Firstly - the ``MembershipInline`` class references ``Group.members.through``.
  1041. The ``through`` attribute is a reference to the model that manages the
  1042. many-to-many relation. This model is automatically created by Django when you
  1043. define a many-to-many field.
  1044. Secondly, the ``GroupAdmin`` must manually exclude the ``members`` field.
  1045. Django displays an admin widget for a many-to-many field on the model that
  1046. defines the relation (in this case, ``Group``). If you want to use an inline
  1047. model to represent the many-to-many relationship, you must tell Django's admin
  1048. to *not* display this widget - otherwise you will end up with two widgets on
  1049. your admin page for managing the relation.
  1050. In all other respects, the ``InlineModelAdmin`` is exactly the same as any
  1051. other. You can customize the appearance using any of the normal
  1052. ``ModelAdmin`` properties.
  1053. Working with many-to-many intermediary models
  1054. ---------------------------------------------
  1055. When you specify an intermediary model using the ``through`` argument to a
  1056. :class:`~django.db.models.ManyToManyField`, the admin will not display a
  1057. widget by default. This is because each instance of that intermediary model
  1058. requires more information than could be displayed in a single widget, and the
  1059. layout required for multiple widgets will vary depending on the intermediate
  1060. model.
  1061. However, we still want to be able to edit that information inline. Fortunately,
  1062. this is easy to do with inline admin models. Suppose we have the following
  1063. models::
  1064. class Person(models.Model):
  1065. name = models.CharField(max_length=128)
  1066. class Group(models.Model):
  1067. name = models.CharField(max_length=128)
  1068. members = models.ManyToManyField(Person, through='Membership')
  1069. class Membership(models.Model):
  1070. person = models.ForeignKey(Person)
  1071. group = models.ForeignKey(Group)
  1072. date_joined = models.DateField()
  1073. invite_reason = models.CharField(max_length=64)
  1074. The first step in displaying this intermediate model in the admin is to
  1075. define an inline class for the ``Membership`` model::
  1076. class MembershipInline(admin.TabularInline):
  1077. model = Membership
  1078. extra = 1
  1079. This simple example uses the default ``InlineModelAdmin`` values for the
  1080. ``Membership`` model, and limits the extra add forms to one. This could be
  1081. customized using any of the options available to ``InlineModelAdmin`` classes.
  1082. Now create admin views for the ``Person`` and ``Group`` models::
  1083. class PersonAdmin(admin.ModelAdmin):
  1084. inlines = (MembershipInline,)
  1085. class GroupAdmin(admin.ModelAdmin):
  1086. inlines = (MembershipInline,)
  1087. Finally, register your ``Person`` and ``Group`` models with the admin site::
  1088. admin.site.register(Person, PersonAdmin)
  1089. admin.site.register(Group, GroupAdmin)
  1090. Now your admin site is set up to edit ``Membership`` objects inline from
  1091. either the ``Person`` or the ``Group`` detail pages.
  1092. .. _using-generic-relations-as-an-inline:
  1093. Using generic relations as an inline
  1094. ------------------------------------
  1095. It is possible to use an inline with generically related objects. Let's say
  1096. you have the following models::
  1097. class Image(models.Model):
  1098. image = models.ImageField(upload_to="images")
  1099. content_type = models.ForeignKey(ContentType)
  1100. object_id = models.PositiveIntegerField()
  1101. content_object = generic.GenericForeignKey("content_type", "object_id")
  1102. class Product(models.Model):
  1103. name = models.CharField(max_length=100)
  1104. If you want to allow editing and creating ``Image`` instance on the ``Product``
  1105. add/change views you can use ``GenericTabularInline`` or
  1106. ``GenericStackedInline`` (both subclasses of ``GenericInlineModelAdmin``)
  1107. provided by ``django.contrib.contenttypes.generic``, they implement tabular and
  1108. stacked visual layouts for the forms representing the inline objects
  1109. respectively just like their non-generic counterparts and behave just like any
  1110. other inline. In your ``admin.py`` for this example app::
  1111. from django.contrib import admin
  1112. from django.contrib.contenttypes import generic
  1113. from myproject.myapp.models import Image, Product
  1114. class ImageInline(generic.GenericTabularInline):
  1115. model = Image
  1116. class ProductAdmin(admin.ModelAdmin):
  1117. inlines = [
  1118. ImageInline,
  1119. ]
  1120. admin.site.register(Product, ProductAdmin)
  1121. See the :doc:`contenttypes documentation </ref/contrib/contenttypes>` for more
  1122. specific information.
  1123. Overriding admin templates
  1124. ==========================
  1125. It is relatively easy to override many of the templates which the admin module
  1126. uses to generate the various pages of an admin site. You can even override a
  1127. few of these templates for a specific app, or a specific model.
  1128. Set up your projects admin template directories
  1129. -----------------------------------------------
  1130. The admin template files are located in the ``contrib/admin/templates/admin``
  1131. directory.
  1132. In order to override one or more of them, first create an ``admin`` directory
  1133. in your project's ``templates`` directory. This can be any of the directories
  1134. you specified in :setting:`TEMPLATE_DIRS`.
  1135. Within this ``admin`` directory, create sub-directories named after your app.
  1136. Within these app subdirectories create sub-directories named after your models.
  1137. Note, that the admin app will lowercase the model name when looking for the
  1138. directory, so make sure you name the directory in all lowercase if you are
  1139. going to run your app on a case-sensitive filesystem.
  1140. To override an admin template for a specific app, copy and edit the template
  1141. from the ``django/contrib/admin/templates/admin`` directory, and save it to one
  1142. of the directories you just created.
  1143. For example, if we wanted to add a tool to the change list view for all the
  1144. models in an app named ``my_app``, we would copy
  1145. ``contrib/admin/templates/admin/change_list.html`` to the
  1146. ``templates/admin/my_app/`` directory of our project, and make any necessary
  1147. changes.
  1148. If we wanted to add a tool to the change list view for only a specific model
  1149. named 'Page', we would copy that same file to the
  1150. ``templates/admin/my_app/page`` directory of our project.
  1151. Overriding vs. replacing an admin template
  1152. ------------------------------------------
  1153. Because of the modular design of the admin templates, it is usually neither
  1154. necessary nor advisable to replace an entire template. It is almost always
  1155. better to override only the section of the template which you need to change.
  1156. To continue the example above, we want to add a new link next to the ``History``
  1157. tool for the ``Page`` model. After looking at ``change_form.html`` we determine
  1158. that we only need to override the ``object-tools`` block. Therefore here is our
  1159. new ``change_form.html`` :
  1160. .. code-block:: html+django
  1161. {% extends "admin/change_form.html" %}
  1162. {% load i18n %}
  1163. {% block object-tools %}
  1164. {% if change %}{% if not is_popup %}
  1165. <ul class="object-tools">
  1166. <li><a href="history/" class="historylink">{% trans "History" %}</a></li>
  1167. <li><a href="mylink/" class="historylink">My Link</a></li>
  1168. {% if has_absolute_url %}
  1169. <li><a href="../../../r/{{ content_type_id }}/{{ object_id }}/" class="viewsitelink">
  1170. {% trans "View on site" %}</a>
  1171. </li>
  1172. {% endif%}
  1173. </ul>
  1174. {% endif %}{% endif %}
  1175. {% endblock %}
  1176. And that's it! If we placed this file in the ``templates/admin/my_app``
  1177. directory, our link would appear on every model's change form.
  1178. Templates which may be overridden per app or model
  1179. --------------------------------------------------
  1180. Not every template in ``contrib/admin/templates/admin`` may be overridden per
  1181. app or per model. The following can:
  1182. * ``app_index.html``
  1183. * ``change_form.html``
  1184. * ``change_list.html``
  1185. * ``delete_confirmation.html``
  1186. * ``object_history.html``
  1187. For those templates that cannot be overridden in this way, you may still
  1188. override them for your entire project. Just place the new version in your
  1189. ``templates/admin`` directory. This is particularly useful to create custom 404
  1190. and 500 pages.
  1191. .. note::
  1192. Some of the admin templates, such as ``change_list_request.html`` are used
  1193. to render custom inclusion tags. These may be overridden, but in such cases
  1194. you are probably better off creating your own version of the tag in
  1195. question and giving it a different name. That way you can use it
  1196. selectively.
  1197. Root and login templates
  1198. ------------------------
  1199. If you wish to change the index, login or logout templates, you are better off
  1200. creating your own ``AdminSite`` instance (see below), and changing the
  1201. :attr:`AdminSite.index_template` , :attr:`AdminSite.login_template` or
  1202. :attr:`AdminSite.logout_template` properties.
  1203. ``AdminSite`` objects
  1204. =====================
  1205. .. class:: AdminSite(name=None)
  1206. A Django administrative site is represented by an instance of
  1207. ``django.contrib.admin.sites.AdminSite``; by default, an instance of
  1208. this class is created as ``django.contrib.admin.site`` and you can
  1209. register your models and ``ModelAdmin`` instances with it.
  1210. If you'd like to set up your own administrative site with custom
  1211. behavior, however, you're free to subclass ``AdminSite`` and override
  1212. or add anything you like. Then, simply create an instance of your
  1213. ``AdminSite`` subclass (the same way you'd instantiate any other
  1214. Python class), and register your models and ``ModelAdmin`` subclasses
  1215. with it instead of using the default.
  1216. When constructing an instance of an ``AdminSite``, you are able to provide
  1217. a unique instance name using the ``name`` argument to the constructor. This
  1218. instance name is used to identify the instance, especially when
  1219. :ref:`reversing admin URLs <admin-reverse-urls>`. If no instance name is
  1220. provided, a default instance name of ``admin`` will be used.
  1221. ``AdminSite`` attributes
  1222. ------------------------
  1223. Templates can override or extend base admin templates as described in
  1224. `Overriding Admin Templates`_.
  1225. .. attribute:: AdminSite.index_template
  1226. Path to a custom template that will be used by the admin site main index
  1227. view.
  1228. .. attribute:: AdminSite.login_template
  1229. Path to a custom template that will be used by the admin site login view.
  1230. .. attribute:: AdminSite.login_form
  1231. .. versionadded:: 1.3
  1232. Subclass of :class:`~django.contrib.auth.forms.AuthenticationForm` that
  1233. will be used by the admin site login view.
  1234. .. attribute:: AdminSite.logout_template
  1235. .. versionadded:: 1.2
  1236. Path to a custom template that will be used by the admin site logout view.
  1237. .. attribute:: AdminSite.password_change_template
  1238. .. versionadded:: 1.2
  1239. Path to a custom template that will be used by the admin site password
  1240. change view.
  1241. .. attribute:: AdminSite.password_change_done_template
  1242. .. versionadded:: 1.2
  1243. Path to a custom template that will be used by the admin site password
  1244. change done view.
  1245. Hooking ``AdminSite`` instances into your URLconf
  1246. -------------------------------------------------
  1247. The last step in setting up the Django admin is to hook your ``AdminSite``
  1248. instance into your URLconf. Do this by pointing a given URL at the
  1249. ``AdminSite.urls`` method.
  1250. In this example, we register the default ``AdminSite`` instance
  1251. ``django.contrib.admin.site`` at the URL ``/admin/`` ::
  1252. # urls.py
  1253. from django.conf.urls.defaults import *
  1254. from django.contrib import admin
  1255. admin.autodiscover()
  1256. urlpatterns = patterns('',
  1257. (r'^admin/', include(admin.site.urls)),
  1258. )
  1259. Above we used ``admin.autodiscover()`` to automatically load the
  1260. ``INSTALLED_APPS`` admin.py modules.
  1261. In this example, we register the ``AdminSite`` instance
  1262. ``myproject.admin.admin_site`` at the URL ``/myadmin/`` ::
  1263. # urls.py
  1264. from django.conf.urls.defaults import *
  1265. from myproject.admin import admin_site
  1266. urlpatterns = patterns('',
  1267. (r'^myadmin/', include(admin_site.urls)),
  1268. )
  1269. There is really no need to use autodiscover when using your own ``AdminSite``
  1270. instance since you will likely be importing all the per-app admin.py modules
  1271. in your ``myproject.admin`` module.
  1272. Multiple admin sites in the same URLconf
  1273. ----------------------------------------
  1274. It's easy to create multiple instances of the admin site on the same
  1275. Django-powered Web site. Just create multiple instances of ``AdminSite`` and
  1276. root each one at a different URL.
  1277. In this example, the URLs ``/basic-admin/`` and ``/advanced-admin/`` feature
  1278. separate versions of the admin site -- using the ``AdminSite`` instances
  1279. ``myproject.admin.basic_site`` and ``myproject.admin.advanced_site``,
  1280. respectively::
  1281. # urls.py
  1282. from django.conf.urls.defaults import *
  1283. from myproject.admin import basic_site, advanced_site
  1284. urlpatterns = patterns('',
  1285. (r'^basic-admin/', include(basic_site.urls)),
  1286. (r'^advanced-admin/', include(advanced_site.urls)),
  1287. )
  1288. ``AdminSite`` instances take a single argument to their constructor, their
  1289. name, which can be anything you like. This argument becomes the prefix to the
  1290. URL names for the purposes of :ref:`reversing them<admin-reverse-urls>`. This
  1291. is only necessary if you are using more than one ``AdminSite``.
  1292. Adding views to admin sites
  1293. ---------------------------
  1294. Just like :class:`ModelAdmin`, :class:`AdminSite` provides a
  1295. :meth:`~django.contrib.admin.ModelAdmin.get_urls()` method
  1296. that can be overridden to define additional views for the site. To add
  1297. a new view to your admin site, extend the base
  1298. :meth:`~django.contrib.admin.ModelAdmin.get_urls()` method to include
  1299. a pattern for your new view.
  1300. .. note::
  1301. Any view you render that uses the admin templates, or extends the base
  1302. admin template, should provide the ``current_app`` argument to
  1303. :class:`~django.template.RequestContext` or :class:`~django.template.Context`
  1304. when rendering the template. It should be set to either ``self.name`` if
  1305. your view is on an ``AdminSite`` or ``self.admin_site.name`` if your view
  1306. is on a ``ModelAdmin``.
  1307. .. _admin-reverse-urls:
  1308. Reversing admin URLs
  1309. ====================
  1310. When an :class:`AdminSite` is deployed, the views provided by that site are
  1311. accessible using Django's :ref:`URL reversing system <naming-url-patterns>`.
  1312. The :class:`AdminSite` provides the following named URL patterns:
  1313. ====================== ======================== =============
  1314. Page URL name Parameters
  1315. ====================== ======================== =============
  1316. Index ``index``
  1317. Logout ``logout``
  1318. Password change ``password_change``
  1319. Password change done ``password_change_done``
  1320. i18n javascript ``jsi18n``
  1321. Application index page ``app_list`` ``app_label``
  1322. ====================== ======================== =============
  1323. Each :class:`ModelAdmin` instance provides an additional set of named URLs:
  1324. ====================== =============================================== =============
  1325. Page URL name Parameters
  1326. ====================== =============================================== =============
  1327. Changelist ``{{ app_label }}_{{ model_name }}_changelist``
  1328. Add ``{{ app_label }}_{{ model_name }}_add``
  1329. History ``{{ app_label }}_{{ model_name }}_history`` ``object_id``
  1330. Delete ``{{ app_label }}_{{ model_name }}_delete`` ``object_id``
  1331. Change ``{{ app_label }}_{{ model_name }}_change`` ``object_id``
  1332. ====================== =============================================== =============
  1333. These named URLs are registered with the application namespace ``admin``, and
  1334. with an instance namespace corresponding to the name of the Site instance.
  1335. So - if you wanted to get a reference to the Change view for a particular
  1336. ``Choice`` object (from the polls application) in the default admin, you would
  1337. call::
  1338. >>> from django.core import urlresolvers
  1339. >>> c = Choice.objects.get(...)
  1340. >>> change_url = urlresolvers.reverse('admin:polls_choice_change', args=(c.id,))
  1341. This will find the first registered instance of the admin application
  1342. (whatever the instance name), and resolve to the view for changing
  1343. ``poll.Choice`` instances in that instance.
  1344. If you want to find a URL in a specific admin instance, provide the name of
  1345. that instance as a ``current_app`` hint to the reverse call. For example,
  1346. if you specifically wanted the admin view from the admin instance named
  1347. ``custom``, you would need to call::
  1348. >>> change_url = urlresolvers.reverse('custom:polls_choice_change', args=(c.id,))
  1349. For more details, see the documentation on :ref:`reversing namespaced URLs
  1350. <topics-http-reversing-url-namespaces>`.