index.txt 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606
  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. .. admonition:: Note
  12. The admin site has been refactored significantly since Django 0.96. This
  13. document describes the newest version of the admin site, which allows for
  14. much richer customization. If you follow the development of Django itself,
  15. you may have heard this described as "newforms-admin."
  16. Overview
  17. ========
  18. There are six steps in activating the Django admin site:
  19. 1. Add ``'django.contrib.admin'`` to your :setting:`INSTALLED_APPS`
  20. setting.
  21. 2. Admin has two dependencies - ``django.contrib.auth`` and
  22. ``django.contrib.contenttypes``. If these applications are not
  23. in your :setting:`INSTALLED_APPS` list, add them.
  24. 3. Determine which of your application's models should be editable in the
  25. admin interface.
  26. 4. 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. 5. Instantiate an ``AdminSite`` and tell it about each of your models and
  30. ``ModelAdmin`` classes.
  31. 6. Hook the ``AdminSite`` instance into your URLconf.
  32. Other topics
  33. ------------
  34. .. toctree::
  35. :maxdepth: 1
  36. actions
  37. .. seealso::
  38. For information about serving the media files (images, JavaScript, and CSS)
  39. associated with the admin in production, see :ref:`serving-media-files`.
  40. ``ModelAdmin`` objects
  41. ======================
  42. .. class:: ModelAdmin
  43. The ``ModelAdmin`` class is the representation of a model in the admin
  44. interface. These are stored in a file named ``admin.py`` in your application.
  45. Let's take a look at a very simple example of the ``ModelAdmin``::
  46. from django.contrib import admin
  47. from myproject.myapp.models import Author
  48. class AuthorAdmin(admin.ModelAdmin):
  49. pass
  50. admin.site.register(Author, AuthorAdmin)
  51. .. admonition:: Do you need a ``ModelAdmin`` object at all?
  52. In the preceding example, the ``ModelAdmin`` class doesn't define any
  53. custom values (yet). As a result, the default admin interface will be
  54. provided. If you are happy with the default admin interface, you don't
  55. need to define a ``ModelAdmin`` object at all -- you can register the
  56. model class without providing a ``ModelAdmin`` description. The
  57. preceding example could be simplified to::
  58. from django.contrib import admin
  59. from myproject.myapp.models import Author
  60. admin.site.register(Author)
  61. ``ModelAdmin`` Options
  62. ----------------------
  63. The ``ModelAdmin`` is very flexible. It has several options for dealing with
  64. customizing the interface. All options are defined on the ``ModelAdmin``
  65. subclass::
  66. class AuthorAdmin(admin.ModelAdmin):
  67. date_hierarchy = 'pub_date'
  68. .. attribute:: ModelAdmin.date_hierarchy
  69. Set ``date_hierarchy`` to the name of a ``DateField`` or ``DateTimeField`` in
  70. your model, and the change list page will include a date-based drilldown
  71. navigation by that field.
  72. Example::
  73. date_hierarchy = 'pub_date'
  74. .. attribute:: ModelAdmin.form
  75. By default a ``ModelForm`` is dynamically created for your model. It is used
  76. to create the form presented on both the add/change pages. You can easily
  77. provide your own ``ModelForm`` to override any default form behavior on the
  78. add/change pages.
  79. For an example see the section `Adding custom validation to the admin`_.
  80. .. attribute:: ModelAdmin.fieldsets
  81. Set ``fieldsets`` to control the layout of admin "add" and "change" pages.
  82. ``fieldsets`` is a list of two-tuples, in which each two-tuple represents a
  83. ``<fieldset>`` on the admin form page. (A ``<fieldset>`` is a "section" of the
  84. form.)
  85. The two-tuples are in the format ``(name, field_options)``, where ``name`` is a
  86. string representing the title of the fieldset and ``field_options`` is a
  87. dictionary of information about the fieldset, including a list of fields to be
  88. displayed in it.
  89. A full example, taken from the ``django.contrib.flatpages.FlatPage`` model::
  90. class FlatPageAdmin(admin.ModelAdmin):
  91. fieldsets = (
  92. (None, {
  93. 'fields': ('url', 'title', 'content', 'sites')
  94. }),
  95. ('Advanced options', {
  96. 'classes': ('collapse',),
  97. 'fields': ('enable_comments', 'registration_required', 'template_name')
  98. }),
  99. )
  100. This results in an admin page that looks like:
  101. .. image:: _images/flatfiles_admin.png
  102. If ``fieldsets`` isn't given, Django will default to displaying each field
  103. that isn't an ``AutoField`` and has ``editable=True``, in a single fieldset,
  104. in the same order as the fields are defined in the model.
  105. The ``field_options`` dictionary can have the following keys:
  106. * ``fields``
  107. A tuple of field names to display in this fieldset. This key is
  108. required.
  109. Example::
  110. {
  111. 'fields': ('first_name', 'last_name', 'address', 'city', 'state'),
  112. }
  113. To display multiple fields on the same line, wrap those fields in
  114. their own tuple. In this example, the ``first_name`` and ``last_name``
  115. fields will display on the same line::
  116. {
  117. 'fields': (('first_name', 'last_name'), 'address', 'city', 'state'),
  118. }
  119. .. versionadded:: 1.2
  120. ``fields`` can contain values defined in
  121. :attr:`ModelAdmin.readonly_fields` to be displayed as read-only.
  122. * ``classes``
  123. A list containing extra CSS classes to apply to the fieldset.
  124. Example::
  125. {
  126. 'classes': ['wide', 'extrapretty'],
  127. }
  128. Two useful classes defined by the default admin site stylesheet are
  129. ``collapse`` and ``wide``. Fieldsets with the ``collapse`` style will
  130. be initially collapsed in the admin and replaced with a small
  131. "click to expand" link. Fieldsets with the ``wide`` style will be
  132. given extra horizontal space.
  133. * ``description``
  134. A string of optional extra text to be displayed at the top of each
  135. fieldset, under the heading of the fieldset.
  136. Note that this value is *not* HTML-escaped when it's displayed in
  137. the admin interface. This lets you include HTML if you so desire.
  138. Alternatively you can use plain text and
  139. ``django.utils.html.escape()`` to escape any HTML special
  140. characters.
  141. .. attribute:: ModelAdmin.fields
  142. Use this option as an alternative to ``fieldsets`` if the layout does not
  143. matter and if you want to only show a subset of the available fields in the
  144. form. For example, you could define a simpler version of the admin form for
  145. the ``django.contrib.flatpages.FlatPage`` model as follows::
  146. class FlatPageAdmin(admin.ModelAdmin):
  147. fields = ('url', 'title', 'content')
  148. In the above example, only the fields 'url', 'title' and 'content' will be
  149. displayed, sequentially, in the form.
  150. .. versionadded:: 1.2
  151. ``fields`` can contain values defined in :attr:`ModelAdmin.readonly_fields`
  152. to be displayed as read-only.
  153. .. admonition:: Note
  154. This ``fields`` option should not be confused with the ``fields``
  155. dictionary key that is within the ``fieldsets`` option, as described in
  156. the previous section.
  157. .. attribute:: ModelAdmin.exclude
  158. This attribute, if given, should be a list of field names to exclude from the
  159. form.
  160. For example, let's consider the following model::
  161. class Author(models.Model):
  162. name = models.CharField(max_length=100)
  163. title = models.CharField(max_length=3)
  164. birth_date = models.DateField(blank=True, null=True)
  165. If you want a form for the ``Author`` model that includes only the ``name``
  166. and ``title`` fields, you would specify ``fields`` or ``exclude`` like this::
  167. class AuthorAdmin(admin.ModelAdmin):
  168. fields = ('name', 'title')
  169. class AuthorAdmin(admin.ModelAdmin):
  170. exclude = ('birth_date',)
  171. Since the Author model only has three fields, ``name``, ``title``, and
  172. ``birth_date``, the forms resulting from the above declarations will contain
  173. exactly the same fields.
  174. .. attribute:: ModelAdmin.filter_horizontal
  175. Use a nifty unobtrusive JavaScript "filter" interface instead of the
  176. usability-challenged ``<select multiple>`` in the admin form. The value is a
  177. list of fields that should be displayed as a horizontal filter interface. See
  178. ``filter_vertical`` to use a vertical interface.
  179. .. attribute:: ModelAdmin.filter_vertical
  180. Same as ``filter_horizontal``, but is a vertical display of the filter
  181. interface.
  182. .. attribute:: ModelAdmin.list_display
  183. Set ``list_display`` to control which fields are displayed on the change list
  184. page of the admin.
  185. Example::
  186. list_display = ('first_name', 'last_name')
  187. If you don't set ``list_display``, the admin site will display a single column
  188. that displays the ``__unicode__()`` representation of each object.
  189. You have four possible values that can be used in ``list_display``:
  190. * A field of the model. For example::
  191. class PersonAdmin(admin.ModelAdmin):
  192. list_display = ('first_name', 'last_name')
  193. * A callable that accepts one parameter for the model instance. For
  194. example::
  195. def upper_case_name(obj):
  196. return ("%s %s" % (obj.first_name, obj.last_name)).upper()
  197. upper_case_name.short_description = 'Name'
  198. class PersonAdmin(admin.ModelAdmin):
  199. list_display = (upper_case_name,)
  200. * A string representing an attribute on the ``ModelAdmin``. This behaves
  201. same as the callable. For example::
  202. class PersonAdmin(admin.ModelAdmin):
  203. list_display = ('upper_case_name',)
  204. def upper_case_name(self, obj):
  205. return ("%s %s" % (obj.first_name, obj.last_name)).upper()
  206. upper_case_name.short_description = 'Name'
  207. * A string representing an attribute on the model. This behaves almost
  208. the same as the callable, but ``self`` in this context is the model
  209. instance. Here's a full model example::
  210. class Person(models.Model):
  211. name = models.CharField(max_length=50)
  212. birthday = models.DateField()
  213. def decade_born_in(self):
  214. return self.birthday.strftime('%Y')[:3] + "0's"
  215. decade_born_in.short_description = 'Birth decade'
  216. class PersonAdmin(admin.ModelAdmin):
  217. list_display = ('name', 'decade_born_in')
  218. A few special cases to note about ``list_display``:
  219. * If the field is a ``ForeignKey``, Django will display the
  220. ``__unicode__()`` of the related object.
  221. * ``ManyToManyField`` fields aren't supported, because that would entail
  222. executing a separate SQL statement for each row in the table. If you
  223. want to do this nonetheless, give your model a custom method, and add
  224. that method's name to ``list_display``. (See below for more on custom
  225. methods in ``list_display``.)
  226. * If the field is a ``BooleanField`` or ``NullBooleanField``, Django will
  227. display a pretty "on" or "off" icon instead of ``True`` or ``False``.
  228. * If the string given is a method of the model, ``ModelAdmin`` or a
  229. callable, Django will HTML-escape the output by default. If you'd rather
  230. not escape the output of the method, give the method an ``allow_tags``
  231. attribute whose value is ``True``.
  232. Here's a full example model::
  233. class Person(models.Model):
  234. first_name = models.CharField(max_length=50)
  235. last_name = models.CharField(max_length=50)
  236. color_code = models.CharField(max_length=6)
  237. def colored_name(self):
  238. return '<span style="color: #%s;">%s %s</span>' % (self.color_code, self.first_name, self.last_name)
  239. colored_name.allow_tags = True
  240. class PersonAdmin(admin.ModelAdmin):
  241. list_display = ('first_name', 'last_name', 'colored_name')
  242. * If the string given is a method of the model, ``ModelAdmin`` or a
  243. callable that returns True or False Django will display a pretty "on" or
  244. "off" icon if you give the method a ``boolean`` attribute whose value is
  245. ``True``.
  246. Here's a full example model::
  247. class Person(models.Model):
  248. first_name = models.CharField(max_length=50)
  249. birthday = models.DateField()
  250. def born_in_fifties(self):
  251. return self.birthday.strftime('%Y')[:3] == '195'
  252. born_in_fifties.boolean = True
  253. class PersonAdmin(admin.ModelAdmin):
  254. list_display = ('name', 'born_in_fifties')
  255. * The ``__str__()`` and ``__unicode__()`` methods are just as valid in
  256. ``list_display`` as any other model method, so it's perfectly OK to do
  257. this::
  258. list_display = ('__unicode__', 'some_other_field')
  259. * Usually, elements of ``list_display`` that aren't actual database fields
  260. can't be used in sorting (because Django does all the sorting at the
  261. database level).
  262. However, if an element of ``list_display`` represents a certain database
  263. field, you can indicate this fact by setting the ``admin_order_field``
  264. attribute of the item.
  265. For example::
  266. class Person(models.Model):
  267. first_name = models.CharField(max_length=50)
  268. color_code = models.CharField(max_length=6)
  269. def colored_first_name(self):
  270. return '<span style="color: #%s;">%s</span>' % (self.color_code, self.first_name)
  271. colored_first_name.allow_tags = True
  272. colored_first_name.admin_order_field = 'first_name'
  273. class PersonAdmin(admin.ModelAdmin):
  274. list_display = ('first_name', 'colored_first_name')
  275. The above will tell Django to order by the ``first_name`` field when
  276. trying to sort by ``colored_first_name`` in the admin.
  277. .. attribute:: ModelAdmin.list_display_links
  278. Set ``list_display_links`` to control which fields in ``list_display`` should
  279. be linked to the "change" page for an object.
  280. By default, the change list page will link the first column -- the first field
  281. specified in ``list_display`` -- to the change page for each item. But
  282. ``list_display_links`` lets you change which columns are linked. Set
  283. ``list_display_links`` to a list or tuple of field names (in the same format as
  284. ``list_display``) to link.
  285. ``list_display_links`` can specify one or many field names. As long as the
  286. field names appear in ``list_display``, Django doesn't care how many (or how
  287. few) fields are linked. The only requirement is: If you want to use
  288. ``list_display_links``, you must define ``list_display``.
  289. In this example, the ``first_name`` and ``last_name`` fields will be linked on
  290. the change list page::
  291. class PersonAdmin(admin.ModelAdmin):
  292. list_display = ('first_name', 'last_name', 'birthday')
  293. list_display_links = ('first_name', 'last_name')
  294. .. _admin-list-editable:
  295. .. attribute:: ModelAdmin.list_editable
  296. .. versionadded:: 1.1
  297. Set ``list_editable`` to a list of field names on the model which will allow
  298. editing on the change list page. That is, fields listed in ``list_editable``
  299. will be displayed as form widgets on the change list page, allowing users to
  300. edit and save multiple rows at once.
  301. .. note::
  302. ``list_editable`` interacts with a couple of other options in particular
  303. ways; you should note the following rules:
  304. * Any field in ``list_editable`` must also be in ``list_display``. You
  305. can't edit a field that's not displayed!
  306. * The same field can't be listed in both ``list_editable`` and
  307. ``list_display_links`` -- a field can't be both a form and a link.
  308. You'll get a validation error if either of these rules are broken.
  309. .. attribute:: ModelAdmin.list_filter
  310. Set ``list_filter`` to activate filters in the right sidebar of the change list
  311. page of the admin. This should be a list of field names, and each specified
  312. field should be either a ``BooleanField``, ``CharField``, ``DateField``,
  313. ``DateTimeField``, ``IntegerField`` or ``ForeignKey``.
  314. This example, taken from the ``django.contrib.auth.models.User`` model, shows
  315. how both ``list_display`` and ``list_filter`` work::
  316. class UserAdmin(admin.ModelAdmin):
  317. list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff')
  318. list_filter = ('is_staff', 'is_superuser')
  319. The above code results in an admin change list page that looks like this:
  320. .. image:: _images/users_changelist.png
  321. (This example also has ``search_fields`` defined. See below.)
  322. .. attribute:: ModelAdmin.list_per_page
  323. Set ``list_per_page`` to control how many items appear on each paginated admin
  324. change list page. By default, this is set to ``100``.
  325. .. attribute:: ModelAdmin.list_select_related
  326. Set ``list_select_related`` to tell Django to use
  327. :meth:`~django.db.models.QuerySet.select_related` in retrieving the list of
  328. objects on the admin change list page. This can save you a bunch of database
  329. queries.
  330. The value should be either ``True`` or ``False``. Default is ``False``.
  331. Note that Django will use :meth:`~django.db.models.QuerySet.select_related`,
  332. regardless of this setting, if one of the ``list_display`` fields is a
  333. ``ForeignKey``.
  334. .. attribute:: ModelAdmin.inlines
  335. See ``InlineModelAdmin`` objects below.
  336. .. attribute:: ModelAdmin.ordering
  337. Set ``ordering`` to specify how objects on the admin change list page should be
  338. ordered. This should be a list or tuple in the same format as a model's
  339. ``ordering`` parameter.
  340. If this isn't provided, the Django admin will use the model's default ordering.
  341. .. admonition:: Note
  342. Django will only honor the first element in the list/tuple; any others
  343. will be ignored.
  344. .. attribute:: ModelAdmin.prepopulated_fields
  345. Set ``prepopulated_fields`` to a dictionary mapping field names to the fields
  346. it should prepopulate from::
  347. class ArticleAdmin(admin.ModelAdmin):
  348. prepopulated_fields = {"slug": ("title",)}
  349. When set, the given fields will use a bit of JavaScript to populate from the
  350. fields assigned. The main use for this functionality is to automatically
  351. generate the value for ``SlugField`` fields from one or more other fields. The
  352. generated value is produced by concatenating the values of the source fields,
  353. and then by transforming that result into a valid slug (e.g. substituting
  354. dashes for spaces).
  355. ``prepopulated_fields`` doesn't accept ``DateTimeField``, ``ForeignKey``, nor
  356. ``ManyToManyField`` fields.
  357. .. attribute:: ModelAdmin.radio_fields
  358. By default, Django's admin uses a select-box interface (<select>) for
  359. fields that are ``ForeignKey`` or have ``choices`` set. If a field is present
  360. in ``radio_fields``, Django will use a radio-button interface instead.
  361. Assuming ``group`` is a ``ForeignKey`` on the ``Person`` model::
  362. class PersonAdmin(admin.ModelAdmin):
  363. radio_fields = {"group": admin.VERTICAL}
  364. You have the choice of using ``HORIZONTAL`` or ``VERTICAL`` from the
  365. ``django.contrib.admin`` module.
  366. Don't include a field in ``radio_fields`` unless it's a ``ForeignKey`` or has
  367. ``choices`` set.
  368. .. attribute:: ModelAdmin.raw_id_fields
  369. By default, Django's admin uses a select-box interface (<select>) for
  370. fields that are ``ForeignKey``. Sometimes you don't want to incur the
  371. overhead of having to select all the related instances to display in the
  372. drop-down.
  373. ``raw_id_fields`` is a list of fields you would like to change
  374. into a ``Input`` widget for either a ``ForeignKey`` or ``ManyToManyField``::
  375. class ArticleAdmin(admin.ModelAdmin):
  376. raw_id_fields = ("newspaper",)
  377. .. attribute:: ModelAdmin.readonly_fields
  378. .. versionadded:: 1.2
  379. By default the admin shows all fields as editable. Any fields in this option
  380. (which should be a ``list`` or ``tuple``) will display its data as-is and
  381. non-editable. This option behaves nearly identical to :attr:`ModelAdmin.list_display`.
  382. Usage is the same, however, when you specify :attr:`ModelAdmin.fields` or
  383. :attr:`ModelAdmin.fieldsets` the read-only fields must be present to be shown
  384. (they are ignored otherwise).
  385. If ``readonly_fields`` is used without defining explicit ordering through
  386. :attr:`ModelAdmin.fields` or :attr:`ModelAdmin.fieldsets` they will be added
  387. last after all editable fields.
  388. .. attribute:: ModelAdmin.save_as
  389. Set ``save_as`` to enable a "save as" feature on admin change forms.
  390. Normally, objects have three save options: "Save", "Save and continue editing"
  391. and "Save and add another". If ``save_as`` is ``True``, "Save and add another"
  392. will be replaced by a "Save as" button.
  393. "Save as" means the object will be saved as a new object (with a new ID),
  394. rather than the old object.
  395. By default, ``save_as`` is set to ``False``.
  396. .. attribute:: ModelAdmin.save_on_top
  397. Set ``save_on_top`` to add save buttons across the top of your admin change
  398. forms.
  399. Normally, the save buttons appear only at the bottom of the forms. If you set
  400. ``save_on_top``, the buttons will appear both on the top and the bottom.
  401. By default, ``save_on_top`` is set to ``False``.
  402. .. attribute:: ModelAdmin.search_fields
  403. Set ``search_fields`` to enable a search box on the admin change list page.
  404. This should be set to a list of field names that will be searched whenever
  405. somebody submits a search query in that text box.
  406. These fields should be some kind of text field, such as ``CharField`` or
  407. ``TextField``. You can also perform a related lookup on a ``ForeignKey`` or
  408. ``ManyToManyField`` with the lookup API "follow" notation::
  409. search_fields = ['foreign_key__related_fieldname']
  410. For example, if you have a blog entry with an author, the following definition
  411. would enable search blog entries by the email address of the author::
  412. search_fields = ['user__email']
  413. When somebody does a search in the admin search box, Django splits the search
  414. query into words and returns all objects that contain each of the words, case
  415. insensitive, where each word must be in at least one of ``search_fields``. For
  416. example, if ``search_fields`` is set to ``['first_name', 'last_name']`` and a
  417. user searches for ``john lennon``, Django will do the equivalent of this SQL
  418. ``WHERE`` clause::
  419. WHERE (first_name ILIKE '%john%' OR last_name ILIKE '%john%')
  420. AND (first_name ILIKE '%lennon%' OR last_name ILIKE '%lennon%')
  421. For faster and/or more restrictive searches, prefix the field name
  422. with an operator:
  423. ``^``
  424. Matches the beginning of the field. For example, if ``search_fields`` is
  425. set to ``['^first_name', '^last_name']`` and a user searches for
  426. ``john lennon``, Django will do the equivalent of this SQL ``WHERE``
  427. clause::
  428. WHERE (first_name ILIKE 'john%' OR last_name ILIKE 'john%')
  429. AND (first_name ILIKE 'lennon%' OR last_name ILIKE 'lennon%')
  430. This query is more efficient than the normal ``'%john%'`` query, because
  431. the database only needs to check the beginning of a column's data, rather
  432. than seeking through the entire column's data. Plus, if the column has an
  433. index on it, some databases may be able to use the index for this query,
  434. even though it's a ``LIKE`` query.
  435. ``=``
  436. Matches exactly, case-insensitive. For example, if
  437. ``search_fields`` is set to ``['=first_name', '=last_name']`` and
  438. a user searches for ``john lennon``, Django will do the equivalent
  439. of this SQL ``WHERE`` clause::
  440. WHERE (first_name ILIKE 'john' OR last_name ILIKE 'john')
  441. AND (first_name ILIKE 'lennon' OR last_name ILIKE 'lennon')
  442. Note that the query input is split by spaces, so, following this example,
  443. it's currently not possible to search for all records in which
  444. ``first_name`` is exactly ``'john winston'`` (containing a space).
  445. ``@``
  446. Performs a full-text match. This is like the default search method but uses
  447. an index. Currently this is only available for MySQL.
  448. .. attribute:: ModelAdmin.formfield_overrides
  449. .. versionadded:: 1.1
  450. This provides a quick-and-dirty way to override some of the
  451. :class:`~django.forms.Field` options for use in the admin.
  452. ``formfield_overrides`` is a dictionary mapping a field class to a dict of
  453. arguments to pass to the field at construction time.
  454. Since that's a bit abstract, let's look at a concrete example. The most common
  455. use of ``formfield_overrides`` is to add a custom widget for a certain type of
  456. field. So, imagine we've written a ``RichTextEditorWidget`` that we'd like to
  457. use for large text fields instead of the default ``<textarea>``. Here's how we'd
  458. do that::
  459. from django.db import models
  460. from django.contrib import admin
  461. # Import our custom widget and our model from where they're defined
  462. from myapp.widgets import RichTextEditorWidget
  463. from myapp.models import MyModel
  464. class MyModelAdmin(admin.ModelAdmin):
  465. formfield_overrides = {
  466. models.TextField: {'widget': RichTextEditorWidget},
  467. }
  468. Note that the key in the dictionary is the actual field class, *not* a string.
  469. The value is another dictionary; these arguments will be passed to
  470. :meth:`~django.forms.Field.__init__`. See :doc:`/ref/forms/api` for details.
  471. .. warning::
  472. If you want to use a custom widget with a relation field (i.e.
  473. :class:`~django.db.models.ForeignKey` or
  474. :class:`~django.db.models.ManyToManyField`), make sure you haven't included
  475. that field's name in ``raw_id_fields`` or ``radio_fields``.
  476. ``formfield_overrides`` won't let you change the widget on relation fields
  477. that have ``raw_id_fields`` or ``radio_fields`` set. That's because
  478. ``raw_id_fields`` and ``radio_fields`` imply custom widgets of their own.
  479. .. attribute:: ModelAdmin.actions
  480. .. versionadded:: 1.1
  481. A list of actions to make available on the change list page. See
  482. :doc:`/ref/contrib/admin/actions` for details.
  483. .. attribute:: ModelAdmin.actions_on_top
  484. .. attribute:: ModelAdmin.actions_on_bottom
  485. .. versionadded:: 1.1
  486. Controls where on the page the actions bar appears. By default, the admin
  487. changelist displays actions at the top of the page (``actions_on_top = True;
  488. actions_on_bottom = False``).
  489. .. attribute:: ModelAdmin.actions_selection_counter
  490. .. versionadded:: 1.2
  491. Controls whether a selection counter is display next to the action dropdown.
  492. By default, the admin changelist will display it
  493. (``actions_selection_counter = True``).
  494. Custom template options
  495. ~~~~~~~~~~~~~~~~~~~~~~~
  496. The `Overriding Admin Templates`_ section describes how to override or extend
  497. the default admin templates. Use the following options to override the default
  498. templates used by the :class:`ModelAdmin` views:
  499. .. attribute:: ModelAdmin.add_form_template
  500. .. versionadded:: 1.2
  501. Path to a custom template, used by :meth:`add_view`.
  502. .. attribute:: ModelAdmin.change_form_template
  503. Path to a custom template, used by :meth:`change_view`.
  504. .. attribute:: ModelAdmin.change_list_template
  505. Path to a custom template, used by :meth:`changelist_view`.
  506. .. attribute:: ModelAdmin.delete_confirmation_template
  507. Path to a custom template, used by :meth:`delete_view` for displaying a
  508. confirmation page when deleting one or more objects.
  509. .. attribute:: ModelAdmin.delete_selected_confirmation_template
  510. .. versionadded:: 1.2
  511. Path to a custom template, used by the :meth:`delete_selected`
  512. action method for displaying a confirmation page when deleting one
  513. or more objects. See the :doc:`actions
  514. documentation</ref/contrib/admin/actions>`.
  515. .. attribute:: ModelAdmin.object_history_template
  516. Path to a custom template, used by :meth:`history_view`.
  517. .. _model-admin-methods:
  518. ``ModelAdmin`` methods
  519. ----------------------
  520. .. method:: ModelAdmin.save_model(self, request, obj, form, change)
  521. The ``save_model`` method is given the ``HttpRequest``, a model instance,
  522. a ``ModelForm`` instance and a boolean value based on whether it is adding or
  523. changing the object. Here you can do any pre- or post-save operations.
  524. For example to attach ``request.user`` to the object prior to saving::
  525. class ArticleAdmin(admin.ModelAdmin):
  526. def save_model(self, request, obj, form, change):
  527. obj.user = request.user
  528. obj.save()
  529. .. method:: ModelAdmin.save_formset(self, request, form, formset, change)
  530. The ``save_formset`` method is given the ``HttpRequest``, the parent
  531. ``ModelForm`` instance and a boolean value based on whether it is adding or
  532. changing the parent object.
  533. For example to attach ``request.user`` to each changed formset
  534. model instance::
  535. class ArticleAdmin(admin.ModelAdmin):
  536. def save_formset(self, request, form, formset, change):
  537. instances = formset.save(commit=False)
  538. for instance in instances:
  539. instance.user = request.user
  540. instance.save()
  541. formset.save_m2m()
  542. .. method:: ModelAdmin.get_readonly_fields(self, request, obj=None)
  543. .. versionadded:: 1.2
  544. The ``get_readonly_fields`` method is given the ``HttpRequest`` and the
  545. ``obj`` being edited (or ``None`` on an add form) and is expected to return a
  546. ``list`` or ``tuple`` of field names that will be displayed as read-only, as
  547. described above in the :attr:`ModelAdmin.readonly_fields` section.
  548. .. method:: ModelAdmin.get_urls(self)
  549. .. versionadded:: 1.1
  550. The ``get_urls`` method on a ``ModelAdmin`` returns the URLs to be used for
  551. that ModelAdmin in the same way as a URLconf. Therefore you can extend them as
  552. documented in :doc:`/topics/http/urls`::
  553. class MyModelAdmin(admin.ModelAdmin):
  554. def get_urls(self):
  555. urls = super(MyModelAdmin, self).get_urls()
  556. my_urls = patterns('',
  557. (r'^my_view/$', self.my_view)
  558. )
  559. return my_urls + urls
  560. .. note::
  561. Notice that the custom patterns are included *before* the regular admin
  562. URLs: the admin URL patterns are very permissive and will match nearly
  563. anything, so you'll usually want to prepend your custom URLs to the built-in
  564. ones.
  565. However, the ``self.my_view`` function registered above suffers from two
  566. problems:
  567. * It will *not* perform any permission checks, so it will be accessible to
  568. the general public.
  569. * It will *not* provide any header details to prevent caching. This means if
  570. the page retrieves data from the database, and caching middleware is
  571. active, the page could show outdated information.
  572. Since this is usually not what you want, Django provides a convenience wrapper
  573. to check permissions and mark the view as non-cacheable. This wrapper is
  574. :meth:`AdminSite.admin_view` (i.e. ``self.admin_site.admin_view`` inside a
  575. ``ModelAdmin`` instance); use it like so::
  576. class MyModelAdmin(admin.ModelAdmin):
  577. def get_urls(self):
  578. urls = super(MyModelAdmin, self).get_urls()
  579. my_urls = patterns('',
  580. (r'^my_view/$', self.admin_site.admin_view(self.my_view))
  581. )
  582. return my_urls + urls
  583. Notice the wrapped view in the fifth line above::
  584. (r'^my_view/$', self.admin_site.admin_view(self.my_view))
  585. This wrapping will protect ``self.my_view`` from unauthorized access and will
  586. apply the ``django.views.decorators.cache.never_cache`` decorator to make sure
  587. it is not cached if the cache middleware is active.
  588. If the page is cacheable, but you still want the permission check to be performed,
  589. you can pass a ``cacheable=True`` argument to :meth:`AdminSite.admin_view`::
  590. (r'^my_view/$', self.admin_site.admin_view(self.my_view, cacheable=True))
  591. .. method:: ModelAdmin.formfield_for_foreignkey(self, db_field, request, **kwargs)
  592. .. versionadded:: 1.1
  593. The ``formfield_for_foreignkey`` method on a ``ModelAdmin`` allows you to
  594. override the default formfield for a foreign key field. For example, to
  595. return a subset of objects for this foreign key field based on the user::
  596. class MyModelAdmin(admin.ModelAdmin):
  597. def formfield_for_foreignkey(self, db_field, request, **kwargs):
  598. if db_field.name == "car":
  599. kwargs["queryset"] = Car.objects.filter(owner=request.user)
  600. return super(MyModelAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
  601. This uses the ``HttpRequest`` instance to filter the ``Car`` foreign key field
  602. to only display the cars owned by the ``User`` instance.
  603. .. method:: ModelAdmin.formfield_for_manytomany(self, db_field, request, **kwargs)
  604. .. versionadded:: 1.1
  605. Like the ``formfield_for_foreignkey`` method, the ``formfield_for_manytomany``
  606. method can be overridden to change the default formfield for a many to many
  607. field. For example, if an owner can own multiple cars and cars can belong
  608. to multiple owners -- a many to many relationship -- you could filter the
  609. ``Car`` foreign key field to only display the cars owned by the ``User``::
  610. class MyModelAdmin(admin.ModelAdmin):
  611. def formfield_for_manytomany(self, db_field, request, **kwargs):
  612. if db_field.name == "cars":
  613. kwargs["queryset"] = Car.objects.filter(owner=request.user)
  614. return super(MyModelAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)
  615. .. method:: ModelAdmin.queryset(self, request)
  616. The ``queryset`` method on a ``ModelAdmin`` returns a
  617. :class:`~django.db.models.QuerySet` of all model instances that can be
  618. edited by the admin site. One use case for overriding this method is
  619. to show objects owned by the logged-in user::
  620. class MyModelAdmin(admin.ModelAdmin):
  621. def queryset(self, request):
  622. qs = super(MyModelAdmin, self).queryset(request)
  623. if request.user.is_superuser:
  624. return qs
  625. return qs.filter(author=request.user)
  626. Other methods
  627. ~~~~~~~~~~~~~
  628. .. method:: ModelAdmin.add_view(self, request, form_url='', extra_context=None)
  629. Django view for the model instance addition page. See note below.
  630. .. method:: ModelAdmin.change_view(self, request, object_id, extra_context=None)
  631. Django view for the model instance edition page. See note below.
  632. .. method:: ModelAdmin.changelist_view(self, request, extra_context=None)
  633. Django view for the model instances change list/actions page. See note below.
  634. .. method:: ModelAdmin.delete_view(self, request, object_id, extra_context=None)
  635. Django view for the model instance(s) deletion confirmation page. See note below.
  636. .. method:: ModelAdmin.history_view(self, request, object_id, extra_context=None)
  637. Django view for the page that shows the modification history for a given model
  638. instance.
  639. Unlike the hook-type ``ModelAdmin`` methods detailed in the previous section,
  640. these five methods are in reality designed to be invoked as Django views from
  641. the admin application URL dispatching handler to render the pages that deal
  642. with model instances CRUD operations. As a result, completely overriding these
  643. methods will significantly change the behavior of the admin application.
  644. One common reason for overriding these methods is to augment the context data
  645. that is provided to the template that renders the view. In the following
  646. example, the change view is overridden so that the rendered template is
  647. provided some extra mapping data that would not otherwise be available::
  648. class MyModelAdmin(admin.ModelAdmin):
  649. # A template for a very customized change view:
  650. change_form_template = 'admin/myapp/extras/openstreetmap_change_form.html'
  651. def get_osm_info(self):
  652. # ...
  653. def change_view(self, request, object_id, extra_context=None):
  654. my_context = {
  655. 'osm_data': self.get_osm_info(),
  656. }
  657. return super(MyModelAdmin, self).change_view(request, object_id,
  658. extra_context=my_context)
  659. ``ModelAdmin`` media definitions
  660. --------------------------------
  661. There are times where you would like add a bit of CSS and/or JavaScript to
  662. the add/change views. This can be accomplished by using a Media inner class
  663. on your ``ModelAdmin``::
  664. class ArticleAdmin(admin.ModelAdmin):
  665. class Media:
  666. css = {
  667. "all": ("my_styles.css",)
  668. }
  669. js = ("my_code.js",)
  670. Keep in mind that this will be prepended with ``MEDIA_URL``. The same rules
  671. apply as :doc:`regular media definitions on forms </topics/forms/media>`.
  672. Django admin Javascript makes use of the `jQuery`_ library. To avoid
  673. conflict with user scripts, Django's jQuery is namespaced as
  674. ``django.jQuery``. If you want to use jQuery in your own admin
  675. JavaScript without including a second copy, you can use the
  676. ``django.jQuery`` object on changelist and add/edit views.
  677. .. _jQuery: http://jquery.com
  678. Adding custom validation to the admin
  679. -------------------------------------
  680. Adding custom validation of data in the admin is quite easy. The automatic admin
  681. interface reuses :mod:`django.forms`, and the ``ModelAdmin`` class gives you
  682. the ability define your own form::
  683. class ArticleAdmin(admin.ModelAdmin):
  684. form = MyArticleAdminForm
  685. ``MyArticleAdminForm`` can be defined anywhere as long as you import where
  686. needed. Now within your form you can add your own custom validation for
  687. any field::
  688. class MyArticleAdminForm(forms.ModelForm):
  689. class Meta:
  690. model = Article
  691. def clean_name(self):
  692. # do something that validates your data
  693. return self.cleaned_data["name"]
  694. It is important you use a ``ModelForm`` here otherwise things can break. See the
  695. :doc:`forms </ref/forms/index>` documentation on :doc:`custom validation
  696. </ref/forms/validation>` and, more specifically, the
  697. :ref:`model form validation notes <overriding-modelform-clean-method>` for more
  698. information.
  699. .. _admin-inlines:
  700. ``InlineModelAdmin`` objects
  701. ============================
  702. .. class:: InlineModelAdmin
  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>`.