admin.txt 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054
  1. .. _ref-contrib-admin:
  2. =====================
  3. The Django admin site
  4. =====================
  5. One of the most powerful parts of Django is the automatic admin interface. It
  6. reads metadata in your model to provide a powerful and production-ready
  7. interface that content producers can immediately use to start adding content to
  8. the site. In this document, we discuss how to activate, use and customize
  9. Django's admin interface.
  10. .. admonition:: Note
  11. The admin site has been refactored significantly since Django 0.96. This
  12. document describes the newest version of the admin site, which allows for
  13. much richer customization. If you follow the development of Django itself,
  14. you may have heard this described as "newforms-admin."
  15. Overview
  16. ========
  17. There are five steps in activating the Django admin site:
  18. 1. Add ``django.contrib.admin`` to your ``INSTALLED_APPS`` setting.
  19. 2. Determine which of your application's models should be editable in the
  20. admin interface.
  21. 3. For each of those models, optionally create a ``ModelAdmin`` class that
  22. encapsulates the customized admin functionality and options for that
  23. particular model.
  24. 4. Instantiate an ``AdminSite`` and tell it about each of your models and
  25. ``ModelAdmin`` classes.
  26. 5. Hook the ``AdminSite`` instance into your URLconf.
  27. ``ModelAdmin`` objects
  28. ======================
  29. The ``ModelAdmin`` class is the representation of a model in the admin
  30. interface. These are stored in a file named ``admin.py`` in your application.
  31. Let's take a look at a very simple example the ``ModelAdmin``::
  32. from django.contrib import admin
  33. from myproject.myapp.models import Author
  34. class AuthorAdmin(admin.ModelAdmin):
  35. pass
  36. admin.site.register(Author, AuthorAdmin)
  37. ``ModelAdmin`` Options
  38. ----------------------
  39. The ``ModelAdmin`` is very flexible. It has several options for dealing with
  40. customizing the interface. All options are defined on the ``ModelAdmin``
  41. subclass::
  42. class AuthorAdmin(admin.ModelAdmin):
  43. date_hierarchy = 'pub_date'
  44. ``date_hierarchy``
  45. ~~~~~~~~~~~~~~~~~~
  46. Set ``date_hierarchy`` to the name of a ``DateField`` or ``DateTimeField`` in
  47. your model, and the change list page will include a date-based drilldown
  48. navigation by that field.
  49. Example::
  50. date_hierarchy = 'pub_date'
  51. ``form``
  52. ~~~~~~~~
  53. By default a ``ModelForm`` is dynamically created for your model. It is used
  54. to create the form presented on both the add/change pages. You can easily
  55. provide your own ``ModelForm`` to override any default form behavior on the
  56. add/change pages.
  57. For an example see the section `Adding custom validation to the admin`_.
  58. ``fieldsets``
  59. ~~~~~~~~~~~~~
  60. Set ``fieldsets`` to control the layout of admin "add" and "change" pages.
  61. ``fieldsets`` is a list of two-tuples, in which each two-tuple represents a
  62. ``<fieldset>`` on the admin form page. (A ``<fieldset>`` is a "section" of the
  63. form.)
  64. The two-tuples are in the format ``(name, field_options)``, where ``name`` is a
  65. string representing the title of the fieldset and ``field_options`` is a
  66. dictionary of information about the fieldset, including a list of fields to be
  67. displayed in it.
  68. A full example, taken from the ``django.contrib.flatpages.FlatPage`` model::
  69. class FlatPageAdmin(admin.ModelAdmin):
  70. fieldsets = (
  71. (None, {
  72. 'fields': ('url', 'title', 'content', 'sites')
  73. }),
  74. ('Advanced options', {
  75. 'classes': ('collapse',),
  76. 'fields': ('enable_comments', 'registration_required', 'template_name')
  77. }),
  78. )
  79. This results in an admin page that looks like:
  80. .. image:: _images/flatfiles_admin.png
  81. If ``fieldsets`` isn't given, Django will default to displaying each field
  82. that isn't an ``AutoField`` and has ``editable=True``, in a single fieldset,
  83. in the same order as the fields are defined in the model.
  84. The ``field_options`` dictionary can have the following keys:
  85. * ``fields``
  86. A tuple of field names to display in this fieldset. This key is
  87. required.
  88. Example::
  89. {
  90. 'fields': ('first_name', 'last_name', 'address', 'city', 'state'),
  91. }
  92. To display multiple fields on the same line, wrap those fields in
  93. their own tuple. In this example, the ``first_name`` and ``last_name``
  94. fields will display on the same line::
  95. {
  96. 'fields': (('first_name', 'last_name'), 'address', 'city', 'state'),
  97. }
  98. * ``classes``
  99. A list containing extra CSS classes to apply to the fieldset.
  100. Example::
  101. {
  102. 'classes': ['wide', 'extrapretty'],
  103. }
  104. Two useful classes defined by the default admin-site stylesheet are
  105. ``collapse`` and ``wide``. Fieldsets with the ``collapse`` style will
  106. be initially collapsed in the admin and replaced with a small
  107. "click to expand" link. Fieldsets with the ``wide`` style will be
  108. given extra horizontal space.
  109. * ``description``
  110. A string of optional extra text to be displayed at the top of each
  111. fieldset, under the heading of the fieldset.
  112. Note that this value is *not* HTML-escaped when it's displayed in
  113. the admin interface. This lets you include HTML if you so desire.
  114. Alternatively you can use plain text and
  115. ``django.utils.html.escape()`` to escape any HTML special
  116. characters.
  117. ``fields``
  118. ~~~~~~~~~~
  119. Use this option as an alternative to ``fieldsets`` if the layout does not
  120. matter and if you want to only show a subset of the available fields in the
  121. form. For example, you could define a simpler version of the admin form for
  122. the ``django.contrib.flatpages.FlatPage`` model as follows::
  123. class FlatPageAdmin(admin.ModelAdmin):
  124. fields = ('url', 'title', 'content')
  125. In the above example, only the fields 'url', 'title' and 'content' will be
  126. displayed, sequentially, in the form.
  127. .. admonition:: Note
  128. This ``fields`` option should not be confused with the ``fields``
  129. dictionary key that is within the ``fieldsets`` option, as described in
  130. the previous section.
  131. ``exclude``
  132. ~~~~~~~~~~~
  133. This attribute, if given, should be a list of field names to exclude from the
  134. form.
  135. For example, let's consider the following model::
  136. class Author(models.Model):
  137. name = models.CharField(max_length=100)
  138. title = models.CharField(max_length=3)
  139. birth_date = models.DateField(blank=True, null=True)
  140. If you want a form for the ``Author`` model that includes only the ``name``
  141. and ``title`` fields, you would specify ``fields`` or ``exclude`` like this::
  142. class AuthorAdmin(admin.ModelAdmin):
  143. fields = ('name', 'title')
  144. class AuthorAdmin(admin.ModelAdmin):
  145. exclude = ('birth_date',)
  146. Since the Author model only has three fields, ``name``, ``title``, and
  147. ``birth_date``, the forms resulting from the above declarations will contain
  148. exactly the same fields.
  149. ``filter_horizontal``
  150. ~~~~~~~~~~~~~~~~~~~~~
  151. Use a nifty unobtrusive JavaScript "filter" interface instead of the
  152. usability-challenged ``<select multiple>`` in the admin form. The value is a
  153. list of fields that should be displayed as a horizontal filter interface. See
  154. ``filter_vertical`` to use a vertical interface.
  155. ``filter_vertical``
  156. ~~~~~~~~~~~~~~~~~~~
  157. Same as ``filter_horizontal``, but is a vertical display of the filter
  158. interface.
  159. ``list_display``
  160. ~~~~~~~~~~~~~~~~
  161. Set ``list_display`` to control which fields are displayed on the change list
  162. page of the admin.
  163. Example::
  164. list_display = ('first_name', 'last_name')
  165. If you don't set ``list_display``, the admin site will display a single column
  166. that displays the ``__unicode__()`` representation of each object.
  167. You have four possible values that can be used in ``list_display``:
  168. * A field of the model. For example::
  169. class PersonAdmin(admin.ModelAdmin):
  170. list_display = ('first_name', 'last_name')
  171. * A callable that accepts one parameter for the model instance. For
  172. example::
  173. def upper_case_name(obj):
  174. return "%s %s" % (obj.first_name, obj.last_name).upper()
  175. upper_case_name.short_description = 'Name'
  176. class PersonAdmin(admin.ModelAdmin):
  177. list_display = (upper_case_name,)
  178. * A string representing an attribute on the ``ModelAdmin``. This behaves
  179. same as the callable. For example::
  180. class PersonAdmin(admin.ModelAdmin):
  181. list_display = ('upper_case_name',)
  182. def upper_case_name(self, obj):
  183. return "%s %s" % (obj.first_name, obj.last_name).upper()
  184. upper_case_name.short_description = 'Name'
  185. * A string representing an attribute on the model. This behaves almost
  186. the same as the callable, but ``self`` in this context is the model
  187. instance. Here's a full model example::
  188. class Person(models.Model):
  189. name = models.CharField(max_length=50)
  190. birthday = models.DateField()
  191. def decade_born_in(self):
  192. return self.birthday.strftime('%Y')[:3] + "0's"
  193. decade_born_in.short_description = 'Birth decade'
  194. class PersonAdmin(admin.ModelAdmin):
  195. list_display = ('name', 'decade_born_in')
  196. A few special cases to note about ``list_display``:
  197. * If the field is a ``ForeignKey``, Django will display the
  198. ``__unicode__()`` of the related object.
  199. * ``ManyToManyField`` fields aren't supported, because that would entail
  200. executing a separate SQL statement for each row in the table. If you
  201. want to do this nonetheless, give your model a custom method, and add
  202. that method's name to ``list_display``. (See below for more on custom
  203. methods in ``list_display``.)
  204. * If the field is a ``BooleanField`` or ``NullBooleanField``, Django will
  205. display a pretty "on" or "off" icon instead of ``True`` or ``False``.
  206. * If the string given is a method of the model, ``ModelAdmin`` or a
  207. callable, Django will HTML-escape the output by default. If you'd rather
  208. not escape the output of the method, give the method an ``allow_tags``
  209. attribute whose value is ``True``.
  210. Here's a full example model::
  211. class Person(models.Model):
  212. first_name = models.CharField(max_length=50)
  213. last_name = models.CharField(max_length=50)
  214. color_code = models.CharField(max_length=6)
  215. def colored_name(self):
  216. return '<span style="color: #%s;">%s %s</span>' % (self.color_code, self.first_name, self.last_name)
  217. colored_name.allow_tags = True
  218. class PersonAdmin(admin.ModelAdmin):
  219. list_display = ('first_name', 'last_name', 'colored_name')
  220. * If the string given is a method of the model, ``ModelAdmin`` or a
  221. callable that returns True or False Django will display a pretty "on" or
  222. "off" icon if you give the method a ``boolean`` attribute whose value is
  223. ``True``.
  224. Here's a full example model::
  225. class Person(models.Model):
  226. first_name = models.CharField(max_length=50)
  227. birthday = models.DateField()
  228. def born_in_fifties(self):
  229. return self.birthday.strftime('%Y')[:3] == 5
  230. born_in_fifties.boolean = True
  231. class PersonAdmin(admin.ModelAdmin):
  232. list_display = ('name', 'born_in_fifties')
  233. * The ``__str__()`` and ``__unicode__()`` methods are just as valid in
  234. ``list_display`` as any other model method, so it's perfectly OK to do
  235. this::
  236. list_display = ('__unicode__', 'some_other_field')
  237. * Usually, elements of ``list_display`` that aren't actual database fields
  238. can't be used in sorting (because Django does all the sorting at the
  239. database level).
  240. However, if an element of ``list_display`` represents a certain database
  241. field, you can indicate this fact by setting the ``admin_order_field``
  242. attribute of the item.
  243. For example::
  244. class Person(models.Model):
  245. first_name = models.CharField(max_length=50)
  246. color_code = models.CharField(max_length=6)
  247. def colored_first_name(self):
  248. return '<span style="color: #%s;">%s</span>' % (self.color_code, self.first_name)
  249. colored_first_name.allow_tags = True
  250. colored_first_name.admin_order_field = 'first_name'
  251. class PersonAdmin(admin.ModelAdmin):
  252. list_display = ('first_name', 'colored_first_name')
  253. The above will tell Django to order by the ``first_name`` field when
  254. trying to sort by ``colored_first_name`` in the admin.
  255. ``list_display_links``
  256. ~~~~~~~~~~~~~~~~~~~~~~
  257. Set ``list_display_links`` to control which fields in ``list_display`` should
  258. be linked to the "change" page for an object.
  259. By default, the change list page will link the first column -- the first field
  260. specified in ``list_display`` -- to the change page for each item. But
  261. ``list_display_links`` lets you change which columns are linked. Set
  262. ``list_display_links`` to a list or tuple of field names (in the same format as
  263. ``list_display``) to link.
  264. ``list_display_links`` can specify one or many field names. As long as the
  265. field names appear in ``list_display``, Django doesn't care how many (or how
  266. few) fields are linked. The only requirement is: If you want to use
  267. ``list_display_links``, you must define ``list_display``.
  268. In this example, the ``first_name`` and ``last_name`` fields will be linked on
  269. the change list page::
  270. class PersonAdmin(admin.ModelAdmin):
  271. list_display = ('first_name', 'last_name', 'birthday')
  272. list_display_links = ('first_name', 'last_name')
  273. Finally, note that in order to use ``list_display_links``, you must define
  274. ``list_display``, too.
  275. ``list_filter``
  276. ~~~~~~~~~~~~~~~
  277. Set ``list_filter`` to activate filters in the right sidebar of the change list
  278. page of the admin. This should be a list of field names, and each specified
  279. field should be either a ``BooleanField``, ``CharField``, ``DateField``,
  280. ``DateTimeField``, ``IntegerField`` or ``ForeignKey``.
  281. This example, taken from the ``django.contrib.auth.models.User`` model, shows
  282. how both ``list_display`` and ``list_filter`` work::
  283. class UserAdmin(admin.ModelAdmin):
  284. list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff')
  285. list_filter = ('is_staff', 'is_superuser')
  286. The above code results in an admin change list page that looks like this:
  287. .. image:: _images/users_changelist.png
  288. (This example also has ``search_fields`` defined. See below.)
  289. ``list_per_page``
  290. ~~~~~~~~~~~~~~~~~
  291. Set ``list_per_page`` to control how many items appear on each paginated admin
  292. change list page. By default, this is set to ``100``.
  293. ``list_select_related``
  294. ~~~~~~~~~~~~~~~~~~~~~~~
  295. Set ``list_select_related`` to tell Django to use ``select_related()`` in
  296. retrieving the list of objects on the admin change list page. This can save you
  297. a bunch of database queries.
  298. The value should be either ``True`` or ``False``. Default is ``False``.
  299. Note that Django will use ``select_related()``, regardless of this setting,
  300. if one of the ``list_display`` fields is a ``ForeignKey``.
  301. For more on ``select_related()``, see
  302. :ref:`the select_related() docs <select-related>`.
  303. ``inlines``
  304. ~~~~~~~~~~~
  305. See ``InlineModelAdmin`` objects below.
  306. ``ordering``
  307. ~~~~~~~~~~~~
  308. Set ``ordering`` to specify how objects on the admin change list page should be
  309. ordered. This should be a list or tuple in the same format as a model's
  310. ``ordering`` parameter.
  311. If this isn't provided, the Django admin will use the model's default ordering.
  312. .. admonition:: Note
  313. Django will only honor the first element in the list/tuple; any others
  314. will be ignored.
  315. ``prepopulated_fields``
  316. ~~~~~~~~~~~~~~~~~~~~~~~
  317. Set ``prepopulated_fields`` to a dictionary mapping field names to the fields
  318. it should prepopulate from::
  319. class ArticleAdmin(admin.ModelAdmin):
  320. prepopulated_fields = {"slug": ("title",)}
  321. When set, the given fields will use a bit of JavaScript to populate from the
  322. fields assigned. The main use for this functionality is to automatically
  323. generate the value for ``SlugField`` fields from one or more other fields. The
  324. generated value is produced by concatenating the values of the source fields,
  325. and then by transforming that result into a valid slug (e.g. substituting
  326. dashes for spaces).
  327. ``prepopulated_fields`` doesn't accept ``DateTimeField``, ``ForeignKey``, nor
  328. ``ManyToManyField`` fields.
  329. ``radio_fields``
  330. ~~~~~~~~~~~~~~~~
  331. By default, Django's admin uses a select-box interface (<select>) for
  332. fields that are ``ForeignKey`` or have ``choices`` set. If a field is present
  333. in ``radio_fields``, Django will use a radio-button interface instead.
  334. Assuming ``group`` is a ``ForeignKey`` on the ``Person`` model::
  335. class PersonAdmin(admin.ModelAdmin):
  336. radio_fields = {"group": admin.VERTICAL}
  337. You have the choice of using ``HORIZONTAL`` or ``VERTICAL`` from the
  338. ``django.contrib.admin`` module.
  339. Don't include a field in ``radio_fields`` unless it's a ``ForeignKey`` or has
  340. ``choices`` set.
  341. ``raw_id_fields``
  342. ~~~~~~~~~~~~~~~~~
  343. By default, Django's admin uses a select-box interface (<select>) for
  344. fields that are ``ForeignKey``. Sometimes you don't want to incur the
  345. overhead of having to select all the related instances to display in the
  346. drop-down.
  347. ``raw_id_fields`` is a list of fields you would like to change
  348. into a ``Input`` widget for either a ``ForeignKey`` or ``ManyToManyField``::
  349. class ArticleAdmin(admin.ModelAdmin):
  350. raw_id_fields = ("newspaper",)
  351. ``save_as``
  352. ~~~~~~~~~~~
  353. Set ``save_as`` to enable a "save as" feature on admin change forms.
  354. Normally, objects have three save options: "Save", "Save and continue editing"
  355. and "Save and add another". If ``save_as`` is ``True``, "Save and add another"
  356. will be replaced by a "Save as" button.
  357. "Save as" means the object will be saved as a new object (with a new ID),
  358. rather than the old object.
  359. By default, ``save_as`` is set to ``False``.
  360. ``save_on_top``
  361. ~~~~~~~~~~~~~~~
  362. Set ``save_on_top`` to add save buttons across the top of your admin change
  363. forms.
  364. Normally, the save buttons appear only at the bottom of the forms. If you set
  365. ``save_on_top``, the buttons will appear both on the top and the bottom.
  366. By default, ``save_on_top`` is set to ``False``.
  367. ``search_fields``
  368. ~~~~~~~~~~~~~~~~~
  369. Set ``search_fields`` to enable a search box on the admin change list page.
  370. This should be set to a list of field names that will be searched whenever
  371. somebody submits a search query in that text box.
  372. These fields should be some kind of text field, such as ``CharField`` or
  373. ``TextField``. You can also perform a related lookup on a ``ForeignKey`` with
  374. the lookup API "follow" notation::
  375. search_fields = ['foreign_key__related_fieldname']
  376. When somebody does a search in the admin search box, Django splits the search
  377. query into words and returns all objects that contain each of the words, case
  378. insensitive, where each word must be in at least one of ``search_fields``. For
  379. example, if ``search_fields`` is set to ``['first_name', 'last_name']`` and a
  380. user searches for ``john lennon``, Django will do the equivalent of this SQL
  381. ``WHERE`` clause::
  382. WHERE (first_name ILIKE '%john%' OR last_name ILIKE '%john%')
  383. AND (first_name ILIKE '%lennon%' OR last_name ILIKE '%lennon%')
  384. For faster and/or more restrictive searches, prefix the field name
  385. with an operator:
  386. ``^``
  387. Matches the beginning of the field. For example, if ``search_fields`` is
  388. set to ``['^first_name', '^last_name']`` and a user searches for
  389. ``john lennon``, Django will do the equivalent of this SQL ``WHERE``
  390. clause::
  391. WHERE (first_name ILIKE 'john%' OR last_name ILIKE 'john%')
  392. AND (first_name ILIKE 'lennon%' OR last_name ILIKE 'lennon%')
  393. This query is more efficient than the normal ``'%john%'`` query, because
  394. the database only needs to check the beginning of a column's data, rather
  395. than seeking through the entire column's data. Plus, if the column has an
  396. index on it, some databases may be able to use the index for this query,
  397. even though it's a ``LIKE`` query.
  398. ``=``
  399. Matches exactly, case-insensitive. For example, if
  400. ``search_fields`` is set to ``['=first_name', '=last_name']`` and
  401. a user searches for ``john lennon``, Django will do the equivalent
  402. of this SQL ``WHERE`` clause::
  403. WHERE (first_name ILIKE 'john' OR last_name ILIKE 'john')
  404. AND (first_name ILIKE 'lennon' OR last_name ILIKE 'lennon')
  405. Note that the query input is split by spaces, so, following this example,
  406. it's currently not possible to search for all records in which
  407. ``first_name`` is exactly ``'john winston'`` (containing a space).
  408. ``@``
  409. Performs a full-text match. This is like the default search method but uses
  410. an index. Currently this is only available for MySQL.
  411. ``ModelAdmin`` methods
  412. ----------------------
  413. ``save_model(self, request, obj, form, change)``
  414. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  415. The ``save_model`` method is given the ``HttpRequest``, a model instance,
  416. a ``ModelForm`` instance and a boolean value based on whether it is adding or
  417. changing the object. Here you can do any pre- or post-save operations.
  418. For example to attach ``request.user`` to the object prior to saving::
  419. class ArticleAdmin(admin.ModelAdmin):
  420. def save_model(self, request, obj, form, change):
  421. obj.user = request.user
  422. obj.save()
  423. ``save_formset(self, request, form, formset, change)``
  424. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  425. The ``save_formset`` method is given the ``HttpRequest``, the parent
  426. ``ModelForm`` instance and a boolean value based on whether it is adding or
  427. changing the parent object.
  428. For example to attach ``request.user`` to each changed formset
  429. model instance::
  430. class ArticleAdmin(admin.ModelAdmin):
  431. def save_formset(self, request, form, formset, change):
  432. instances = formset.save(commit=False)
  433. for instance in instances:
  434. instance.user = request.user
  435. instance.save()
  436. formset.save_m2m()
  437. ``ModelAdmin`` media definitions
  438. --------------------------------
  439. There are times where you would like add a bit of CSS and/or JavaScript to
  440. the add/change views. This can be accomplished by using a Media inner class
  441. on your ``ModelAdmin``::
  442. class ArticleAdmin(admin.ModelAdmin):
  443. class Media:
  444. css = {
  445. "all": ("my_styles.css",)
  446. }
  447. js = ("my_code.js",)
  448. Keep in mind that this will be prepended with ``MEDIA_URL``. The same rules
  449. apply as :ref:`regular media definitions on forms <topics-forms-media>`.
  450. Adding custom validation to the admin
  451. -------------------------------------
  452. Adding custom validation of data in the admin is quite easy. The automatic admin
  453. interfaces reuses :mod:`django.forms`, and the ``ModelAdmin`` class gives you
  454. the ability define your own form::
  455. class ArticleAdmin(admin.ModelAdmin):
  456. form = MyArticleAdminForm
  457. ``MyArticleAdminForm`` can be defined anywhere as long as you import where
  458. needed. Now within your form you can add your own custom validation for
  459. any field::
  460. class MyArticleAdminForm(forms.ModelForm):
  461. class Meta:
  462. model = Article
  463. def clean_name(self):
  464. # do something that validates your data
  465. return self.cleaned_data["name"]
  466. It is important you use a ``ModelForm`` here otherwise things can break. See the
  467. :ref:`forms <ref-forms-index>` documentation on :ref:`custom validation
  468. <ref-forms-validation>` for more information.
  469. .. _admin-inlines:
  470. ``InlineModelAdmin`` objects
  471. ============================
  472. The admin interface has the ability to edit models on the same page as a
  473. parent model. These are called inlines. You can add them to a model by
  474. specifying them in a ``ModelAdmin.inlines`` attribute::
  475. class BookInline(admin.TabularInline):
  476. model = Book
  477. class AuthorAdmin(admin.ModelAdmin):
  478. inlines = [
  479. BookInline,
  480. ]
  481. Django provides two subclasses of ``InlineModelAdmin`` and they are:
  482. * ``TabularInline``
  483. * ``StackedInline``
  484. The difference between these two is merely the template used to render them.
  485. ``InlineModelAdmin`` options
  486. -----------------------------
  487. The ``InlineModelAdmin`` class is a subclass of ``ModelAdmin`` so it inherits
  488. all the same functionality as well as some of its own:
  489. ``model``
  490. ~~~~~~~~~
  491. The model in which the inline is using. This is required.
  492. ``fk_name``
  493. ~~~~~~~~~~~
  494. The name of the foreign key on the model. In most cases this will be dealt
  495. with automatically, but ``fk_name`` must be specified explicitly if there are
  496. more than one foreign key to the same parent model.
  497. ``formset``
  498. ~~~~~~~~~~~
  499. This defaults to ``BaseInlineFormSet``. Using your own formset can give you
  500. many possibilities of customization. Inlines are built around
  501. :ref:`model formsets <model-formsets>`.
  502. ``form``
  503. ~~~~~~~~
  504. The value for ``form`` is inherited from ``ModelAdmin``. This is what is
  505. passed through to ``formset_factory`` when creating the formset for this
  506. inline.
  507. ``extra``
  508. ~~~~~~~~~
  509. This controls the number of extra forms the formset will display in addition
  510. to the initial forms. See the
  511. :ref:`formsets documentation <topics-forms-formsets>` for more information.
  512. ``max_num``
  513. ~~~~~~~~~~~
  514. This controls the maximum number of forms to show in the inline. This doesn't
  515. directly correlate to the number of objects, but can if the value is small
  516. enough. See :ref:`model-formsets-max-num` for more information.
  517. ``raw_id_fields``
  518. ~~~~~~~~~~~~~~~~~
  519. By default, Django's admin uses a select-box interface (<select>) for
  520. fields that are ``ForeignKey``. Sometimes you don't want to incur the
  521. overhead of having to select all the related instances to display in the
  522. drop-down.
  523. ``raw_id_fields`` is a list of fields you would like to change
  524. into a ``Input`` widget for either a ``ForeignKey`` or ``ManyToManyField``::
  525. class BookInline(admin.TabularInline):
  526. model = Book
  527. raw_id_fields = ("pages",)
  528. ``template``
  529. ~~~~~~~~~~~~
  530. The template used to render the inline on the page.
  531. ``verbose_name``
  532. ~~~~~~~~~~~~~~~~
  533. An override to the ``verbose_name`` found in the model's inner ``Meta`` class.
  534. ``verbose_name_plural``
  535. ~~~~~~~~~~~~~~~~~~~~~~~
  536. An override to the ``verbose_name_plural`` found in the model's inner ``Meta``
  537. class.
  538. Working with a model with two or more foreign keys to the same parent model
  539. ---------------------------------------------------------------------------
  540. It is sometimes possible to have more than one foreign key to the same model.
  541. Take this model for instance::
  542. class Friendship(models.Model):
  543. to_person = models.ForeignKey(Person, related_name="friends")
  544. from_person = models.ForeignKey(Person, related_name="from_friends")
  545. If you wanted to display an inline on the ``Person`` admin add/change pages
  546. you need to explicitly define the foreign key since it is unable to do so
  547. automatically::
  548. class FriendshipInline(admin.TabularInline):
  549. model = Friendship
  550. fk_name = "to_person"
  551. class PersonAdmin(admin.ModelAdmin):
  552. inlines = [
  553. FriendshipInline,
  554. ]
  555. Working with Many-to-Many Intermediary Models
  556. ----------------------------------------------
  557. By default, admin widgets for many-to-many relations will be displayed inline
  558. on whichever model contains the actual reference to the ``ManyToManyField``.
  559. However, when you specify an intermediary model using the ``through``
  560. argument to a ``ManyToManyField``, the admin will not display a widget by
  561. default. This is because each instance of that intermediary model requires
  562. more information than could be displayed in a single widget, and the layout
  563. required for multiple widgets will vary depending on the intermediate model.
  564. However, we still want to be able to edit that information inline. Fortunately,
  565. this is easy to do with inline admin models. Suppose we have the following
  566. models::
  567. class Person(models.Model):
  568. name = models.CharField(max_length=128)
  569. class Group(models.Model):
  570. name = models.CharField(max_length=128)
  571. members = models.ManyToManyField(Person, through='Membership')
  572. class Membership(models.Model):
  573. person = models.ForeignKey(Person)
  574. group = models.ForeignKey(Group)
  575. date_joined = models.DateField()
  576. invite_reason = models.CharField(max_length=64)
  577. The first step in displaying this intermediate model in the admin is to
  578. define an inline class for the ``Membership`` model::
  579. class MembershipInline(admin.TabularInline):
  580. model = Membership
  581. extra = 1
  582. This simple example uses the default ``InlineModelAdmin`` values for the
  583. ``Membership`` model, and limits the extra add forms to one. This could be
  584. customized using any of the options available to ``InlineModelAdmin`` classes.
  585. Now create admin views for the ``Person`` and ``Group`` models::
  586. class PersonAdmin(admin.ModelAdmin):
  587. inlines = (MembershipInline,)
  588. class GroupAdmin(admin.ModelAdmin):
  589. inlines = (MembershipInline,)
  590. Finally, register your ``Person`` and ``Group`` models with the admin site::
  591. admin.site.register(Person, PersonAdmin)
  592. admin.site.register(Group, GroupAdmin)
  593. Now your admin site is set up to edit ``Membership`` objects inline from
  594. either the ``Person`` or the ``Group`` detail pages.
  595. Using generic relations as an inline
  596. ------------------------------------
  597. It is possible to use an inline with generically related objects. Let's say
  598. you have the following models::
  599. class Image(models.Model):
  600. image = models.ImageField(upload_to="images")
  601. content_type = models.ForeignKey(ContentType)
  602. object_id = models.PositiveIntegerField()
  603. content_object = generic.GenericForeignKey("content_type", "object_id")
  604. class Product(models.Model):
  605. name = models.CharField(max_length=100)
  606. If you want to allow editing and creating ``Image`` instance on the ``Product``
  607. add/change views you can simply use ``GenericInlineModelAdmin`` provided by
  608. ``django.contrib.contenttypes.generic``. In your ``admin.py`` for this
  609. example app::
  610. from django.contrib import admin
  611. from django.contrib.contenttypes import generic
  612. from myproject.myapp.models import Image, Product
  613. class ImageInline(generic.GenericTabularInline):
  614. model = Image
  615. class ProductAdmin(admin.ModelAdmin):
  616. inlines = [
  617. ImageInline,
  618. ]
  619. admin.site.register(Product, ProductAdmin)
  620. ``django.contrib.contenttypes.generic`` provides both a ``GenericTabularInline``
  621. and ``GenericStackedInline`` and behave just like any other inline. See the
  622. :ref:`contenttypes documentation <ref-contrib-contenttypes>` for more specific
  623. information.
  624. Overriding Admin Templates
  625. ==========================
  626. It is relatively easy to override many of the templates which the admin module
  627. uses to generate the various pages of an admin site. You can even override a few
  628. of these templates for a specific app, or a specific model.
  629. Set up your projects admin template directories
  630. -----------------------------------------------
  631. The admin template files are located in the ``contrib/admin/templates/admin``
  632. directory.
  633. In order to override one or more of them, first create an ``admin`` directory in
  634. your project's ``templates`` directory. This can be any of the directories you
  635. specified in ``TEMPLATE_DIRS``.
  636. Within this ``admin`` directory, create sub-directories named after your app.
  637. Within these app subdirectories create sub-directories named after your models.
  638. Note, that the admin app will lowercase the model name when looking for the
  639. directory, so make sure you name the directory in all lowercase if you are going
  640. to run your app on a case-sensitive filesystem.
  641. To override an admin template for a specific app, copy and edit the template
  642. from the ``django/contrib/admin/templates/admin`` directory, and save it to one
  643. of the directories you just created.
  644. For example, if we wanted to add a tool to the change list view for all the
  645. models in an app named ``my_app``, we would copy
  646. ``contrib/admin/templates/admin/change_list.html`` to the
  647. ``templates/admin/my_app/`` directory of our project, and make any necessary
  648. changes.
  649. If we wanted to add a tool to the change list view for only a specific model
  650. named 'Page', we would copy that same file to the
  651. ``templates/admin/my_app/page`` directory of our project.
  652. Overriding vs. replacing an admin template
  653. ------------------------------------------
  654. Because of the modular design of the admin templates, it is usually neither
  655. necessary nor advisable to replace an entire template. It is almost always
  656. better to override only the section of the template which you need to change.
  657. To continue the example above, we want to add a new link next to the ``History``
  658. tool for the ``Page`` model. After looking at ``change_form.html`` we determine
  659. that we only need to override the ``object-tools`` block. Therefore here is our
  660. new ``change_form.html`` ::
  661. {% extends "admin/change_form.html" %}
  662. {% load i18n %}
  663. {% block object-tools %}
  664. {% if change %}{% if not is_popup %}
  665. <ul class="object-tools">
  666. <li><a href="history/" class="historylink">{% trans "History" %}</a></li>
  667. <li><a href="mylink/" class="historylink">My Link</a></li>
  668. {% if has_absolute_url %}
  669. <li><a href="../../../r/{{ content_type_id }}/{{ object_id }}/" class="viewsitelink">
  670. {% trans "View on site" %}</a>
  671. </li>
  672. {% endif%}
  673. </ul>
  674. {% endif %}{% endif %}
  675. {% endblock %}
  676. And that's it! If we placed this file in the ``templates/admin/my_app``
  677. directory, our link would appear on every model's change form.
  678. Templates which may be overridden per app or model
  679. --------------------------------------------------
  680. Not every template in ``contrib\admin\templates\admin`` may be overridden per
  681. app or per model. The following can:
  682. * ``change_form.html``
  683. * ``change_list.html``
  684. * ``delete_confirmation.html``
  685. * ``object_history.html``
  686. For those templates that cannot be overridden in this way, you may still
  687. override them for your entire project. Just place the new version in your
  688. ``templates/admin`` directory. This is particularly useful to create custom 404
  689. and 500 pages.
  690. .. note::
  691. Some of the admin templates, such as ``change_list_request.html`` are used
  692. to render custom inclusion tags. These may be overridden, but in such cases
  693. you are probably better off creating your own version of the tag in question
  694. and giving it a different name. That way you can use it selectively.
  695. Root and login templates
  696. ------------------------
  697. If you wish to change the index or login templates, you are better off creating
  698. your own ``AdminSite`` instance (see below), and changing the ``index_template``
  699. or ``login_template`` properties.
  700. ``AdminSite`` objects
  701. =====================
  702. A Django administrative site is represented by an instance of
  703. ``django.contrib.admin.sites.AdminSite``; by default, an instance of
  704. this class is created as ``django.contrib.admin.site`` and you can
  705. register your models and ``ModelAdmin`` instances with it.
  706. If you'd like to set up your own administrative site with custom
  707. behavior, however, you're free to subclass ``AdminSite`` and override
  708. or add anything you like. Then, simply create an instance of your
  709. ``AdminSite`` subclass (the same way you'd instantiate any other
  710. Python class), and register your models and ``ModelAdmin`` subclasses
  711. with it instead of using the default.
  712. Hooking ``AdminSite`` instances into your URLconf
  713. -------------------------------------------------
  714. The last step in setting up the Django admin is to hook your ``AdminSite``
  715. instance into your URLconf. Do this by pointing a given URL at the
  716. ``AdminSite.root`` method.
  717. In this example, we register the default ``AdminSite`` instance
  718. ``django.contrib.admin.site`` at the URL ``/admin/`` ::
  719. # urls.py
  720. from django.conf.urls.defaults import *
  721. from django.contrib import admin
  722. admin.autodiscover()
  723. urlpatterns = patterns('',
  724. ('^admin/(.*)', admin.site.root),
  725. )
  726. Above we used ``admin.autodiscover()`` to automatically load the
  727. ``INSTALLED_APPS`` admin.py modules.
  728. In this example, we register the ``AdminSite`` instance
  729. ``myproject.admin.admin_site`` at the URL ``/myadmin/`` ::
  730. # urls.py
  731. from django.conf.urls.defaults import *
  732. from myproject.admin import admin_site
  733. urlpatterns = patterns('',
  734. ('^myadmin/(.*)', admin_site.root),
  735. )
  736. There is really no need to use autodiscover when using your own ``AdminSite``
  737. instance since you will likely be importing all the per-app admin.py modules
  738. in your ``myproject.admin`` module.
  739. Note that the regular expression in the URLpattern *must* group everything in
  740. the URL that comes after the URL root -- hence the ``(.*)`` in these examples.
  741. Multiple admin sites in the same URLconf
  742. ----------------------------------------
  743. It's easy to create multiple instances of the admin site on the same
  744. Django-powered Web site. Just create multiple instances of ``AdminSite`` and
  745. root each one at a different URL.
  746. In this example, the URLs ``/basic-admin/`` and ``/advanced-admin/`` feature
  747. separate versions of the admin site -- using the ``AdminSite`` instances
  748. ``myproject.admin.basic_site`` and ``myproject.admin.advanced_site``,
  749. respectively::
  750. # urls.py
  751. from django.conf.urls.defaults import *
  752. from myproject.admin import basic_site, advanced_site
  753. urlpatterns = patterns('',
  754. ('^basic-admin/(.*)', basic_site.root),
  755. ('^advanced-admin/(.*)', advanced_site.root),
  756. )