index.txt 67 KB

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