index.txt 59 KB

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