index.txt 58 KB

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