index.txt 84 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134
  1. =====================
  2. The Django admin site
  3. =====================
  4. .. module:: django.contrib.admin
  5. :synopsis: Django's admin site.
  6. One of the most powerful parts of Django is the automatic admin interface. It
  7. reads metadata in your model to provide a powerful and production-ready
  8. interface that content producers can immediately use to start adding content to
  9. the site. In this document, we discuss how to activate, use and customize
  10. Django's admin interface.
  11. Overview
  12. ========
  13. The admin is enabled in the default project template used by
  14. :djadmin:`startproject`.
  15. .. versionchanged:: 1.6
  16. In previous versions, the admin wasn't enabled by default.
  17. For reference, here are the requirements:
  18. 1. Add ``'django.contrib.admin'`` to your :setting:`INSTALLED_APPS`
  19. setting.
  20. 2. The admin has four dependencies - :mod:`django.contrib.auth`,
  21. :mod:`django.contrib.contenttypes`,
  22. :mod:`django.contrib.messages` and
  23. :mod:`django.contrib.sessions`. If these applications are not
  24. in your :setting:`INSTALLED_APPS` list, add them.
  25. 3. Add ``django.contrib.messages.context_processors.messages`` to
  26. :setting:`TEMPLATE_CONTEXT_PROCESSORS` as well as
  27. :class:`django.contrib.auth.middleware.AuthenticationMiddleware` and
  28. :class:`django.contrib.messages.middleware.MessageMiddleware` to
  29. :setting:`MIDDLEWARE_CLASSES`. (These are all active by default, so
  30. you only need to do this if you've manually tweaked the settings.)
  31. 4. Determine which of your application's models should be editable in the
  32. admin interface.
  33. 5. For each of those models, optionally create a ``ModelAdmin`` class that
  34. encapsulates the customized admin functionality and options for that
  35. particular model.
  36. 6. Instantiate an ``AdminSite`` and tell it about each of your models and
  37. ``ModelAdmin`` classes.
  38. 7. Hook the ``AdminSite`` instance into your URLconf.
  39. After you've taken these steps, you'll be able to use your Django admin site
  40. by visiting the URL you hooked it into (``/admin/``, by default).
  41. Other topics
  42. ------------
  43. .. toctree::
  44. :maxdepth: 1
  45. actions
  46. admindocs
  47. .. seealso::
  48. For information about serving the static files (images, JavaScript, and
  49. CSS) associated with the admin in production, see :ref:`serving-files`.
  50. Having problems? Try :doc:`/faq/admin`.
  51. ``ModelAdmin`` objects
  52. ======================
  53. .. class:: ModelAdmin
  54. The ``ModelAdmin`` class is the representation of a model in the admin
  55. interface. These are stored in a file named ``admin.py`` in your
  56. application. Let's take a look at a very simple example of
  57. the ``ModelAdmin``::
  58. from django.contrib import admin
  59. from myproject.myapp.models import Author
  60. class AuthorAdmin(admin.ModelAdmin):
  61. pass
  62. admin.site.register(Author, AuthorAdmin)
  63. .. admonition:: Do you need a ``ModelAdmin`` object at all?
  64. In the preceding example, the ``ModelAdmin`` class doesn't define any
  65. custom values (yet). As a result, the default admin interface will be
  66. provided. If you are happy with the default admin interface, you don't
  67. need to define a ``ModelAdmin`` object at all -- you can register the
  68. model class without providing a ``ModelAdmin`` description. The
  69. preceding example could be simplified to::
  70. from django.contrib import admin
  71. from myproject.myapp.models import Author
  72. admin.site.register(Author)
  73. ``ModelAdmin`` options
  74. ----------------------
  75. The ``ModelAdmin`` is very flexible. It has several options for dealing with
  76. customizing the interface. All options are defined on the ``ModelAdmin``
  77. subclass::
  78. class AuthorAdmin(admin.ModelAdmin):
  79. date_hierarchy = 'pub_date'
  80. .. attribute:: ModelAdmin.actions
  81. A list of actions to make available on the change list page. See
  82. :doc:`/ref/contrib/admin/actions` for details.
  83. .. attribute:: ModelAdmin.actions_on_top
  84. .. attribute:: ModelAdmin.actions_on_bottom
  85. Controls where on the page the actions bar appears. By default, the admin
  86. changelist displays actions at the top of the page (``actions_on_top = True;
  87. actions_on_bottom = False``).
  88. .. attribute:: ModelAdmin.actions_selection_counter
  89. Controls whether a selection counter is displayed next to the action dropdown.
  90. By default, the admin changelist will display it
  91. (``actions_selection_counter = True``).
  92. .. attribute:: ModelAdmin.date_hierarchy
  93. Set ``date_hierarchy`` to the name of a ``DateField`` or ``DateTimeField``
  94. in your model, and the change list page will include a date-based drilldown
  95. navigation by that field.
  96. Example::
  97. date_hierarchy = 'pub_date'
  98. This will intelligently populate itself based on available data,
  99. e.g. if all the dates are in one month, it'll show the day-level
  100. drill-down only.
  101. .. attribute:: ModelAdmin.exclude
  102. This attribute, if given, should be a list of field names to exclude from
  103. the form.
  104. For example, let's consider the following model::
  105. class Author(models.Model):
  106. name = models.CharField(max_length=100)
  107. title = models.CharField(max_length=3)
  108. birth_date = models.DateField(blank=True, null=True)
  109. If you want a form for the ``Author`` model that includes only the ``name``
  110. and ``title`` fields, you would specify ``fields`` or ``exclude`` like
  111. this::
  112. class AuthorAdmin(admin.ModelAdmin):
  113. fields = ('name', 'title')
  114. class AuthorAdmin(admin.ModelAdmin):
  115. exclude = ('birth_date',)
  116. Since the Author model only has three fields, ``name``, ``title``, and
  117. ``birth_date``, the forms resulting from the above declarations will
  118. contain exactly the same fields.
  119. .. attribute:: ModelAdmin.fields
  120. If you need to achieve simple changes in the layout of fields in the forms
  121. of the "add" and "change" pages like only showing a subset of the available
  122. fields, modifying their order or grouping them in rows you can use the
  123. ``fields`` option (for more complex layout needs see the
  124. :attr:`~ModelAdmin.fieldsets` option described in the next section). For
  125. example, you could define a simpler version of the admin form for the
  126. :class:`django.contrib.flatpages.models.FlatPage` model as follows::
  127. class FlatPageAdmin(admin.ModelAdmin):
  128. fields = ('url', 'title', 'content')
  129. In the above example, only the fields ``url``, ``title`` and ``content``
  130. will be displayed, sequentially, in the form. ``fields`` can contain
  131. values defined in :attr:`ModelAdmin.readonly_fields` to be displayed as
  132. read-only.
  133. To display multiple fields on the same line, wrap those fields in their own
  134. tuple. In this example, the ``url`` and ``title`` fields will display on the
  135. same line and the ``content`` field will be displayed below them in its
  136. own line::
  137. class FlatPageAdmin(admin.ModelAdmin):
  138. fields = (('url', 'title'), 'content')
  139. .. admonition:: Note
  140. This ``fields`` option should not be confused with the ``fields``
  141. dictionary key that is within the :attr:`~ModelAdmin.fieldsets` option,
  142. as described in the next section.
  143. If neither ``fields`` nor :attr:`~ModelAdmin.fieldsets` options are present,
  144. Django will default to displaying each field that isn't an ``AutoField`` and
  145. has ``editable=True``, in a single fieldset, in the same order as the fields
  146. are defined in the model.
  147. .. attribute:: ModelAdmin.fieldsets
  148. Set ``fieldsets`` to control the layout of admin "add" and "change" pages.
  149. ``fieldsets`` is a list of two-tuples, in which each two-tuple represents a
  150. ``<fieldset>`` on the admin form page. (A ``<fieldset>`` is a "section" of
  151. the form.)
  152. The two-tuples are in the format ``(name, field_options)``, where ``name``
  153. is a string representing the title of the fieldset and ``field_options`` is
  154. a dictionary of information about the fieldset, including a list of fields
  155. to be displayed in it.
  156. A full example, taken from the
  157. :class:`django.contrib.flatpages.models.FlatPage` model::
  158. class FlatPageAdmin(admin.ModelAdmin):
  159. fieldsets = (
  160. (None, {
  161. 'fields': ('url', 'title', 'content', 'sites')
  162. }),
  163. ('Advanced options', {
  164. 'classes': ('collapse',),
  165. 'fields': ('enable_comments', 'registration_required', 'template_name')
  166. }),
  167. )
  168. This results in an admin page that looks like:
  169. .. image:: _images/flatfiles_admin.png
  170. If neither ``fieldsets`` nor :attr:`~ModelAdmin.fields` options are present,
  171. Django will default to displaying each field that isn't an ``AutoField`` and
  172. has ``editable=True``, in a single fieldset, in the same order as the fields
  173. are defined in the model.
  174. The ``field_options`` dictionary can have the following keys:
  175. * ``fields``
  176. A tuple of field names to display in this fieldset. This key is
  177. required.
  178. Example::
  179. {
  180. 'fields': ('first_name', 'last_name', 'address', 'city', 'state'),
  181. }
  182. Just like with the :attr:`~ModelAdmin.fields` option, to display
  183. multiple fields on the same line, wrap those fields in their own
  184. tuple. In this example, the ``first_name`` and ``last_name`` fields
  185. will display on the same line::
  186. {
  187. 'fields': (('first_name', 'last_name'), 'address', 'city', 'state'),
  188. }
  189. ``fields`` can contain values defined in
  190. :attr:`~ModelAdmin.readonly_fields` to be displayed as read-only.
  191. * ``classes``
  192. A list containing extra CSS classes to apply to the fieldset.
  193. Example::
  194. {
  195. 'classes': ['wide', 'extrapretty'],
  196. }
  197. Two useful classes defined by the default admin site stylesheet are
  198. ``collapse`` and ``wide``. Fieldsets with the ``collapse`` style
  199. will be initially collapsed in the admin and replaced with a small
  200. "click to expand" link. Fieldsets with the ``wide`` style will be
  201. given extra horizontal space.
  202. * ``description``
  203. A string of optional extra text to be displayed at the top of each
  204. fieldset, under the heading of the fieldset.
  205. Note that this value is *not* HTML-escaped when it's displayed in
  206. the admin interface. This lets you include HTML if you so desire.
  207. Alternatively you can use plain text and
  208. ``django.utils.html.escape()`` to escape any HTML special
  209. characters.
  210. .. attribute:: ModelAdmin.filter_horizontal
  211. By default, a :class:`~django.db.models.ManyToManyField` is displayed in
  212. the admin site with a ``<select multiple>``. However, multiple-select boxes
  213. can be difficult to use when selecting many items. Adding a
  214. :class:`~django.db.models.ManyToManyField` to this list will instead use
  215. a nifty unobtrusive JavaScript "filter" interface that allows searching
  216. within the options. The unselected and selected options appear in two boxes
  217. side by side. See :attr:`~ModelAdmin.filter_vertical` to use a vertical
  218. interface.
  219. .. attribute:: ModelAdmin.filter_vertical
  220. Same as :attr:`~ModelAdmin.filter_horizontal`, but uses a vertical display
  221. of the filter interface with the box of unselected options appearing above
  222. the box of selected options.
  223. .. attribute:: ModelAdmin.form
  224. By default a ``ModelForm`` is dynamically created for your model. It is
  225. used to create the form presented on both the add/change pages. You can
  226. easily provide your own ``ModelForm`` to override any default form behavior
  227. on the add/change pages. Alternatively, you can customize the default
  228. form rather than specifying an entirely new one by using the
  229. :meth:`ModelAdmin.get_form` method.
  230. For an example see the section `Adding custom validation to the admin`_.
  231. .. admonition:: Note
  232. If your ``ModelForm`` and ``ModelAdmin`` both define an ``exclude``
  233. option then ``ModelAdmin`` takes precedence::
  234. class PersonForm(forms.ModelForm):
  235. class Meta:
  236. model = Person
  237. exclude = ['name']
  238. class PersonAdmin(admin.ModelAdmin):
  239. exclude = ['age']
  240. form = PersonForm
  241. In the above example, the "age" field will be excluded but the "name"
  242. field will be included in the generated form.
  243. .. attribute:: ModelAdmin.formfield_overrides
  244. This provides a quick-and-dirty way to override some of the
  245. :class:`~django.forms.Field` options for use in the admin.
  246. ``formfield_overrides`` is a dictionary mapping a field class to a dict of
  247. arguments to pass to the field at construction time.
  248. Since that's a bit abstract, let's look at a concrete example. The most
  249. common use of ``formfield_overrides`` is to add a custom widget for a
  250. certain type of field. So, imagine we've written a ``RichTextEditorWidget``
  251. that we'd like to use for large text fields instead of the default
  252. ``<textarea>``. Here's how we'd do that::
  253. from django.db import models
  254. from django.contrib import admin
  255. # Import our custom widget and our model from where they're defined
  256. from myapp.widgets import RichTextEditorWidget
  257. from myapp.models import MyModel
  258. class MyModelAdmin(admin.ModelAdmin):
  259. formfield_overrides = {
  260. models.TextField: {'widget': RichTextEditorWidget},
  261. }
  262. Note that the key in the dictionary is the actual field class, *not* a
  263. string. The value is another dictionary; these arguments will be passed to
  264. the form field's ``__init__()`` method. See :doc:`/ref/forms/api` for
  265. details.
  266. .. warning::
  267. If you want to use a custom widget with a relation field (i.e.
  268. :class:`~django.db.models.ForeignKey` or
  269. :class:`~django.db.models.ManyToManyField`), make sure you haven't
  270. included that field's name in ``raw_id_fields`` or ``radio_fields``.
  271. ``formfield_overrides`` won't let you change the widget on relation
  272. fields that have ``raw_id_fields`` or ``radio_fields`` set. That's
  273. because ``raw_id_fields`` and ``radio_fields`` imply custom widgets of
  274. their own.
  275. .. attribute:: ModelAdmin.inlines
  276. See :class:`InlineModelAdmin` objects below as well as
  277. :meth:`ModelAdmin.get_formsets`.
  278. .. attribute:: ModelAdmin.list_display
  279. Set ``list_display`` to control which fields are displayed on the change
  280. list page of the admin.
  281. Example::
  282. list_display = ('first_name', 'last_name')
  283. If you don't set ``list_display``, the admin site will display a single
  284. column that displays the ``__unicode__()`` representation of each object.
  285. You have four possible values that can be used in ``list_display``:
  286. * A field of the model. For example::
  287. class PersonAdmin(admin.ModelAdmin):
  288. list_display = ('first_name', 'last_name')
  289. * A callable that accepts one parameter for the model instance. For
  290. example::
  291. def upper_case_name(obj):
  292. return ("%s %s" % (obj.first_name, obj.last_name)).upper()
  293. upper_case_name.short_description = 'Name'
  294. class PersonAdmin(admin.ModelAdmin):
  295. list_display = (upper_case_name,)
  296. * A string representing an attribute on the ``ModelAdmin``. This
  297. behaves same as the callable. For example::
  298. class PersonAdmin(admin.ModelAdmin):
  299. list_display = ('upper_case_name',)
  300. def upper_case_name(self, obj):
  301. return ("%s %s" % (obj.first_name, obj.last_name)).upper()
  302. upper_case_name.short_description = 'Name'
  303. * A string representing an attribute on the model. This behaves almost
  304. the same as the callable, but ``self`` in this context is the model
  305. instance. Here's a full model example::
  306. class Person(models.Model):
  307. name = models.CharField(max_length=50)
  308. birthday = models.DateField()
  309. def decade_born_in(self):
  310. return self.birthday.strftime('%Y')[:3] + "0's"
  311. decade_born_in.short_description = 'Birth decade'
  312. class PersonAdmin(admin.ModelAdmin):
  313. list_display = ('name', 'decade_born_in')
  314. A few special cases to note about ``list_display``:
  315. * If the field is a ``ForeignKey``, Django will display the
  316. ``__unicode__()`` of the related object.
  317. * ``ManyToManyField`` fields aren't supported, because that would
  318. entail executing a separate SQL statement for each row in the table.
  319. If you want to do this nonetheless, give your model a custom method,
  320. and add that method's name to ``list_display``. (See below for more
  321. on custom methods in ``list_display``.)
  322. * If the field is a ``BooleanField`` or ``NullBooleanField``, Django
  323. will display a pretty "on" or "off" icon instead of ``True`` or
  324. ``False``.
  325. * If the string given is a method of the model, ``ModelAdmin`` or a
  326. callable, Django will HTML-escape the output by default. If you'd
  327. rather not escape the output of the method, give the method an
  328. ``allow_tags`` attribute whose value is ``True``. However, to avoid an
  329. XSS vulnerability, you should use :func:`~django.utils.html.format_html`
  330. to escape user-provided inputs.
  331. Here's a full example model::
  332. from django.utils.html import format_html
  333. class Person(models.Model):
  334. first_name = models.CharField(max_length=50)
  335. last_name = models.CharField(max_length=50)
  336. color_code = models.CharField(max_length=6)
  337. def colored_name(self):
  338. return format_html('<span style="color: #{0};">{1} {2}</span>',
  339. self.color_code,
  340. self.first_name,
  341. self.last_name)
  342. colored_name.allow_tags = True
  343. class PersonAdmin(admin.ModelAdmin):
  344. list_display = ('first_name', 'last_name', 'colored_name')
  345. * If the string given is a method of the model, ``ModelAdmin`` or a
  346. callable that returns True or False Django will display a pretty
  347. "on" or "off" icon if you give the method a ``boolean`` attribute
  348. whose value is ``True``.
  349. Here's a full example model::
  350. class Person(models.Model):
  351. first_name = models.CharField(max_length=50)
  352. birthday = models.DateField()
  353. def born_in_fifties(self):
  354. return self.birthday.strftime('%Y')[:3] == '195'
  355. born_in_fifties.boolean = True
  356. class PersonAdmin(admin.ModelAdmin):
  357. list_display = ('name', 'born_in_fifties')
  358. * The ``__str__()`` and ``__unicode__()`` methods are just as valid in
  359. ``list_display`` as any other model method, so it's perfectly OK to
  360. do this::
  361. list_display = ('__unicode__', 'some_other_field')
  362. * Usually, elements of ``list_display`` that aren't actual database
  363. fields can't be used in sorting (because Django does all the sorting
  364. at the database level).
  365. However, if an element of ``list_display`` represents a certain
  366. database field, you can indicate this fact by setting the
  367. ``admin_order_field`` attribute of the item.
  368. For example::
  369. from django.utils.html import format_html
  370. class Person(models.Model):
  371. first_name = models.CharField(max_length=50)
  372. color_code = models.CharField(max_length=6)
  373. def colored_first_name(self):
  374. return format_html('<span style="color: #{0};">{1}</span>',
  375. self.color_code,
  376. self.first_name)
  377. colored_first_name.allow_tags = True
  378. colored_first_name.admin_order_field = 'first_name'
  379. class PersonAdmin(admin.ModelAdmin):
  380. list_display = ('first_name', 'colored_first_name')
  381. The above will tell Django to order by the ``first_name`` field when
  382. trying to sort by ``colored_first_name`` in the admin.
  383. .. attribute:: ModelAdmin.list_display_links
  384. Set ``list_display_links`` to control which fields in ``list_display``
  385. should be linked to the "change" page for an object.
  386. By default, the change list page will link the first column -- the first
  387. field specified in ``list_display`` -- to the change page for each item.
  388. But ``list_display_links`` lets you change which columns are linked. Set
  389. ``list_display_links`` to a list or tuple of fields (in the same
  390. format as ``list_display``) to link.
  391. ``list_display_links`` can specify one or many fields. As long as the
  392. fields appear in ``list_display``, Django doesn't care how many (or
  393. how few) fields are linked. The only requirement is: If you want to use
  394. ``list_display_links``, you must define ``list_display``.
  395. In this example, the ``first_name`` and ``last_name`` fields will be
  396. linked on the change list page::
  397. class PersonAdmin(admin.ModelAdmin):
  398. list_display = ('first_name', 'last_name', 'birthday')
  399. list_display_links = ('first_name', 'last_name')
  400. .. _admin-list-editable:
  401. .. attribute:: ModelAdmin.list_editable
  402. Set ``list_editable`` to a list of field names on the model which will
  403. allow editing on the change list page. That is, fields listed in
  404. ``list_editable`` will be displayed as form widgets on the change list
  405. page, allowing users to edit and save multiple rows at once.
  406. .. note::
  407. ``list_editable`` interacts with a couple of other options in
  408. particular ways; you should note the following rules:
  409. * Any field in ``list_editable`` must also be in ``list_display``.
  410. You can't edit a field that's not displayed!
  411. * The same field can't be listed in both ``list_editable`` and
  412. ``list_display_links`` -- a field can't be both a form and
  413. a link.
  414. You'll get a validation error if either of these rules are broken.
  415. .. attribute:: ModelAdmin.list_filter
  416. Set ``list_filter`` to activate filters in the right sidebar of the change
  417. list page of the admin, as illustrated in the following screenshot:
  418. .. image:: _images/users_changelist.png
  419. ``list_filter`` should be a list or tuple of elements, where each element
  420. should be of one of the following types:
  421. * a field name, where the specified field should be either a
  422. ``BooleanField``, ``CharField``, ``DateField``, ``DateTimeField``,
  423. ``IntegerField``, ``ForeignKey`` or ``ManyToManyField``, for example::
  424. class PersonAdmin(ModelAdmin):
  425. list_filter = ('is_staff', 'company')
  426. Field names in ``list_filter`` can also span relations
  427. using the ``__`` lookup, for example::
  428. class PersonAdmin(UserAdmin):
  429. list_filter = ('company__name',)
  430. * a class inheriting from ``django.contrib.admin.SimpleListFilter``,
  431. which you need to provide the ``title`` and ``parameter_name``
  432. attributes to and override the ``lookups`` and ``queryset`` methods,
  433. e.g.::
  434. from datetime import date
  435. from django.utils.translation import ugettext_lazy as _
  436. from django.contrib.admin import SimpleListFilter
  437. class DecadeBornListFilter(SimpleListFilter):
  438. # Human-readable title which will be displayed in the
  439. # right admin sidebar just above the filter options.
  440. title = _('decade born')
  441. # Parameter for the filter that will be used in the URL query.
  442. parameter_name = 'decade'
  443. def lookups(self, request, model_admin):
  444. """
  445. Returns a list of tuples. The first element in each
  446. tuple is the coded value for the option that will
  447. appear in the URL query. The second element is the
  448. human-readable name for the option that will appear
  449. in the right sidebar.
  450. """
  451. return (
  452. ('80s', _('in the eighties')),
  453. ('90s', _('in the nineties')),
  454. )
  455. def queryset(self, request, queryset):
  456. """
  457. Returns the filtered queryset based on the value
  458. provided in the query string and retrievable via
  459. `self.value()`.
  460. """
  461. # Compare the requested value (either '80s' or '90s')
  462. # to decide how to filter the queryset.
  463. if self.value() == '80s':
  464. return queryset.filter(birthday__gte=date(1980, 1, 1),
  465. birthday__lte=date(1989, 12, 31))
  466. if self.value() == '90s':
  467. return queryset.filter(birthday__gte=date(1990, 1, 1),
  468. birthday__lte=date(1999, 12, 31))
  469. class PersonAdmin(ModelAdmin):
  470. list_filter = (DecadeBornListFilter,)
  471. .. note::
  472. As a convenience, the ``HttpRequest`` object is passed to the
  473. ``lookups`` and ``queryset`` methods, for example::
  474. class AuthDecadeBornListFilter(DecadeBornListFilter):
  475. def lookups(self, request, model_admin):
  476. if request.user.is_superuser:
  477. return super(AuthDecadeBornListFilter,
  478. self).lookups(request, model_admin)
  479. def queryset(self, request, queryset):
  480. if request.user.is_superuser:
  481. return super(AuthDecadeBornListFilter,
  482. self).queryset(request, queryset)
  483. Also as a convenience, the ``ModelAdmin`` object is passed to
  484. the ``lookups`` method, for example if you want to base the
  485. lookups on the available data::
  486. class AdvancedDecadeBornListFilter(DecadeBornListFilter):
  487. def lookups(self, request, model_admin):
  488. """
  489. Only show the lookups if there actually is
  490. anyone born in the corresponding decades.
  491. """
  492. qs = model_admin.queryset(request)
  493. if qs.filter(birthday__gte=date(1980, 1, 1),
  494. birthday__lte=date(1989, 12, 31)).exists():
  495. yield ('80s', _('in the eighties'))
  496. if qs.filter(birthday__gte=date(1990, 1, 1),
  497. birthday__lte=date(1999, 12, 31)).exists():
  498. yield ('90s', _('in the nineties'))
  499. * a tuple, where the first element is a field name and the second
  500. element is a class inheriting from
  501. ``django.contrib.admin.FieldListFilter``, for example::
  502. from django.contrib.admin import BooleanFieldListFilter
  503. class PersonAdmin(ModelAdmin):
  504. list_filter = (
  505. ('is_staff', BooleanFieldListFilter),
  506. )
  507. .. note::
  508. The ``FieldListFilter`` API is considered internal and might be
  509. changed.
  510. It is possible to specify a custom template for rendering a list filter::
  511. class FilterWithCustomTemplate(SimpleListFilter):
  512. template = "custom_template.html"
  513. See the default template provided by django (``admin/filter.html``) for
  514. a concrete example.
  515. .. attribute:: ModelAdmin.list_max_show_all
  516. Set ``list_max_show_all`` to control how many items can appear on a "Show
  517. all" admin change list page. The admin will display a "Show all" link on the
  518. change list only if the total result count is less than or equal to this
  519. setting. By default, this is set to ``200``.
  520. .. attribute:: ModelAdmin.list_per_page
  521. Set ``list_per_page`` to control how many items appear on each paginated
  522. admin change list page. By default, this is set to ``100``.
  523. .. attribute:: ModelAdmin.list_select_related
  524. Set ``list_select_related`` to tell Django to use
  525. :meth:`~django.db.models.query.QuerySet.select_related` in retrieving
  526. the list of objects on the admin change list page. This can save you a
  527. bunch of database queries.
  528. The value should be either ``True`` or ``False``. Default is ``False``.
  529. Note that Django will use
  530. :meth:`~django.db.models.query.QuerySet.select_related`,
  531. regardless of this setting if one of the ``list_display`` fields is a
  532. ``ForeignKey``.
  533. .. attribute:: ModelAdmin.ordering
  534. Set ``ordering`` to specify how lists of objects should be ordered in the
  535. Django admin views. This should be a list or tuple in the same format as a
  536. model's :attr:`~django.db.models.Options.ordering` parameter.
  537. If this isn't provided, the Django admin will use the model's default
  538. ordering.
  539. If you need to specify a dynamic order (for example depending on user or
  540. language) you can implement a :meth:`~ModelAdmin.get_ordering` method.
  541. .. attribute:: ModelAdmin.paginator
  542. The paginator class to be used for pagination. By default,
  543. :class:`django.core.paginator.Paginator` is used. If the custom paginator
  544. class doesn't have the same constructor interface as
  545. :class:`django.core.paginator.Paginator`, you will also need to
  546. provide an implementation for :meth:`ModelAdmin.get_paginator`.
  547. .. attribute:: ModelAdmin.prepopulated_fields
  548. Set ``prepopulated_fields`` to a dictionary mapping field names to the
  549. fields it should prepopulate from::
  550. class ArticleAdmin(admin.ModelAdmin):
  551. prepopulated_fields = {"slug": ("title",)}
  552. When set, the given fields will use a bit of JavaScript to populate from
  553. the fields assigned. The main use for this functionality is to
  554. automatically generate the value for ``SlugField`` fields from one or more
  555. other fields. The generated value is produced by concatenating the values
  556. of the source fields, and then by transforming that result into a valid
  557. slug (e.g. substituting dashes for spaces).
  558. ``prepopulated_fields`` doesn't accept ``DateTimeField``, ``ForeignKey``,
  559. nor ``ManyToManyField`` fields.
  560. .. attribute:: ModelAdmin.radio_fields
  561. By default, Django's admin uses a select-box interface (<select>) for
  562. fields that are ``ForeignKey`` or have ``choices`` set. If a field is
  563. present in ``radio_fields``, Django will use a radio-button interface
  564. instead. Assuming ``group`` is a ``ForeignKey`` on the ``Person`` model::
  565. class PersonAdmin(admin.ModelAdmin):
  566. radio_fields = {"group": admin.VERTICAL}
  567. You have the choice of using ``HORIZONTAL`` or ``VERTICAL`` from the
  568. ``django.contrib.admin`` module.
  569. Don't include a field in ``radio_fields`` unless it's a ``ForeignKey`` or has
  570. ``choices`` set.
  571. .. attribute:: ModelAdmin.raw_id_fields
  572. By default, Django's admin uses a select-box interface (<select>) for
  573. fields that are ``ForeignKey``. Sometimes you don't want to incur the
  574. overhead of having to select all the related instances to display in the
  575. drop-down.
  576. ``raw_id_fields`` is a list of fields you would like to change
  577. into an ``Input`` widget for either a ``ForeignKey`` or
  578. ``ManyToManyField``::
  579. class ArticleAdmin(admin.ModelAdmin):
  580. raw_id_fields = ("newspaper",)
  581. The ``raw_id_fields`` ``Input`` widget should contain a primary key if the
  582. field is a ``ForeignKey`` or a comma separated list of values if the field
  583. is a ``ManyToManyField``. The ``raw_id_fields`` widget shows a magnifying
  584. glass button next to the field which allows users to search for and select
  585. a value:
  586. .. image:: _images/raw_id_fields.png
  587. .. attribute:: ModelAdmin.readonly_fields
  588. By default the admin shows all fields as editable. Any fields in this
  589. option (which should be a ``list`` or ``tuple``) will display its data
  590. as-is and non-editable; they are also excluded from the
  591. :class:`~django.forms.ModelForm` used for creating and editing. Note that
  592. when specifying :attr:`ModelAdmin.fields` or :attr:`ModelAdmin.fieldsets`
  593. the read-only fields must be present to be shown (they are ignored
  594. otherwise).
  595. If ``readonly_fields`` is used without defining explicit ordering through
  596. :attr:`ModelAdmin.fields` or :attr:`ModelAdmin.fieldsets` they will be
  597. added last after all editable fields.
  598. A read-only field can not only display data from a model's field, it can
  599. also display the output of a model's method or a method of the
  600. ``ModelAdmin`` class itself. This is very similar to the way
  601. :attr:`ModelAdmin.list_display` behaves. This provides an easy way to use
  602. the admin interface to provide feedback on the status of the objects being
  603. edited, for example::
  604. from django.utils.html import format_html_join
  605. from django.utils.safestring import mark_safe
  606. class PersonAdmin(ModelAdmin):
  607. readonly_fields = ('address_report',)
  608. def address_report(self, instance):
  609. # assuming get_full_address() returns a list of strings
  610. # for each line of the address and you want to separate each
  611. # line by a linebreak
  612. return format_html_join(
  613. mark_safe('<br/>'),
  614. '{0}',
  615. ((line,) for line in instance.get_full_address()),
  616. ) or "<span class='errors'>I can't determine this address.</span>"
  617. # short_description functions like a model field's verbose_name
  618. address_report.short_description = "Address"
  619. # in this example, we have used HTML tags in the output
  620. address_report.allow_tags = True
  621. .. attribute:: ModelAdmin.save_as
  622. Set ``save_as`` to enable a "save as" feature on admin change forms.
  623. Normally, objects have three save options: "Save", "Save and continue
  624. editing" and "Save and add another". If ``save_as`` is ``True``, "Save
  625. and add another" will be replaced by a "Save as" button.
  626. "Save as" means the object will be saved as a new object (with a new ID),
  627. rather than the old object.
  628. By default, ``save_as`` is set to ``False``.
  629. .. attribute:: ModelAdmin.save_on_top
  630. Set ``save_on_top`` to add save buttons across the top of your admin change
  631. forms.
  632. Normally, the save buttons appear only at the bottom of the forms. If you
  633. set ``save_on_top``, the buttons will appear both on the top and the
  634. bottom.
  635. By default, ``save_on_top`` is set to ``False``.
  636. .. attribute:: ModelAdmin.search_fields
  637. Set ``search_fields`` to enable a search box on the admin change list page.
  638. This should be set to a list of field names that will be searched whenever
  639. somebody submits a search query in that text box.
  640. These fields should be some kind of text field, such as ``CharField`` or
  641. ``TextField``. You can also perform a related lookup on a ``ForeignKey`` or
  642. ``ManyToManyField`` with the lookup API "follow" notation::
  643. search_fields = ['foreign_key__related_fieldname']
  644. For example, if you have a blog entry with an author, the following
  645. definition would enable search blog entries by the email address of the
  646. author::
  647. search_fields = ['user__email']
  648. When somebody does a search in the admin search box, Django splits the
  649. search query into words and returns all objects that contain each of the
  650. words, case insensitive, where each word must be in at least one of
  651. ``search_fields``. For example, if ``search_fields`` is set to
  652. ``['first_name', 'last_name']`` and a user searches for ``john lennon``,
  653. Django will do the equivalent of this SQL ``WHERE`` clause::
  654. WHERE (first_name ILIKE '%john%' OR last_name ILIKE '%john%')
  655. AND (first_name ILIKE '%lennon%' OR last_name ILIKE '%lennon%')
  656. For faster and/or more restrictive searches, prefix the field name
  657. with an operator:
  658. ``^``
  659. Matches the beginning of the field. For example, if ``search_fields``
  660. is set to ``['^first_name', '^last_name']`` and a user searches for
  661. ``john lennon``, Django will do the equivalent of this SQL ``WHERE``
  662. clause::
  663. WHERE (first_name ILIKE 'john%' OR last_name ILIKE 'john%')
  664. AND (first_name ILIKE 'lennon%' OR last_name ILIKE 'lennon%')
  665. This query is more efficient than the normal ``'%john%'`` query,
  666. because the database only needs to check the beginning of a column's
  667. data, rather than seeking through the entire column's data. Plus, if
  668. the column has an index on it, some databases may be able to use the
  669. index for this query, even though it's a ``LIKE`` query.
  670. ``=``
  671. Matches exactly, case-insensitive. For example, if
  672. ``search_fields`` is set to ``['=first_name', '=last_name']`` and
  673. a user searches for ``john lennon``, Django will do the equivalent
  674. of this SQL ``WHERE`` clause::
  675. WHERE (first_name ILIKE 'john' OR last_name ILIKE 'john')
  676. AND (first_name ILIKE 'lennon' OR last_name ILIKE 'lennon')
  677. Note that the query input is split by spaces, so, following this
  678. example, it's currently not possible to search for all records in which
  679. ``first_name`` is exactly ``'john winston'`` (containing a space).
  680. ``@``
  681. Performs a full-text match. This is like the default search method but
  682. uses an index. Currently this is only available for MySQL.
  683. Custom template options
  684. ~~~~~~~~~~~~~~~~~~~~~~~
  685. The `Overriding Admin Templates`_ section describes how to override or extend
  686. the default admin templates. Use the following options to override the default
  687. templates used by the :class:`ModelAdmin` views:
  688. .. attribute:: ModelAdmin.add_form_template
  689. Path to a custom template, used by :meth:`add_view`.
  690. .. attribute:: ModelAdmin.change_form_template
  691. Path to a custom template, used by :meth:`change_view`.
  692. .. attribute:: ModelAdmin.change_list_template
  693. Path to a custom template, used by :meth:`changelist_view`.
  694. .. attribute:: ModelAdmin.delete_confirmation_template
  695. Path to a custom template, used by :meth:`delete_view` for displaying a
  696. confirmation page when deleting one or more objects.
  697. .. attribute:: ModelAdmin.delete_selected_confirmation_template
  698. Path to a custom template, used by the ``delete_selected`` action method
  699. for displaying a confirmation page when deleting one or more objects. See
  700. the :doc:`actions documentation</ref/contrib/admin/actions>`.
  701. .. attribute:: ModelAdmin.object_history_template
  702. Path to a custom template, used by :meth:`history_view`.
  703. .. _model-admin-methods:
  704. ``ModelAdmin`` methods
  705. ----------------------
  706. .. warning::
  707. :meth:`ModelAdmin.save_model` and :meth:`ModelAdmin.delete_model` must
  708. save/delete the object, they are not for veto purposes, rather they allow
  709. you to perform extra operations.
  710. .. method:: ModelAdmin.save_model(self, request, obj, form, change)
  711. The ``save_model`` method is given the ``HttpRequest``, a model instance,
  712. a ``ModelForm`` instance and a boolean value based on whether it is adding
  713. or changing the object. Here you can do any pre- or post-save operations.
  714. For example to attach ``request.user`` to the object prior to saving::
  715. class ArticleAdmin(admin.ModelAdmin):
  716. def save_model(self, request, obj, form, change):
  717. obj.user = request.user
  718. obj.save()
  719. .. method:: ModelAdmin.delete_model(self, request, obj)
  720. The ``delete_model`` method is given the ``HttpRequest`` and a model
  721. instance. Use this method to do pre- or post-delete operations.
  722. .. method:: ModelAdmin.save_formset(self, request, form, formset, change)
  723. The ``save_formset`` method is given the ``HttpRequest``, the parent
  724. ``ModelForm`` instance and a boolean value based on whether it is adding or
  725. changing the parent object.
  726. For example to attach ``request.user`` to each changed formset
  727. model instance::
  728. class ArticleAdmin(admin.ModelAdmin):
  729. def save_formset(self, request, form, formset, change):
  730. instances = formset.save(commit=False)
  731. for instance in instances:
  732. instance.user = request.user
  733. instance.save()
  734. formset.save_m2m()
  735. .. method:: ModelAdmin.get_ordering(self, request)
  736. The ``get_ordering`` method takes a``request`` as parameter and
  737. is expected to return a ``list`` or ``tuple`` for ordering similar
  738. to the :attr:`ordering` attribute. For example::
  739. class PersonAdmin(ModelAdmin):
  740. def get_ordering(self, request):
  741. if request.user.is_superuser:
  742. return ['name', 'rank']
  743. else:
  744. return ['name']
  745. .. method:: ModelAdmin.save_related(self, request, form, formsets, change)
  746. The ``save_related`` method is given the ``HttpRequest``, the parent
  747. ``ModelForm`` instance, the list of inline formsets and a boolean value
  748. based on whether the parent is being added or changed. Here you can do any
  749. pre- or post-save operations for objects related to the parent. Note
  750. that at this point the parent object and its form have already been saved.
  751. .. method:: ModelAdmin.get_readonly_fields(self, request, obj=None)
  752. The ``get_readonly_fields`` method is given the ``HttpRequest`` and the
  753. ``obj`` being edited (or ``None`` on an add form) and is expected to return
  754. a ``list`` or ``tuple`` of field names that will be displayed as read-only,
  755. as described above in the :attr:`ModelAdmin.readonly_fields` section.
  756. .. method:: ModelAdmin.get_prepopulated_fields(self, request, obj=None)
  757. The ``get_prepopulated_fields`` method is given the ``HttpRequest`` and the
  758. ``obj`` being edited (or ``None`` on an add form) and is expected to return
  759. a ``dictionary``, as described above in the :attr:`ModelAdmin.prepopulated_fields`
  760. section.
  761. .. method:: ModelAdmin.get_list_display(self, request)
  762. The ``get_list_display`` method is given the ``HttpRequest`` and is
  763. expected to return a ``list`` or ``tuple`` of field names that will be
  764. displayed on the changelist view as described above in the
  765. :attr:`ModelAdmin.list_display` section.
  766. .. method:: ModelAdmin.get_list_display_links(self, request, list_display)
  767. The ``get_list_display_links`` method is given the ``HttpRequest`` and
  768. the ``list`` or ``tuple`` returned by :meth:`ModelAdmin.get_list_display`.
  769. It is expected to return a ``list`` or ``tuple`` of field names on the
  770. changelist that will be linked to the change view, as described in the
  771. :attr:`ModelAdmin.list_display_links` section.
  772. .. method:: ModelAdmin.get_fieldsets(self, request, obj=None)
  773. The ``get_fieldsets`` method is given the ``HttpRequest`` and the ``obj``
  774. being edited (or ``None`` on an add form) and is expected to return a list
  775. of two-tuples, in which each two-tuple represents a ``<fieldset>`` on the
  776. admin form page, as described above in the :attr:`ModelAdmin.fieldsets` section.
  777. .. method:: ModelAdmin.get_list_filter(self, request)
  778. .. versionadded:: 1.5
  779. The ``get_list_filter`` method is given the ``HttpRequest`` and is expected
  780. to return the same kind of sequence type as for the
  781. :attr:`~ModelAdmin.list_filter` attribute.
  782. .. method:: ModelAdmin.get_inline_instances(self, request, obj=None)
  783. .. versionadded:: 1.5
  784. The ``get_inline_instances`` method is given the ``HttpRequest`` and the
  785. ``obj`` being edited (or ``None`` on an add form) and is expected to return
  786. a ``list`` or ``tuple`` of :class:`~django.contrib.admin.InlineModelAdmin`
  787. objects, as described below in the :class:`~django.contrib.admin.InlineModelAdmin`
  788. section.
  789. .. method:: ModelAdmin.get_urls(self)
  790. The ``get_urls`` method on a ``ModelAdmin`` returns the URLs to be used for
  791. that ModelAdmin in the same way as a URLconf. Therefore you can extend
  792. them as documented in :doc:`/topics/http/urls`::
  793. class MyModelAdmin(admin.ModelAdmin):
  794. def get_urls(self):
  795. urls = super(MyModelAdmin, self).get_urls()
  796. my_urls = patterns('',
  797. (r'^my_view/$', self.my_view)
  798. )
  799. return my_urls + urls
  800. def my_view(self, request):
  801. # custom view which should return an HttpResponse
  802. pass
  803. .. note::
  804. Notice that the custom patterns are included *before* the regular admin
  805. URLs: the admin URL patterns are very permissive and will match nearly
  806. anything, so you'll usually want to prepend your custom URLs to the
  807. built-in ones.
  808. In this example, ``my_view`` will be accessed at
  809. ``/admin/myapp/mymodel/my_view/`` (assuming the admin URLs are included
  810. at ``/admin/``.)
  811. However, the ``self.my_view`` function registered above suffers from two
  812. problems:
  813. * It will *not* perform any permission checks, so it will be accessible
  814. to the general public.
  815. * It will *not* provide any header details to prevent caching. This means
  816. if the page retrieves data from the database, and caching middleware is
  817. active, the page could show outdated information.
  818. Since this is usually not what you want, Django provides a convenience
  819. wrapper to check permissions and mark the view as non-cacheable. This
  820. wrapper is ``AdminSite.admin_view()`` (i.e. ``self.admin_site.admin_view``
  821. inside a ``ModelAdmin`` instance); use it like so::
  822. class MyModelAdmin(admin.ModelAdmin):
  823. def get_urls(self):
  824. urls = super(MyModelAdmin, self).get_urls()
  825. my_urls = patterns('',
  826. (r'^my_view/$', self.admin_site.admin_view(self.my_view))
  827. )
  828. return my_urls + urls
  829. Notice the wrapped view in the fifth line above::
  830. (r'^my_view/$', self.admin_site.admin_view(self.my_view))
  831. This wrapping will protect ``self.my_view`` from unauthorized access and
  832. will apply the ``django.views.decorators.cache.never_cache`` decorator to
  833. make sure it is not cached if the cache middleware is active.
  834. If the page is cacheable, but you still want the permission check to be
  835. performed, you can pass a ``cacheable=True`` argument to
  836. ``AdminSite.admin_view()``::
  837. (r'^my_view/$', self.admin_site.admin_view(self.my_view, cacheable=True))
  838. .. method:: ModelAdmin.get_form(self, request, obj=None, **kwargs)
  839. Returns a :class:`~django.forms.ModelForm` class for use in the admin add
  840. and change views, see :meth:`add_view` and :meth:`change_view`.
  841. If you wanted to hide a field from non-superusers, for example, you could
  842. override ``get_form`` as follows::
  843. class MyModelAdmin(admin.ModelAdmin):
  844. def get_form(self, request, obj=None, **kwargs):
  845. self.exclude = []
  846. if not request.user.is_superuser:
  847. self.exclude.append('field_to_hide')
  848. return super(MyModelAdmin, self).get_form(request, obj, **kwargs)
  849. .. method:: ModelAdmin.get_formsets(self, request, obj=None)
  850. Yields :class:`InlineModelAdmin`\s for use in admin add and change views.
  851. For example if you wanted to display a particular inline only in the change
  852. view, you could override ``get_formsets`` as follows::
  853. class MyModelAdmin(admin.ModelAdmin):
  854. inlines = [MyInline, SomeOtherInline]
  855. def get_formsets(self, request, obj=None):
  856. for inline in self.get_inline_instances(request, obj):
  857. # hide MyInline in the add view
  858. if isinstance(inline, MyInline) and obj is None:
  859. continue
  860. yield inline.get_formset(request, obj)
  861. .. method:: ModelAdmin.formfield_for_foreignkey(self, db_field, request, **kwargs)
  862. The ``formfield_for_foreignkey`` method on a ``ModelAdmin`` allows you to
  863. override the default formfield for a foreign keys field. For example, to
  864. return a subset of objects for this foreign key field based on the user::
  865. class MyModelAdmin(admin.ModelAdmin):
  866. def formfield_for_foreignkey(self, db_field, request, **kwargs):
  867. if db_field.name == "car":
  868. kwargs["queryset"] = Car.objects.filter(owner=request.user)
  869. return super(MyModelAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
  870. This uses the ``HttpRequest`` instance to filter the ``Car`` foreign key
  871. field to only display the cars owned by the ``User`` instance.
  872. .. method:: ModelAdmin.formfield_for_manytomany(self, db_field, request, **kwargs)
  873. Like the ``formfield_for_foreignkey`` method, the
  874. ``formfield_for_manytomany`` method can be overridden to change the
  875. default formfield for a many to many field. For example, if an owner can
  876. own multiple cars and cars can belong to multiple owners -- a many to
  877. many relationship -- you could filter the ``Car`` foreign key field to
  878. only display the cars owned by the ``User``::
  879. class MyModelAdmin(admin.ModelAdmin):
  880. def formfield_for_manytomany(self, db_field, request, **kwargs):
  881. if db_field.name == "cars":
  882. kwargs["queryset"] = Car.objects.filter(owner=request.user)
  883. return super(MyModelAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)
  884. .. method:: ModelAdmin.formfield_for_choice_field(self, db_field, request, **kwargs)
  885. Like the ``formfield_for_foreignkey`` and ``formfield_for_manytomany``
  886. methods, the ``formfield_for_choice_field`` method can be overridden to
  887. change the default formfield for a field that has declared choices. For
  888. example, if the choices available to a superuser should be different than
  889. those available to regular staff, you could proceed as follows::
  890. class MyModelAdmin(admin.ModelAdmin):
  891. def formfield_for_choice_field(self, db_field, request, **kwargs):
  892. if db_field.name == "status":
  893. kwargs['choices'] = (
  894. ('accepted', 'Accepted'),
  895. ('denied', 'Denied'),
  896. )
  897. if request.user.is_superuser:
  898. kwargs['choices'] += (('ready', 'Ready for deployment'),)
  899. return super(MyModelAdmin, self).formfield_for_choice_field(db_field, request, **kwargs)
  900. .. method:: ModelAdmin.get_changelist(self, request, **kwargs)
  901. Returns the ``Changelist`` class to be used for listing. By default,
  902. ``django.contrib.admin.views.main.ChangeList`` is used. By inheriting this
  903. class you can change the behavior of the listing.
  904. .. method:: ModelAdmin.get_changelist_form(self, request, **kwargs)
  905. Returns a :class:`~django.forms.ModelForm` class for use in the ``Formset``
  906. on the changelist page. To use a custom form, for example::
  907. class MyForm(forms.ModelForm):
  908. class Meta:
  909. model = MyModel
  910. class MyModelAdmin(admin.ModelAdmin):
  911. def get_changelist_form(self, request, **kwargs):
  912. return MyForm
  913. .. method:: ModelAdmin.get_changelist_formset(self, request, **kwargs)
  914. Returns a :ref:`ModelFormSet <model-formsets>` class for use on the
  915. changelist page if :attr:`~ModelAdmin.list_editable` is used. To use a
  916. custom formset, for example::
  917. from django.forms.models import BaseModelFormSet
  918. class MyAdminFormSet(BaseModelFormSet):
  919. pass
  920. class MyModelAdmin(admin.ModelAdmin):
  921. def get_changelist_formset(self, request, **kwargs):
  922. kwargs['formset'] = MyAdminFormSet
  923. return super(MyModelAdmin, self).get_changelist_formset(request, **kwargs)
  924. .. method:: ModelAdmin.has_add_permission(self, request)
  925. Should return ``True`` if adding an object is permitted, ``False``
  926. otherwise.
  927. .. method:: ModelAdmin.has_change_permission(self, request, obj=None)
  928. Should return ``True`` if editing obj is permitted, ``False`` otherwise.
  929. If obj is ``None``, should return ``True`` or ``False`` to indicate whether
  930. editing of objects of this type is permitted in general (e.g., ``False``
  931. will be interpreted as meaning that the current user is not permitted to
  932. edit any object of this type).
  933. .. method:: ModelAdmin.has_delete_permission(self, request, obj=None)
  934. Should return ``True`` if deleting obj is permitted, ``False`` otherwise.
  935. If obj is ``None``, should return ``True`` or ``False`` to indicate whether
  936. deleting objects of this type is permitted in general (e.g., ``False`` will
  937. be interpreted as meaning that the current user is not permitted to delete
  938. any object of this type).
  939. .. method:: ModelAdmin.queryset(self, request)
  940. The ``queryset`` method on a ``ModelAdmin`` returns a
  941. :class:`~django.db.models.query.QuerySet` of all model instances that
  942. can be edited by the admin site. One use case for overriding this method
  943. is to show objects owned by the logged-in user::
  944. class MyModelAdmin(admin.ModelAdmin):
  945. def queryset(self, request):
  946. qs = super(MyModelAdmin, self).queryset(request)
  947. if request.user.is_superuser:
  948. return qs
  949. return qs.filter(author=request.user)
  950. .. method:: ModelAdmin.message_user(request, message, level=messages.INFO, extra_tags='', fail_silently=False)
  951. Sends a message to the user using the :mod:`django.contrib.messages`
  952. backend. See the :ref:`custom ModelAdmin example <custom-admin-action>`.
  953. .. versionadded:: 1.5
  954. Keyword arguments allow you to change the message level, add extra CSS
  955. tags, or fail silently if the ``contrib.messages`` framework is not
  956. installed. These keyword arguments match those for
  957. :func:`django.contrib.messages.add_message`, see that function's
  958. documentation for more details. One difference is that the level may be
  959. passed as a string label in addition to integer/constant.
  960. .. method:: ModelAdmin.get_paginator(queryset, per_page, orphans=0, allow_empty_first_page=True)
  961. Returns an instance of the paginator to use for this view. By default,
  962. instantiates an instance of :attr:`paginator`.
  963. Other methods
  964. ~~~~~~~~~~~~~
  965. .. method:: ModelAdmin.add_view(self, request, form_url='', extra_context=None)
  966. Django view for the model instance addition page. See note below.
  967. .. method:: ModelAdmin.change_view(self, request, object_id, form_url='', extra_context=None)
  968. Django view for the model instance edition page. See note below.
  969. .. method:: ModelAdmin.changelist_view(self, request, extra_context=None)
  970. Django view for the model instances change list/actions page. See note
  971. below.
  972. .. method:: ModelAdmin.delete_view(self, request, object_id, extra_context=None)
  973. Django view for the model instance(s) deletion confirmation page. See note
  974. below.
  975. .. method:: ModelAdmin.history_view(self, request, object_id, extra_context=None)
  976. Django view for the page that shows the modification history for a given
  977. model instance.
  978. Unlike the hook-type ``ModelAdmin`` methods detailed in the previous section,
  979. these five methods are in reality designed to be invoked as Django views from
  980. the admin application URL dispatching handler to render the pages that deal
  981. with model instances CRUD operations. As a result, completely overriding these
  982. methods will significantly change the behavior of the admin application.
  983. One common reason for overriding these methods is to augment the context data
  984. that is provided to the template that renders the view. In the following
  985. example, the change view is overridden so that the rendered template is
  986. provided some extra mapping data that would not otherwise be available::
  987. class MyModelAdmin(admin.ModelAdmin):
  988. # A template for a very customized change view:
  989. change_form_template = 'admin/myapp/extras/openstreetmap_change_form.html'
  990. def get_osm_info(self):
  991. # ...
  992. pass
  993. def change_view(self, request, object_id, form_url='', extra_context=None):
  994. extra_context = extra_context or {}
  995. extra_context['osm_data'] = self.get_osm_info()
  996. return super(MyModelAdmin, self).change_view(request, object_id,
  997. form_url, extra_context=extra_context)
  998. These views return :class:`~django.template.response.TemplateResponse`
  999. instances which allow you to easily customize the response data before
  1000. rendering. For more details, see the :doc:`TemplateResponse documentation
  1001. </ref/template-response>`.
  1002. .. _modeladmin-media-definitions:
  1003. ``ModelAdmin`` media definitions
  1004. --------------------------------
  1005. There are times where you would like add a bit of CSS and/or JavaScript to
  1006. the add/change views. This can be accomplished by using a Media inner class
  1007. on your ``ModelAdmin``::
  1008. class ArticleAdmin(admin.ModelAdmin):
  1009. class Media:
  1010. css = {
  1011. "all": ("my_styles.css",)
  1012. }
  1013. js = ("my_code.js",)
  1014. The :doc:`staticfiles app </ref/contrib/staticfiles>` prepends
  1015. :setting:`STATIC_URL` (or :setting:`MEDIA_URL` if :setting:`STATIC_URL` is
  1016. ``None``) to any media paths. The same rules apply as :ref:`regular media
  1017. definitions on forms <form-media-paths>`.
  1018. jQuery
  1019. ~~~~~~
  1020. Django admin Javascript makes use of the `jQuery`_ library.
  1021. To avoid conflicts with user-supplied scripts or libraries, Django's jQuery
  1022. (version 1.4.2) is namespaced as ``django.jQuery``. If you want to use jQuery
  1023. in your own admin JavaScript without including a second copy, you can use the
  1024. ``django.jQuery`` object on changelist and add/edit views.
  1025. The :class:`ModelAdmin` class requires jQuery by default, so there is no need
  1026. to add jQuery to your ``ModelAdmin``'s list of media resources unless you have
  1027. a specifc need. For example, if you require the jQuery library to be in the
  1028. global namespace (for example when using third-party jQuery plugins) or if you
  1029. need a newer version of jQuery, you will have to include your own copy.
  1030. Django provides both uncompressed and 'minified' versions of jQuery, as
  1031. ``jquery.js`` and ``jquery.min.js`` respectively.
  1032. :class:`ModelAdmin` and :class:`InlineModelAdmin` have a ``media`` property
  1033. that returns a list of ``Media`` objects which store paths to the JavaScript
  1034. files for the forms and/or formsets. If :setting:`DEBUG` is ``True`` it will
  1035. return the uncompressed versions of the various JavaScript files, including
  1036. ``jquery.js``; if not, it will return the 'minified' versions.
  1037. .. _jQuery: http://jquery.com
  1038. Adding custom validation to the admin
  1039. -------------------------------------
  1040. Adding custom validation of data in the admin is quite easy. The automatic
  1041. admin interface reuses :mod:`django.forms`, and the ``ModelAdmin`` class gives
  1042. you the ability define your own form::
  1043. class ArticleAdmin(admin.ModelAdmin):
  1044. form = MyArticleAdminForm
  1045. ``MyArticleAdminForm`` can be defined anywhere as long as you import where
  1046. needed. Now within your form you can add your own custom validation for
  1047. any field::
  1048. class MyArticleAdminForm(forms.ModelForm):
  1049. class Meta:
  1050. model = Article
  1051. def clean_name(self):
  1052. # do something that validates your data
  1053. return self.cleaned_data["name"]
  1054. It is important you use a ``ModelForm`` here otherwise things can break. See
  1055. the :doc:`forms </ref/forms/index>` documentation on :doc:`custom validation
  1056. </ref/forms/validation>` and, more specifically, the
  1057. :ref:`model form validation notes <overriding-modelform-clean-method>` for more
  1058. information.
  1059. .. _admin-inlines:
  1060. ``InlineModelAdmin`` objects
  1061. ============================
  1062. .. class:: InlineModelAdmin
  1063. .. class:: TabularInline
  1064. .. class:: StackedInline
  1065. The admin interface has the ability to edit models on the same page as a
  1066. parent model. These are called inlines. Suppose you have these two models::
  1067. class Author(models.Model):
  1068. name = models.CharField(max_length=100)
  1069. class Book(models.Model):
  1070. author = models.ForeignKey(Author)
  1071. title = models.CharField(max_length=100)
  1072. You can edit the books authored by an author on the author page. You add
  1073. inlines to a model by specifying them in a ``ModelAdmin.inlines``::
  1074. class BookInline(admin.TabularInline):
  1075. model = Book
  1076. class AuthorAdmin(admin.ModelAdmin):
  1077. inlines = [
  1078. BookInline,
  1079. ]
  1080. Django provides two subclasses of ``InlineModelAdmin`` and they are:
  1081. * :class:`~django.contrib.admin.TabularInline`
  1082. * :class:`~django.contrib.admin.StackedInline`
  1083. The difference between these two is merely the template used to render
  1084. them.
  1085. ``InlineModelAdmin`` options
  1086. -----------------------------
  1087. ``InlineModelAdmin`` shares many of the same features as ``ModelAdmin``, and
  1088. adds some of its own (the shared features are actually defined in the
  1089. ``BaseModelAdmin`` superclass). The shared features are:
  1090. - :attr:`~InlineModelAdmin.form`
  1091. - :attr:`~ModelAdmin.fieldsets`
  1092. - :attr:`~ModelAdmin.fields`
  1093. - :attr:`~ModelAdmin.formfield_overrides`
  1094. - :attr:`~ModelAdmin.exclude`
  1095. - :attr:`~ModelAdmin.filter_horizontal`
  1096. - :attr:`~ModelAdmin.filter_vertical`
  1097. - :attr:`~ModelAdmin.ordering`
  1098. - :attr:`~ModelAdmin.prepopulated_fields`
  1099. - :meth:`~ModelAdmin.queryset`
  1100. - :attr:`~ModelAdmin.radio_fields`
  1101. - :attr:`~ModelAdmin.readonly_fields`
  1102. - :attr:`~InlineModelAdmin.raw_id_fields`
  1103. - :meth:`~ModelAdmin.formfield_for_foreignkey`
  1104. - :meth:`~ModelAdmin.formfield_for_manytomany`
  1105. - :meth:`~ModelAdmin.has_add_permission`
  1106. - :meth:`~ModelAdmin.has_change_permission`
  1107. - :meth:`~ModelAdmin.has_delete_permission`
  1108. The ``InlineModelAdmin`` class adds:
  1109. .. attribute:: InlineModelAdmin.model
  1110. The model which the inline is using. This is required.
  1111. .. attribute:: InlineModelAdmin.fk_name
  1112. The name of the foreign key on the model. In most cases this will be dealt
  1113. with automatically, but ``fk_name`` must be specified explicitly if there
  1114. are more than one foreign key to the same parent model.
  1115. .. attribute:: InlineModelAdmin.formset
  1116. This defaults to ``BaseInlineFormSet``. Using your own formset can give you
  1117. many possibilities of customization. Inlines are built around
  1118. :ref:`model formsets <model-formsets>`.
  1119. .. attribute:: InlineModelAdmin.form
  1120. The value for ``form`` defaults to ``ModelForm``. This is what is passed
  1121. through to :func:`~django.forms.models.inlineformset_factory` when
  1122. creating the formset for this inline.
  1123. .. attribute:: InlineModelAdmin.extra
  1124. This controls the number of extra forms the formset will display in
  1125. addition to the initial forms. See the
  1126. :doc:`formsets documentation </topics/forms/formsets>` for more
  1127. information.
  1128. For users with JavaScript-enabled browsers, an "Add another" link is
  1129. provided to enable any number of additional inlines to be added in addition
  1130. to those provided as a result of the ``extra`` argument.
  1131. The dynamic link will not appear if the number of currently displayed forms
  1132. exceeds ``max_num``, or if the user does not have JavaScript enabled.
  1133. .. _ref-contrib-admin-inline-max-num:
  1134. .. attribute:: InlineModelAdmin.max_num
  1135. This controls the maximum number of forms to show in the inline. This
  1136. doesn't directly correlate to the number of objects, but can if the value
  1137. is small enough. See :ref:`model-formsets-max-num` for more information.
  1138. .. attribute:: InlineModelAdmin.raw_id_fields
  1139. By default, Django's admin uses a select-box interface (<select>) for
  1140. fields that are ``ForeignKey``. Sometimes you don't want to incur the
  1141. overhead of having to select all the related instances to display in the
  1142. drop-down.
  1143. ``raw_id_fields`` is a list of fields you would like to change into a
  1144. ``Input`` widget for either a ``ForeignKey`` or ``ManyToManyField``::
  1145. class BookInline(admin.TabularInline):
  1146. model = Book
  1147. raw_id_fields = ("pages",)
  1148. .. attribute:: InlineModelAdmin.template
  1149. The template used to render the inline on the page.
  1150. .. attribute:: InlineModelAdmin.verbose_name
  1151. An override to the ``verbose_name`` found in the model's inner ``Meta``
  1152. class.
  1153. .. attribute:: InlineModelAdmin.verbose_name_plural
  1154. An override to the ``verbose_name_plural`` found in the model's inner
  1155. ``Meta`` class.
  1156. .. attribute:: InlineModelAdmin.can_delete
  1157. Specifies whether or not inline objects can be deleted in the inline.
  1158. Defaults to ``True``.
  1159. .. method:: InlineModelAdmin.get_formset(self, request, obj=None, **kwargs)
  1160. Returns a ``BaseInlineFormSet`` class for use in admin add/change views.
  1161. See the example for :class:`ModelAdmin.get_formsets`.
  1162. Working with a model with two or more foreign keys to the same parent model
  1163. ---------------------------------------------------------------------------
  1164. It is sometimes possible to have more than one foreign key to the same model.
  1165. Take this model for instance::
  1166. class Friendship(models.Model):
  1167. to_person = models.ForeignKey(Person, related_name="friends")
  1168. from_person = models.ForeignKey(Person, related_name="from_friends")
  1169. If you wanted to display an inline on the ``Person`` admin add/change pages
  1170. you need to explicitly define the foreign key since it is unable to do so
  1171. automatically::
  1172. class FriendshipInline(admin.TabularInline):
  1173. model = Friendship
  1174. fk_name = "to_person"
  1175. class PersonAdmin(admin.ModelAdmin):
  1176. inlines = [
  1177. FriendshipInline,
  1178. ]
  1179. Working with many-to-many models
  1180. --------------------------------
  1181. By default, admin widgets for many-to-many relations will be displayed
  1182. on whichever model contains the actual reference to the
  1183. :class:`~django.db.models.ManyToManyField`. Depending on your ``ModelAdmin``
  1184. definition, each many-to-many field in your model will be represented by a
  1185. standard HTML ``<select multiple>``, a horizontal or vertical filter, or a
  1186. ``raw_id_admin`` widget. However, it is also possible to replace these
  1187. widgets with inlines.
  1188. Suppose we have the following models::
  1189. class Person(models.Model):
  1190. name = models.CharField(max_length=128)
  1191. class Group(models.Model):
  1192. name = models.CharField(max_length=128)
  1193. members = models.ManyToManyField(Person, related_name='groups')
  1194. If you want to display many-to-many relations using an inline, you can do
  1195. so by defining an ``InlineModelAdmin`` object for the relationship::
  1196. class MembershipInline(admin.TabularInline):
  1197. model = Group.members.through
  1198. class PersonAdmin(admin.ModelAdmin):
  1199. inlines = [
  1200. MembershipInline,
  1201. ]
  1202. class GroupAdmin(admin.ModelAdmin):
  1203. inlines = [
  1204. MembershipInline,
  1205. ]
  1206. exclude = ('members',)
  1207. There are two features worth noting in this example.
  1208. Firstly - the ``MembershipInline`` class references ``Group.members.through``.
  1209. The ``through`` attribute is a reference to the model that manages the
  1210. many-to-many relation. This model is automatically created by Django when you
  1211. define a many-to-many field.
  1212. Secondly, the ``GroupAdmin`` must manually exclude the ``members`` field.
  1213. Django displays an admin widget for a many-to-many field on the model that
  1214. defines the relation (in this case, ``Group``). If you want to use an inline
  1215. model to represent the many-to-many relationship, you must tell Django's admin
  1216. to *not* display this widget - otherwise you will end up with two widgets on
  1217. your admin page for managing the relation.
  1218. In all other respects, the ``InlineModelAdmin`` is exactly the same as any
  1219. other. You can customize the appearance using any of the normal
  1220. ``ModelAdmin`` properties.
  1221. Working with many-to-many intermediary models
  1222. ---------------------------------------------
  1223. When you specify an intermediary model using the ``through`` argument to a
  1224. :class:`~django.db.models.ManyToManyField`, the admin will not display a
  1225. widget by default. This is because each instance of that intermediary model
  1226. requires more information than could be displayed in a single widget, and the
  1227. layout required for multiple widgets will vary depending on the intermediate
  1228. model.
  1229. However, we still want to be able to edit that information inline. Fortunately,
  1230. this is easy to do with inline admin models. Suppose we have the following
  1231. models::
  1232. class Person(models.Model):
  1233. name = models.CharField(max_length=128)
  1234. class Group(models.Model):
  1235. name = models.CharField(max_length=128)
  1236. members = models.ManyToManyField(Person, through='Membership')
  1237. class Membership(models.Model):
  1238. person = models.ForeignKey(Person)
  1239. group = models.ForeignKey(Group)
  1240. date_joined = models.DateField()
  1241. invite_reason = models.CharField(max_length=64)
  1242. The first step in displaying this intermediate model in the admin is to
  1243. define an inline class for the ``Membership`` model::
  1244. class MembershipInline(admin.TabularInline):
  1245. model = Membership
  1246. extra = 1
  1247. This simple example uses the default ``InlineModelAdmin`` values for the
  1248. ``Membership`` model, and limits the extra add forms to one. This could be
  1249. customized using any of the options available to ``InlineModelAdmin`` classes.
  1250. Now create admin views for the ``Person`` and ``Group`` models::
  1251. class PersonAdmin(admin.ModelAdmin):
  1252. inlines = (MembershipInline,)
  1253. class GroupAdmin(admin.ModelAdmin):
  1254. inlines = (MembershipInline,)
  1255. Finally, register your ``Person`` and ``Group`` models with the admin site::
  1256. admin.site.register(Person, PersonAdmin)
  1257. admin.site.register(Group, GroupAdmin)
  1258. Now your admin site is set up to edit ``Membership`` objects inline from
  1259. either the ``Person`` or the ``Group`` detail pages.
  1260. .. _using-generic-relations-as-an-inline:
  1261. Using generic relations as an inline
  1262. ------------------------------------
  1263. It is possible to use an inline with generically related objects. Let's say
  1264. you have the following models::
  1265. class Image(models.Model):
  1266. image = models.ImageField(upload_to="images")
  1267. content_type = models.ForeignKey(ContentType)
  1268. object_id = models.PositiveIntegerField()
  1269. content_object = generic.GenericForeignKey("content_type", "object_id")
  1270. class Product(models.Model):
  1271. name = models.CharField(max_length=100)
  1272. If you want to allow editing and creating ``Image`` instance on the ``Product``
  1273. add/change views you can use ``GenericTabularInline`` or
  1274. ``GenericStackedInline`` (both subclasses of ``GenericInlineModelAdmin``)
  1275. provided by ``django.contrib.contenttypes.generic``, they implement tabular and
  1276. stacked visual layouts for the forms representing the inline objects
  1277. respectively just like their non-generic counterparts and behave just like any
  1278. other inline. In your ``admin.py`` for this example app::
  1279. from django.contrib import admin
  1280. from django.contrib.contenttypes import generic
  1281. from myproject.myapp.models import Image, Product
  1282. class ImageInline(generic.GenericTabularInline):
  1283. model = Image
  1284. class ProductAdmin(admin.ModelAdmin):
  1285. inlines = [
  1286. ImageInline,
  1287. ]
  1288. admin.site.register(Product, ProductAdmin)
  1289. See the :doc:`contenttypes documentation </ref/contrib/contenttypes>` for more
  1290. specific information.
  1291. Overriding admin templates
  1292. ==========================
  1293. It is relatively easy to override many of the templates which the admin module
  1294. uses to generate the various pages of an admin site. You can even override a
  1295. few of these templates for a specific app, or a specific model.
  1296. Set up your projects admin template directories
  1297. -----------------------------------------------
  1298. The admin template files are located in the ``contrib/admin/templates/admin``
  1299. directory.
  1300. In order to override one or more of them, first create an ``admin`` directory
  1301. in your project's ``templates`` directory. This can be any of the directories
  1302. you specified in :setting:`TEMPLATE_DIRS`.
  1303. Within this ``admin`` directory, create sub-directories named after your app.
  1304. Within these app subdirectories create sub-directories named after your models.
  1305. Note, that the admin app will lowercase the model name when looking for the
  1306. directory, so make sure you name the directory in all lowercase if you are
  1307. going to run your app on a case-sensitive filesystem.
  1308. To override an admin template for a specific app, copy and edit the template
  1309. from the ``django/contrib/admin/templates/admin`` directory, and save it to one
  1310. of the directories you just created.
  1311. For example, if we wanted to add a tool to the change list view for all the
  1312. models in an app named ``my_app``, we would copy
  1313. ``contrib/admin/templates/admin/change_list.html`` to the
  1314. ``templates/admin/my_app/`` directory of our project, and make any necessary
  1315. changes.
  1316. If we wanted to add a tool to the change list view for only a specific model
  1317. named 'Page', we would copy that same file to the
  1318. ``templates/admin/my_app/page`` directory of our project.
  1319. Overriding vs. replacing an admin template
  1320. ------------------------------------------
  1321. Because of the modular design of the admin templates, it is usually neither
  1322. necessary nor advisable to replace an entire template. It is almost always
  1323. better to override only the section of the template which you need to change.
  1324. To continue the example above, we want to add a new link next to the
  1325. ``History`` tool for the ``Page`` model. After looking at ``change_form.html``
  1326. we determine that we only need to override the ``object-tools-items`` block.
  1327. Therefore here is our new ``change_form.html`` :
  1328. .. code-block:: html+django
  1329. {% extends "admin/change_form.html" %}
  1330. {% load i18n admin_urls %}
  1331. {% block object-tools-items %}
  1332. <li>
  1333. <a href="{% url opts|admin_urlname:'history' original.pk|admin_urlquote %}" class="historylink">{% trans "History" %}</a>
  1334. </li>
  1335. <li>
  1336. <a href="mylink/" class="historylink">My Link</a>
  1337. </li>
  1338. {% if has_absolute_url %}
  1339. <li>
  1340. <a href="{% url 'admin:view_on_site' content_type_id original.pk %}" class="viewsitelink">{% trans "View on site" %}</a>
  1341. </li>
  1342. {% endif%}
  1343. {% endblock %}
  1344. And that's it! If we placed this file in the ``templates/admin/my_app``
  1345. directory, our link would appear on the change form for all models within
  1346. my_app.
  1347. Templates which may be overridden per app or model
  1348. --------------------------------------------------
  1349. Not every template in ``contrib/admin/templates/admin`` may be overridden per
  1350. app or per model. The following can:
  1351. * ``app_index.html``
  1352. * ``change_form.html``
  1353. * ``change_list.html``
  1354. * ``delete_confirmation.html``
  1355. * ``object_history.html``
  1356. For those templates that cannot be overridden in this way, you may still
  1357. override them for your entire project. Just place the new version in your
  1358. ``templates/admin`` directory. This is particularly useful to create custom 404
  1359. and 500 pages.
  1360. .. note::
  1361. Some of the admin templates, such as ``change_list_request.html`` are used
  1362. to render custom inclusion tags. These may be overridden, but in such cases
  1363. you are probably better off creating your own version of the tag in
  1364. question and giving it a different name. That way you can use it
  1365. selectively.
  1366. Root and login templates
  1367. ------------------------
  1368. If you wish to change the index, login or logout templates, you are better off
  1369. creating your own ``AdminSite`` instance (see below), and changing the
  1370. :attr:`AdminSite.index_template` , :attr:`AdminSite.login_template` or
  1371. :attr:`AdminSite.logout_template` properties.
  1372. ``AdminSite`` objects
  1373. =====================
  1374. .. class:: AdminSite(name='admin')
  1375. A Django administrative site is represented by an instance of
  1376. ``django.contrib.admin.sites.AdminSite``; by default, an instance of
  1377. this class is created as ``django.contrib.admin.site`` and you can
  1378. register your models and ``ModelAdmin`` instances with it.
  1379. If you'd like to set up your own administrative site with custom
  1380. behavior, however, you're free to subclass ``AdminSite`` and override
  1381. or add anything you like. Then, simply create an instance of your
  1382. ``AdminSite`` subclass (the same way you'd instantiate any other
  1383. Python class), and register your models and ``ModelAdmin`` subclasses
  1384. with it instead of using the default.
  1385. When constructing an instance of an ``AdminSite``, you are able to provide
  1386. a unique instance name using the ``name`` argument to the constructor. This
  1387. instance name is used to identify the instance, especially when
  1388. :ref:`reversing admin URLs <admin-reverse-urls>`. If no instance name is
  1389. provided, a default instance name of ``admin`` will be used.
  1390. ``AdminSite`` attributes
  1391. ------------------------
  1392. Templates can override or extend base admin templates as described in
  1393. `Overriding Admin Templates`_.
  1394. .. attribute:: AdminSite.index_template
  1395. Path to a custom template that will be used by the admin site main index
  1396. view.
  1397. .. attribute:: AdminSite.login_template
  1398. Path to a custom template that will be used by the admin site login view.
  1399. .. attribute:: AdminSite.login_form
  1400. Subclass of :class:`~django.contrib.auth.forms.AuthenticationForm` that
  1401. will be used by the admin site login view.
  1402. .. attribute:: AdminSite.logout_template
  1403. Path to a custom template that will be used by the admin site logout view.
  1404. .. attribute:: AdminSite.password_change_template
  1405. Path to a custom template that will be used by the admin site password
  1406. change view.
  1407. .. attribute:: AdminSite.password_change_done_template
  1408. Path to a custom template that will be used by the admin site password
  1409. change done view.
  1410. Hooking ``AdminSite`` instances into your URLconf
  1411. -------------------------------------------------
  1412. The last step in setting up the Django admin is to hook your ``AdminSite``
  1413. instance into your URLconf. Do this by pointing a given URL at the
  1414. ``AdminSite.urls`` method.
  1415. In this example, we register the default ``AdminSite`` instance
  1416. ``django.contrib.admin.site`` at the URL ``/admin/`` ::
  1417. # urls.py
  1418. from django.conf.urls import patterns, include
  1419. from django.contrib import admin
  1420. admin.autodiscover()
  1421. urlpatterns = patterns('',
  1422. (r'^admin/', include(admin.site.urls)),
  1423. )
  1424. Above we used ``admin.autodiscover()`` to automatically load the
  1425. :setting:`INSTALLED_APPS` admin.py modules.
  1426. In this example, we register the ``AdminSite`` instance
  1427. ``myproject.admin.admin_site`` at the URL ``/myadmin/`` ::
  1428. # urls.py
  1429. from django.conf.urls import patterns, include
  1430. from myproject.admin import admin_site
  1431. urlpatterns = patterns('',
  1432. (r'^myadmin/', include(admin_site.urls)),
  1433. )
  1434. There is really no need to use autodiscover when using your own ``AdminSite``
  1435. instance since you will likely be importing all the per-app admin.py modules
  1436. in your ``myproject.admin`` module.
  1437. Multiple admin sites in the same URLconf
  1438. ----------------------------------------
  1439. It's easy to create multiple instances of the admin site on the same
  1440. Django-powered Web site. Just create multiple instances of ``AdminSite`` and
  1441. root each one at a different URL.
  1442. In this example, the URLs ``/basic-admin/`` and ``/advanced-admin/`` feature
  1443. separate versions of the admin site -- using the ``AdminSite`` instances
  1444. ``myproject.admin.basic_site`` and ``myproject.admin.advanced_site``,
  1445. respectively::
  1446. # urls.py
  1447. from django.conf.urls import patterns, include
  1448. from myproject.admin import basic_site, advanced_site
  1449. urlpatterns = patterns('',
  1450. (r'^basic-admin/', include(basic_site.urls)),
  1451. (r'^advanced-admin/', include(advanced_site.urls)),
  1452. )
  1453. ``AdminSite`` instances take a single argument to their constructor, their
  1454. name, which can be anything you like. This argument becomes the prefix to the
  1455. URL names for the purposes of :ref:`reversing them<admin-reverse-urls>`. This
  1456. is only necessary if you are using more than one ``AdminSite``.
  1457. Adding views to admin sites
  1458. ---------------------------
  1459. Just like :class:`ModelAdmin`, :class:`AdminSite` provides a
  1460. :meth:`~django.contrib.admin.ModelAdmin.get_urls()` method
  1461. that can be overridden to define additional views for the site. To add
  1462. a new view to your admin site, extend the base
  1463. :meth:`~django.contrib.admin.ModelAdmin.get_urls()` method to include
  1464. a pattern for your new view.
  1465. .. note::
  1466. Any view you render that uses the admin templates, or extends the base
  1467. admin template, should provide the ``current_app`` argument to
  1468. :class:`~django.template.RequestContext` or
  1469. :class:`~django.template.Context` when rendering the template. It should
  1470. be set to either ``self.name`` if your view is on an ``AdminSite`` or
  1471. ``self.admin_site.name`` if your view is on a ``ModelAdmin``.
  1472. .. _auth_password_reset:
  1473. Adding a password-reset feature
  1474. -------------------------------
  1475. You can add a password-reset feature to the admin site by adding a few lines to
  1476. your URLconf. Specifically, add these four patterns:
  1477. .. code-block:: python
  1478. url(r'^admin/password_reset/$', 'django.contrib.auth.views.password_reset', name='admin_password_reset'),
  1479. (r'^admin/password_reset/done/$', 'django.contrib.auth.views.password_reset_done'),
  1480. (r'^reset/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$', 'django.contrib.auth.views.password_reset_confirm'),
  1481. (r'^reset/done/$', 'django.contrib.auth.views.password_reset_complete'),
  1482. (This assumes you've added the admin at ``admin/`` and requires that you put
  1483. the URLs starting with ``^admin/`` before the line that includes the admin app
  1484. itself).
  1485. The presence of the ``admin_password_reset`` named URL will cause a "forgotten
  1486. your password?" link to appear on the default admin log-in page under the
  1487. password box.
  1488. .. _admin-reverse-urls:
  1489. Reversing admin URLs
  1490. ====================
  1491. When an :class:`AdminSite` is deployed, the views provided by that site are
  1492. accessible using Django's :ref:`URL reversing system <naming-url-patterns>`.
  1493. The :class:`AdminSite` provides the following named URL patterns:
  1494. ========================= ======================== ==================================
  1495. Page URL name Parameters
  1496. ========================= ======================== ==================================
  1497. Index ``index``
  1498. Logout ``logout``
  1499. Password change ``password_change``
  1500. Password change done ``password_change_done``
  1501. i18n javascript ``jsi18n``
  1502. Application index page ``app_list`` ``app_label``
  1503. Redirect to object's page ``view_on_site`` ``content_type_id``, ``object_id``
  1504. ========================= ======================== ==================================
  1505. Each :class:`ModelAdmin` instance provides an additional set of named URLs:
  1506. ====================== =============================================== =============
  1507. Page URL name Parameters
  1508. ====================== =============================================== =============
  1509. Changelist ``{{ app_label }}_{{ model_name }}_changelist``
  1510. Add ``{{ app_label }}_{{ model_name }}_add``
  1511. History ``{{ app_label }}_{{ model_name }}_history`` ``object_id``
  1512. Delete ``{{ app_label }}_{{ model_name }}_delete`` ``object_id``
  1513. Change ``{{ app_label }}_{{ model_name }}_change`` ``object_id``
  1514. ====================== =============================================== =============
  1515. These named URLs are registered with the application namespace ``admin``, and
  1516. with an instance namespace corresponding to the name of the Site instance.
  1517. So - if you wanted to get a reference to the Change view for a particular
  1518. ``Choice`` object (from the polls application) in the default admin, you would
  1519. call::
  1520. >>> from django.core import urlresolvers
  1521. >>> c = Choice.objects.get(...)
  1522. >>> change_url = urlresolvers.reverse('admin:polls_choice_change', args=(c.id,))
  1523. This will find the first registered instance of the admin application
  1524. (whatever the instance name), and resolve to the view for changing
  1525. ``poll.Choice`` instances in that instance.
  1526. If you want to find a URL in a specific admin instance, provide the name of
  1527. that instance as a ``current_app`` hint to the reverse call. For example,
  1528. if you specifically wanted the admin view from the admin instance named
  1529. ``custom``, you would need to call::
  1530. >>> change_url = urlresolvers.reverse('custom:polls_choice_change', args=(c.id,))
  1531. For more details, see the documentation on :ref:`reversing namespaced URLs
  1532. <topics-http-reversing-url-namespaces>`.
  1533. To allow easier reversing of the admin urls in templates, Django provides an
  1534. ``admin_urlname`` filter which takes an action as argument:
  1535. .. code-block:: html+django
  1536. {% load admin_urls %}
  1537. <a href="{% url opts|admin_urlname:'add' %}">Add user</a>
  1538. <a href="{% url opts|admin_urlname:'delete' user.pk %}">Delete this user</a>
  1539. The action in the examples above match the last part of the URL names for
  1540. :class:`ModelAdmin` instances described above. The ``opts`` variable can be any
  1541. object which has an ``app_label`` and ``module_name`` and is usually supplied
  1542. by the admin views for the current model.