PageRenderTime 56ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/docs/ref/contrib/admin/index.txt

https://code.google.com/p/mango-py/
Plain Text | 1744 lines | 1239 code | 505 blank | 0 comment | 0 complexity | 5d7cde0b64cd21f805e1b80b6951bc46 MD5 | raw file
Possible License(s): BSD-3-Clause

Large files files are truncated, but you can click here to view the full file

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

Large files files are truncated, but you can click here to view the full file