index.txt 64 KB

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