admin.txt 32 KB

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