index.txt 76 KB

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