index.txt 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962
  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.QuerySet.select_related` in retrieving the list of
  512. objects on the admin change list page. This can save you a bunch of
  513. database queries.
  514. The value should be either ``True`` or ``False``. Default is ``False``.
  515. Note that Django will use :meth:`~django.db.models.QuerySet.select_related`,
  516. regardless of this setting if one of the ``list_display`` fields is a
  517. ``ForeignKey``.
  518. .. attribute:: ModelAdmin.ordering
  519. Set ``ordering`` to specify how lists of objects should be ordered in the
  520. Django admin views. This should be a list or tuple in the same format as a
  521. model's :attr:`~django.db.models.Options.ordering` parameter.
  522. If this isn't provided, the Django admin will use the model's default
  523. ordering.
  524. .. versionadded:: 1.4
  525. If you need to specify a dynamic order (for example depending on user or
  526. language) you can implement a :meth:`~ModelAdmin.get_ordering` method.
  527. .. versionchanged:: 1.4
  528. Django honors all elements in the list/tuple; before 1.4, only the first
  529. was respected.
  530. .. attribute:: ModelAdmin.paginator
  531. .. versionadded:: 1.3
  532. The paginator class to be used for pagination. By default,
  533. :class:`django.core.paginator.Paginator` is used. If the custom paginator
  534. class doesn't have the same constructor interface as
  535. :class:`django.core.paginator.Paginator`, you will also need to
  536. provide an implementation for :meth:`ModelAdmin.get_paginator`.
  537. .. attribute:: ModelAdmin.prepopulated_fields
  538. Set ``prepopulated_fields`` to a dictionary mapping field names to the
  539. fields it should prepopulate from::
  540. class ArticleAdmin(admin.ModelAdmin):
  541. prepopulated_fields = {"slug": ("title",)}
  542. When set, the given fields will use a bit of JavaScript to populate from
  543. the fields assigned. The main use for this functionality is to
  544. automatically generate the value for ``SlugField`` fields from one or more
  545. other fields. The generated value is produced by concatenating the values
  546. of the source fields, and then by transforming that result into a valid
  547. slug (e.g. substituting dashes for spaces).
  548. ``prepopulated_fields`` doesn't accept ``DateTimeField``, ``ForeignKey``,
  549. nor ``ManyToManyField`` fields.
  550. .. attribute:: ModelAdmin.radio_fields
  551. By default, Django's admin uses a select-box interface (<select>) for
  552. fields that are ``ForeignKey`` or have ``choices`` set. If a field is
  553. present in ``radio_fields``, Django will use a radio-button interface
  554. instead. Assuming ``group`` is a ``ForeignKey`` on the ``Person`` model::
  555. class PersonAdmin(admin.ModelAdmin):
  556. radio_fields = {"group": admin.VERTICAL}
  557. You have the choice of using ``HORIZONTAL`` or ``VERTICAL`` from the
  558. ``django.contrib.admin`` module.
  559. Don't include a field in ``radio_fields`` unless it's a ``ForeignKey`` or has
  560. ``choices`` set.
  561. .. attribute:: ModelAdmin.raw_id_fields
  562. By default, Django's admin uses a select-box interface (<select>) for
  563. fields that are ``ForeignKey``. Sometimes you don't want to incur the
  564. overhead of having to select all the related instances to display in the
  565. drop-down.
  566. ``raw_id_fields`` is a list of fields you would like to change
  567. into an ``Input`` widget for either a ``ForeignKey`` or
  568. ``ManyToManyField``::
  569. class ArticleAdmin(admin.ModelAdmin):
  570. raw_id_fields = ("newspaper",)
  571. .. attribute:: ModelAdmin.readonly_fields
  572. .. versionadded:: 1.2
  573. By default the admin shows all fields as editable. Any fields in this
  574. option (which should be a ``list`` or ``tuple``) will display its data
  575. as-is and non-editable. This option behaves nearly identical to
  576. :attr:`ModelAdmin.list_display`. Usage is the same, however, when you
  577. specify :attr:`ModelAdmin.fields` or :attr:`ModelAdmin.fieldsets` the
  578. read-only fields must be present to be shown (they are ignored otherwise).
  579. If ``readonly_fields`` is used without defining explicit ordering through
  580. :attr:`ModelAdmin.fields` or :attr:`ModelAdmin.fieldsets` they will be
  581. added last after all editable fields.
  582. .. attribute:: ModelAdmin.save_as
  583. Set ``save_as`` to enable a "save as" feature on admin change forms.
  584. Normally, objects have three save options: "Save", "Save and continue
  585. editing" and "Save and add another". If ``save_as`` is ``True``, "Save
  586. and add another" will be replaced by a "Save as" button.
  587. "Save as" means the object will be saved as a new object (with a new ID),
  588. rather than the old object.
  589. By default, ``save_as`` is set to ``False``.
  590. .. attribute:: ModelAdmin.save_on_top
  591. Set ``save_on_top`` to add save buttons across the top of your admin change
  592. forms.
  593. Normally, the save buttons appear only at the bottom of the forms. If you
  594. set ``save_on_top``, the buttons will appear both on the top and the
  595. bottom.
  596. By default, ``save_on_top`` is set to ``False``.
  597. .. attribute:: ModelAdmin.search_fields
  598. Set ``search_fields`` to enable a search box on the admin change list page.
  599. This should be set to a list of field names that will be searched whenever
  600. somebody submits a search query in that text box.
  601. These fields should be some kind of text field, such as ``CharField`` or
  602. ``TextField``. You can also perform a related lookup on a ``ForeignKey`` or
  603. ``ManyToManyField`` with the lookup API "follow" notation::
  604. search_fields = ['foreign_key__related_fieldname']
  605. For example, if you have a blog entry with an author, the following
  606. definition would enable search blog entries by the email address of the
  607. author::
  608. search_fields = ['user__email']
  609. When somebody does a search in the admin search box, Django splits the
  610. search query into words and returns all objects that contain each of the
  611. words, case insensitive, where each word must be in at least one of
  612. ``search_fields``. For example, if ``search_fields`` is set to
  613. ``['first_name', 'last_name']`` and a user searches for ``john lennon``,
  614. Django will do the equivalent of this SQL ``WHERE`` clause::
  615. WHERE (first_name ILIKE '%john%' OR last_name ILIKE '%john%')
  616. AND (first_name ILIKE '%lennon%' OR last_name ILIKE '%lennon%')
  617. For faster and/or more restrictive searches, prefix the field name
  618. with an operator:
  619. ``^``
  620. Matches the beginning of the field. For example, if ``search_fields``
  621. is set to ``['^first_name', '^last_name']`` and a user searches for
  622. ``john lennon``, Django will do the equivalent of this SQL ``WHERE``
  623. clause::
  624. WHERE (first_name ILIKE 'john%' OR last_name ILIKE 'john%')
  625. AND (first_name ILIKE 'lennon%' OR last_name ILIKE 'lennon%')
  626. This query is more efficient than the normal ``'%john%'`` query,
  627. because the database only needs to check the beginning of a column's
  628. data, rather than seeking through the entire column's data. Plus, if
  629. the column has an index on it, some databases may be able to use the
  630. index for this query, even though it's a ``LIKE`` query.
  631. ``=``
  632. Matches exactly, case-insensitive. For example, if
  633. ``search_fields`` is set to ``['=first_name', '=last_name']`` and
  634. a user searches for ``john lennon``, Django will do the equivalent
  635. of this SQL ``WHERE`` clause::
  636. WHERE (first_name ILIKE 'john' OR last_name ILIKE 'john')
  637. AND (first_name ILIKE 'lennon' OR last_name ILIKE 'lennon')
  638. Note that the query input is split by spaces, so, following this
  639. example, it's currently not possible to search for all records in which
  640. ``first_name`` is exactly ``'john winston'`` (containing a space).
  641. ``@``
  642. Performs a full-text match. This is like the default search method but
  643. uses an index. Currently this is only available for MySQL.
  644. Custom template options
  645. ~~~~~~~~~~~~~~~~~~~~~~~
  646. The `Overriding Admin Templates`_ section describes how to override or extend
  647. the default admin templates. Use the following options to override the default
  648. templates used by the :class:`ModelAdmin` views:
  649. .. attribute:: ModelAdmin.add_form_template
  650. .. versionadded:: 1.2
  651. Path to a custom template, used by :meth:`add_view`.
  652. .. attribute:: ModelAdmin.change_form_template
  653. Path to a custom template, used by :meth:`change_view`.
  654. .. attribute:: ModelAdmin.change_list_template
  655. Path to a custom template, used by :meth:`changelist_view`.
  656. .. attribute:: ModelAdmin.delete_confirmation_template
  657. Path to a custom template, used by :meth:`delete_view` for displaying a
  658. confirmation page when deleting one or more objects.
  659. .. attribute:: ModelAdmin.delete_selected_confirmation_template
  660. .. versionadded:: 1.2
  661. Path to a custom template, used by the :meth:`delete_selected`
  662. action method for displaying a confirmation page when deleting one
  663. or more objects. See the :doc:`actions
  664. documentation</ref/contrib/admin/actions>`.
  665. .. attribute:: ModelAdmin.object_history_template
  666. Path to a custom template, used by :meth:`history_view`.
  667. .. _model-admin-methods:
  668. ``ModelAdmin`` methods
  669. ----------------------
  670. .. warning::
  671. :meth:`ModelAdmin.save_model` and :meth:`ModelAdmin.delete_model` must
  672. save/delete the object, they are not for veto purposes, rather they allow
  673. you to perform extra operations.
  674. .. method:: ModelAdmin.save_model(self, request, obj, form, change)
  675. The ``save_model`` method is given the ``HttpRequest``, a model instance,
  676. a ``ModelForm`` instance and a boolean value based on whether it is adding
  677. or changing the object. Here you can do any pre- or post-save operations.
  678. For example to attach ``request.user`` to the object prior to saving::
  679. class ArticleAdmin(admin.ModelAdmin):
  680. def save_model(self, request, obj, form, change):
  681. obj.user = request.user
  682. obj.save()
  683. .. method:: ModelAdmin.delete_model(self, request, obj)
  684. .. versionadded:: 1.3
  685. The ``delete_model`` method is given the ``HttpRequest`` and a model
  686. instance. Use this method to do pre- or post-delete operations.
  687. .. method:: ModelAdmin.save_formset(self, request, form, formset, change)
  688. The ``save_formset`` method is given the ``HttpRequest``, the parent
  689. ``ModelForm`` instance and a boolean value based on whether it is adding or
  690. changing the parent object.
  691. For example to attach ``request.user`` to each changed formset
  692. model instance::
  693. class ArticleAdmin(admin.ModelAdmin):
  694. def save_formset(self, request, form, formset, change):
  695. instances = formset.save(commit=False)
  696. for instance in instances:
  697. instance.user = request.user
  698. instance.save()
  699. formset.save_m2m()
  700. .. method:: ModelAdmin.get_ordering(self, request)
  701. .. versionadded:: 1.4
  702. The ``get_ordering`` method takes a``request`` as parameter and
  703. is expected to return a ``list`` or ``tuple`` for ordering similar
  704. to the :attr:`ordering` attribute. For example::
  705. class PersonAdmin(ModelAdmin):
  706. def get_ordering(self, request):
  707. if request.user.is_superuser:
  708. return ['name', 'rank']
  709. else:
  710. return ['name']
  711. .. method:: ModelAdmin.save_related(self, request, form, formsets, change)
  712. .. versionadded:: 1.4
  713. The ``save_related`` method is given the ``HttpRequest``, the parent
  714. ``ModelForm`` instance, the list of inline formsets and a boolean value
  715. based on whether the parent is being added or changed. Here you can do any
  716. pre- or post-save operations for objects related to the parent. Note
  717. that at this point the parent object and its form have already been saved.
  718. .. method:: ModelAdmin.get_readonly_fields(self, request, obj=None)
  719. .. versionadded:: 1.2
  720. The ``get_readonly_fields`` method is given the ``HttpRequest`` and the
  721. ``obj`` being edited (or ``None`` on an add form) and is expected to return
  722. a ``list`` or ``tuple`` of field names that will be displayed as read-only,
  723. as described above in the :attr:`ModelAdmin.readonly_fields` section.
  724. .. method:: ModelAdmin.get_prepopulated_fields(self, request, obj=None)
  725. .. versionadded:: 1.4
  726. The ``get_prepopulated_fields`` method is given the ``HttpRequest`` and the
  727. ``obj`` being edited (or ``None`` on an add form) and is expected to return
  728. a ``dictionary``, as described above in the :attr:`ModelAdmin.prepopulated_fields`
  729. section.
  730. .. method:: ModelAdmin.get_list_display(self, request)
  731. .. versionadded:: 1.4
  732. The ``get_list_display`` method is given the ``HttpRequest`` and is
  733. expected to return a ``list`` or ``tuple`` of field names that will be
  734. displayed on the changelist view as described above in the
  735. :attr:`ModelAdmin.list_display` section.
  736. .. method:: ModelAdmin.get_urls(self)
  737. The ``get_urls`` method on a ``ModelAdmin`` returns the URLs to be used for
  738. that ModelAdmin in the same way as a URLconf. Therefore you can extend
  739. them as documented in :doc:`/topics/http/urls`::
  740. class MyModelAdmin(admin.ModelAdmin):
  741. def get_urls(self):
  742. urls = super(MyModelAdmin, self).get_urls()
  743. my_urls = patterns('',
  744. (r'^my_view/$', self.my_view)
  745. )
  746. return my_urls + urls
  747. def my_view(self, request):
  748. # custom view which should return an HttpResponse
  749. pass
  750. .. note::
  751. Notice that the custom patterns are included *before* the regular admin
  752. URLs: the admin URL patterns are very permissive and will match nearly
  753. anything, so you'll usually want to prepend your custom URLs to the
  754. built-in ones.
  755. In this example, ``my_view`` will be accessed at
  756. ``/admin/myapp/mymodel/my_view/`` (assuming the admin URLs are included
  757. at ``/admin/``.)
  758. However, the ``self.my_view`` function registered above suffers from two
  759. problems:
  760. * It will *not* perform any permission checks, so it will be accessible
  761. to the general public.
  762. * It will *not* provide any header details to prevent caching. This means
  763. if the page retrieves data from the database, and caching middleware is
  764. active, the page could show outdated information.
  765. Since this is usually not what you want, Django provides a convenience
  766. wrapper to check permissions and mark the view as non-cacheable. This
  767. wrapper is :meth:`AdminSite.admin_view` (i.e.
  768. ``self.admin_site.admin_view`` inside a ``ModelAdmin`` instance); use it
  769. like so::
  770. class MyModelAdmin(admin.ModelAdmin):
  771. def get_urls(self):
  772. urls = super(MyModelAdmin, self).get_urls()
  773. my_urls = patterns('',
  774. (r'^my_view/$', self.admin_site.admin_view(self.my_view))
  775. )
  776. return my_urls + urls
  777. Notice the wrapped view in the fifth line above::
  778. (r'^my_view/$', self.admin_site.admin_view(self.my_view))
  779. This wrapping will protect ``self.my_view`` from unauthorized access and
  780. will apply the ``django.views.decorators.cache.never_cache`` decorator to
  781. make sure it is not cached if the cache middleware is active.
  782. If the page is cacheable, but you still want the permission check to be
  783. performed, you can pass a ``cacheable=True`` argument to
  784. :meth:`AdminSite.admin_view`::
  785. (r'^my_view/$', self.admin_site.admin_view(self.my_view, cacheable=True))
  786. .. method:: ModelAdmin.formfield_for_foreignkey(self, db_field, request, **kwargs)
  787. The ``formfield_for_foreignkey`` method on a ``ModelAdmin`` allows you to
  788. override the default formfield for a foreign keys field. For example, to
  789. return a subset of objects for this foreign key field based on the user::
  790. class MyModelAdmin(admin.ModelAdmin):
  791. def formfield_for_foreignkey(self, db_field, request, **kwargs):
  792. if db_field.name == "car":
  793. kwargs["queryset"] = Car.objects.filter(owner=request.user)
  794. return super(MyModelAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
  795. This uses the ``HttpRequest`` instance to filter the ``Car`` foreign key
  796. field to only display the cars owned by the ``User`` instance.
  797. .. method:: ModelAdmin.formfield_for_manytomany(self, db_field, request, **kwargs)
  798. Like the ``formfield_for_foreignkey`` method, the
  799. ``formfield_for_manytomany`` method can be overridden to change the
  800. default formfield for a many to many field. For example, if an owner can
  801. own multiple cars and cars can belong to multiple owners -- a many to
  802. many relationship -- you could filter the ``Car`` foreign key field to
  803. only display the cars owned by the ``User``::
  804. class MyModelAdmin(admin.ModelAdmin):
  805. def formfield_for_manytomany(self, db_field, request, **kwargs):
  806. if db_field.name == "cars":
  807. kwargs["queryset"] = Car.objects.filter(owner=request.user)
  808. return super(MyModelAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)
  809. .. method:: ModelAdmin.formfield_for_choice_field(self, db_field, request, **kwargs)
  810. Like the ``formfield_for_foreignkey`` and ``formfield_for_manytomany``
  811. methods, the ``formfield_for_choice_field`` method can be overridden to
  812. change the default formfield for a field that has declared choices. For
  813. example, if the choices available to a superuser should be different than
  814. those available to regular staff, you could proceed as follows::
  815. class MyModelAdmin(admin.ModelAdmin):
  816. def formfield_for_choice_field(self, db_field, request, **kwargs):
  817. if db_field.name == "status":
  818. kwargs['choices'] = (
  819. ('accepted', 'Accepted'),
  820. ('denied', 'Denied'),
  821. )
  822. if request.user.is_superuser:
  823. kwargs['choices'] += (('ready', 'Ready for deployment'),)
  824. return super(MyModelAdmin, self).formfield_for_choice_field(db_field, request, **kwargs)
  825. .. method:: ModelAdmin.has_add_permission(self, request)
  826. Should return ``True`` if adding an object is permitted, ``False``
  827. otherwise.
  828. .. method:: ModelAdmin.has_change_permission(self, request, obj=None)
  829. Should return ``True`` if editing obj is permitted, ``False`` otherwise.
  830. If obj is ``None``, should return ``True`` or ``False`` to indicate whether
  831. editing of objects of this type is permitted in general (e.g., ``False``
  832. will be interpreted as meaning that the current user is not permitted to
  833. edit any object of this type).
  834. .. method:: ModelAdmin.has_delete_permission(self, request, obj=None)
  835. Should return ``True`` if deleting obj is permitted, ``False`` otherwise.
  836. If obj is ``None``, should return ``True`` or ``False`` to indicate whether
  837. deleting objects of this type is permitted in general (e.g., ``False`` will
  838. be interpreted as meaning that the current user is not permitted to delete
  839. any object of this type).
  840. .. method:: ModelAdmin.queryset(self, request)
  841. The ``queryset`` method on a ``ModelAdmin`` returns a
  842. :class:`~django.db.models.QuerySet` of all model instances that can be
  843. edited by the admin site. One use case for overriding this method is
  844. to show objects owned by the logged-in user::
  845. class MyModelAdmin(admin.ModelAdmin):
  846. def queryset(self, request):
  847. qs = super(MyModelAdmin, self).queryset(request)
  848. if request.user.is_superuser:
  849. return qs
  850. return qs.filter(author=request.user)
  851. .. method:: ModelAdmin.message_user(request, message)
  852. Sends a message to the user. The default implementation creates a message
  853. using the :mod:`django.contrib.messages` backend. See the
  854. :ref:`custom ModelAdmin example <custom-admin-action>`.
  855. .. method:: ModelAdmin.get_paginator(queryset, per_page, orphans=0, allow_empty_first_page=True)
  856. .. versionadded:: 1.3
  857. Returns an instance of the paginator to use for this view. By default,
  858. instantiates an instance of :attr:`paginator`.
  859. Other methods
  860. ~~~~~~~~~~~~~
  861. .. method:: ModelAdmin.add_view(self, request, form_url='', extra_context=None)
  862. Django view for the model instance addition page. See note below.
  863. .. method:: ModelAdmin.change_view(self, request, object_id, extra_context=None)
  864. Django view for the model instance edition page. See note below.
  865. .. method:: ModelAdmin.changelist_view(self, request, extra_context=None)
  866. Django view for the model instances change list/actions page. See note
  867. below.
  868. .. method:: ModelAdmin.delete_view(self, request, object_id, extra_context=None)
  869. Django view for the model instance(s) deletion confirmation page. See note
  870. below.
  871. .. method:: ModelAdmin.history_view(self, request, object_id, extra_context=None)
  872. Django view for the page that shows the modification history for a given
  873. model instance.
  874. Unlike the hook-type ``ModelAdmin`` methods detailed in the previous section,
  875. these five methods are in reality designed to be invoked as Django views from
  876. the admin application URL dispatching handler to render the pages that deal
  877. with model instances CRUD operations. As a result, completely overriding these
  878. methods will significantly change the behavior of the admin application.
  879. One common reason for overriding these methods is to augment the context data
  880. that is provided to the template that renders the view. In the following
  881. example, the change view is overridden so that the rendered template is
  882. provided some extra mapping data that would not otherwise be available::
  883. class MyModelAdmin(admin.ModelAdmin):
  884. # A template for a very customized change view:
  885. change_form_template = 'admin/myapp/extras/openstreetmap_change_form.html'
  886. def get_osm_info(self):
  887. # ...
  888. pass
  889. def change_view(self, request, object_id, extra_context=None):
  890. my_context = {
  891. 'osm_data': self.get_osm_info(),
  892. }
  893. return super(MyModelAdmin, self).change_view(request, object_id,
  894. extra_context=my_context)
  895. .. versionadded:: 1.4
  896. These views now return :class:`~django.template.response.TemplateResponse`
  897. instances which allow you to easily customize the response data before
  898. rendering. For more details, see the
  899. :doc:`TemplateResponse documentation </ref/template-response>`.
  900. ``ModelAdmin`` media definitions
  901. --------------------------------
  902. There are times where you would like add a bit of CSS and/or JavaScript to
  903. the add/change views. This can be accomplished by using a Media inner class
  904. on your ``ModelAdmin``::
  905. class ArticleAdmin(admin.ModelAdmin):
  906. class Media:
  907. css = {
  908. "all": ("my_styles.css",)
  909. }
  910. js = ("my_code.js",)
  911. .. versionchanged:: 1.3
  912. The :doc:`staticfiles app </ref/contrib/staticfiles>` prepends
  913. :setting:`STATIC_URL` (or :setting:`MEDIA_URL` if :setting:`STATIC_URL` is
  914. ``None``) to any media paths. The same rules apply as :ref:`regular media
  915. definitions on forms <form-media-paths>`.
  916. Django admin Javascript makes use of the `jQuery`_ library. To avoid
  917. conflict with user scripts, Django's jQuery is namespaced as
  918. ``django.jQuery``. If you want to use jQuery in your own admin
  919. JavaScript without including a second copy, you can use the
  920. ``django.jQuery`` object on changelist and add/edit views.
  921. .. _jQuery: http://jquery.com
  922. Adding custom validation to the admin
  923. -------------------------------------
  924. Adding custom validation of data in the admin is quite easy. The automatic
  925. admin interface reuses :mod:`django.forms`, and the ``ModelAdmin`` class gives
  926. you the ability define your own form::
  927. class ArticleAdmin(admin.ModelAdmin):
  928. form = MyArticleAdminForm
  929. ``MyArticleAdminForm`` can be defined anywhere as long as you import where
  930. needed. Now within your form you can add your own custom validation for
  931. any field::
  932. class MyArticleAdminForm(forms.ModelForm):
  933. class Meta:
  934. model = Article
  935. def clean_name(self):
  936. # do something that validates your data
  937. return self.cleaned_data["name"]
  938. It is important you use a ``ModelForm`` here otherwise things can break. See
  939. the :doc:`forms </ref/forms/index>` documentation on :doc:`custom validation
  940. </ref/forms/validation>` and, more specifically, the
  941. :ref:`model form validation notes <overriding-modelform-clean-method>` for more
  942. information.
  943. .. _admin-inlines:
  944. ``InlineModelAdmin`` objects
  945. ============================
  946. .. class:: InlineModelAdmin
  947. .. class:: TabularInline
  948. .. class:: StackedInline
  949. The admin interface has the ability to edit models on the same page as a
  950. parent model. These are called inlines. Suppose you have these two models::
  951. class Author(models.Model):
  952. name = models.CharField(max_length=100)
  953. class Book(models.Model):
  954. author = models.ForeignKey(Author)
  955. title = models.CharField(max_length=100)
  956. You can edit the books authored by an author on the author page. You add
  957. inlines to a model by specifying them in a ``ModelAdmin.inlines``::
  958. class BookInline(admin.TabularInline):
  959. model = Book
  960. class AuthorAdmin(admin.ModelAdmin):
  961. inlines = [
  962. BookInline,
  963. ]
  964. Django provides two subclasses of ``InlineModelAdmin`` and they are:
  965. * :class:`~django.contrib.admin.TabularInline`
  966. * :class:`~django.contrib.admin.StackedInline`
  967. The difference between these two is merely the template used to render
  968. them.
  969. ``InlineModelAdmin`` options
  970. -----------------------------
  971. ``InlineModelAdmin`` shares many of the same features as ``ModelAdmin``, and
  972. adds some of its own (the shared features are actually defined in the
  973. ``BaseModelAdmin`` superclass). The shared features are:
  974. - :attr:`~InlineModelAdmin.form`
  975. - :attr:`~ModelAdmin.fieldsets`
  976. - :attr:`~ModelAdmin.fields`
  977. - :attr:`~ModelAdmin.exclude`
  978. - :attr:`~ModelAdmin.filter_horizontal`
  979. - :attr:`~ModelAdmin.filter_vertical`
  980. - :attr:`~ModelAdmin.prepopulated_fields`
  981. - :attr:`~ModelAdmin.radio_fields`
  982. - :attr:`~InlineModelAdmin.raw_id_fields`
  983. - :meth:`~ModelAdmin.formfield_for_foreignkey`
  984. - :meth:`~ModelAdmin.formfield_for_manytomany`
  985. .. versionadded:: 1.2
  986. - :attr:`~ModelAdmin.readonly_fields`
  987. - :attr:`~ModelAdmin.formfield_overrides`
  988. .. versionadded:: 1.3
  989. - :attr:`~ModelAdmin.ordering`
  990. - :meth:`~ModelAdmin.queryset`
  991. The ``InlineModelAdmin`` class adds:
  992. .. attribute:: InlineModelAdmin.model
  993. The model in which the inline is using. This is required.
  994. .. attribute:: InlineModelAdmin.fk_name
  995. The name of the foreign key on the model. In most cases this will be dealt
  996. with automatically, but ``fk_name`` must be specified explicitly if there
  997. are more than one foreign key to the same parent model.
  998. .. attribute:: InlineModelAdmin.formset
  999. This defaults to ``BaseInlineFormSet``. Using your own formset can give you
  1000. many possibilities of customization. Inlines are built around
  1001. :ref:`model formsets <model-formsets>`.
  1002. .. attribute:: InlineModelAdmin.form
  1003. The value for ``form`` defaults to ``ModelForm``. This is what is passed
  1004. through to ``inlineformset_factory`` when creating the formset for this
  1005. inline.
  1006. .. _ref-contrib-admin-inline-extra:
  1007. .. attribute:: InlineModelAdmin.extra
  1008. This controls the number of extra forms the formset will display in
  1009. addition to the initial forms. See the
  1010. :doc:`formsets documentation </topics/forms/formsets>` for more
  1011. information.
  1012. .. versionadded:: 1.2
  1013. For users with JavaScript-enabled browsers, an "Add another" link is
  1014. provided to enable any number of additional inlines to be added in addition
  1015. to those provided as a result of the ``extra`` argument.
  1016. The dynamic link will not appear if the number of currently displayed forms
  1017. exceeds ``max_num``, or if the user does not have JavaScript enabled.
  1018. .. _ref-contrib-admin-inline-max-num:
  1019. .. attribute:: InlineModelAdmin.max_num
  1020. This controls the maximum number of forms to show in the inline. This
  1021. doesn't directly correlate to the number of objects, but can if the value
  1022. is small enough. See :ref:`model-formsets-max-num` for more information.
  1023. .. attribute:: InlineModelAdmin.raw_id_fields
  1024. By default, Django's admin uses a select-box interface (<select>) for
  1025. fields that are ``ForeignKey``. Sometimes you don't want to incur the
  1026. overhead of having to select all the related instances to display in the
  1027. drop-down.
  1028. ``raw_id_fields`` is a list of fields you would like to change into a
  1029. ``Input`` widget for either a ``ForeignKey`` or ``ManyToManyField``::
  1030. class BookInline(admin.TabularInline):
  1031. model = Book
  1032. raw_id_fields = ("pages",)
  1033. .. attribute:: InlineModelAdmin.template
  1034. The template used to render the inline on the page.
  1035. .. attribute:: InlineModelAdmin.verbose_name
  1036. An override to the ``verbose_name`` found in the model's inner ``Meta``
  1037. class.
  1038. .. attribute:: InlineModelAdmin.verbose_name_plural
  1039. An override to the ``verbose_name_plural`` found in the model's inner
  1040. ``Meta`` class.
  1041. .. attribute:: InlineModelAdmin.can_delete
  1042. Specifies whether or not inline objects can be deleted in the inline.
  1043. Defaults to ``True``.
  1044. Working with a model with two or more foreign keys to the same parent model
  1045. ---------------------------------------------------------------------------
  1046. It is sometimes possible to have more than one foreign key to the same model.
  1047. Take this model for instance::
  1048. class Friendship(models.Model):
  1049. to_person = models.ForeignKey(Person, related_name="friends")
  1050. from_person = models.ForeignKey(Person, related_name="from_friends")
  1051. If you wanted to display an inline on the ``Person`` admin add/change pages
  1052. you need to explicitly define the foreign key since it is unable to do so
  1053. automatically::
  1054. class FriendshipInline(admin.TabularInline):
  1055. model = Friendship
  1056. fk_name = "to_person"
  1057. class PersonAdmin(admin.ModelAdmin):
  1058. inlines = [
  1059. FriendshipInline,
  1060. ]
  1061. Working with many-to-many models
  1062. --------------------------------
  1063. .. versionadded:: 1.2
  1064. By default, admin widgets for many-to-many relations will be displayed
  1065. on whichever model contains the actual reference to the
  1066. :class:`~django.db.models.ManyToManyField`. Depending on your ``ModelAdmin``
  1067. definition, each many-to-many field in your model will be represented by a
  1068. standard HTML ``<select multiple>``, a horizontal or vertical filter, or a
  1069. ``raw_id_admin`` widget. However, it is also possible to replace these
  1070. widgets with inlines.
  1071. Suppose we have the following models::
  1072. class Person(models.Model):
  1073. name = models.CharField(max_length=128)
  1074. class Group(models.Model):
  1075. name = models.CharField(max_length=128)
  1076. members = models.ManyToManyField(Person, related_name='groups')
  1077. If you want to display many-to-many relations using an inline, you can do
  1078. so by defining an ``InlineModelAdmin`` object for the relationship::
  1079. class MembershipInline(admin.TabularInline):
  1080. model = Group.members.through
  1081. class PersonAdmin(admin.ModelAdmin):
  1082. inlines = [
  1083. MembershipInline,
  1084. ]
  1085. class GroupAdmin(admin.ModelAdmin):
  1086. inlines = [
  1087. MembershipInline,
  1088. ]
  1089. exclude = ('members',)
  1090. There are two features worth noting in this example.
  1091. Firstly - the ``MembershipInline`` class references ``Group.members.through``.
  1092. The ``through`` attribute is a reference to the model that manages the
  1093. many-to-many relation. This model is automatically created by Django when you
  1094. define a many-to-many field.
  1095. Secondly, the ``GroupAdmin`` must manually exclude the ``members`` field.
  1096. Django displays an admin widget for a many-to-many field on the model that
  1097. defines the relation (in this case, ``Group``). If you want to use an inline
  1098. model to represent the many-to-many relationship, you must tell Django's admin
  1099. to *not* display this widget - otherwise you will end up with two widgets on
  1100. your admin page for managing the relation.
  1101. In all other respects, the ``InlineModelAdmin`` is exactly the same as any
  1102. other. You can customize the appearance using any of the normal
  1103. ``ModelAdmin`` properties.
  1104. Working with many-to-many intermediary models
  1105. ---------------------------------------------
  1106. When you specify an intermediary model using the ``through`` argument to a
  1107. :class:`~django.db.models.ManyToManyField`, the admin will not display a
  1108. widget by default. This is because each instance of that intermediary model
  1109. requires more information than could be displayed in a single widget, and the
  1110. layout required for multiple widgets will vary depending on the intermediate
  1111. model.
  1112. However, we still want to be able to edit that information inline. Fortunately,
  1113. this is easy to do with inline admin models. Suppose we have the following
  1114. models::
  1115. class Person(models.Model):
  1116. name = models.CharField(max_length=128)
  1117. class Group(models.Model):
  1118. name = models.CharField(max_length=128)
  1119. members = models.ManyToManyField(Person, through='Membership')
  1120. class Membership(models.Model):
  1121. person = models.ForeignKey(Person)
  1122. group = models.ForeignKey(Group)
  1123. date_joined = models.DateField()
  1124. invite_reason = models.CharField(max_length=64)
  1125. The first step in displaying this intermediate model in the admin is to
  1126. define an inline class for the ``Membership`` model::
  1127. class MembershipInline(admin.TabularInline):
  1128. model = Membership
  1129. extra = 1
  1130. This simple example uses the default ``InlineModelAdmin`` values for the
  1131. ``Membership`` model, and limits the extra add forms to one. This could be
  1132. customized using any of the options available to ``InlineModelAdmin`` classes.
  1133. Now create admin views for the ``Person`` and ``Group`` models::
  1134. class PersonAdmin(admin.ModelAdmin):
  1135. inlines = (MembershipInline,)
  1136. class GroupAdmin(admin.ModelAdmin):
  1137. inlines = (MembershipInline,)
  1138. Finally, register your ``Person`` and ``Group`` models with the admin site::
  1139. admin.site.register(Person, PersonAdmin)
  1140. admin.site.register(Group, GroupAdmin)
  1141. Now your admin site is set up to edit ``Membership`` objects inline from
  1142. either the ``Person`` or the ``Group`` detail pages.
  1143. .. _using-generic-relations-as-an-inline:
  1144. Using generic relations as an inline
  1145. ------------------------------------
  1146. It is possible to use an inline with generically related objects. Let's say
  1147. you have the following models::
  1148. class Image(models.Model):
  1149. image = models.ImageField(upload_to="images")
  1150. content_type = models.ForeignKey(ContentType)
  1151. object_id = models.PositiveIntegerField()
  1152. content_object = generic.GenericForeignKey("content_type", "object_id")
  1153. class Product(models.Model):
  1154. name = models.CharField(max_length=100)
  1155. If you want to allow editing and creating ``Image`` instance on the ``Product``
  1156. add/change views you can use ``GenericTabularInline`` or
  1157. ``GenericStackedInline`` (both subclasses of ``GenericInlineModelAdmin``)
  1158. provided by ``django.contrib.contenttypes.generic``, they implement tabular and
  1159. stacked visual layouts for the forms representing the inline objects
  1160. respectively just like their non-generic counterparts and behave just like any
  1161. other inline. In your ``admin.py`` for this example app::
  1162. from django.contrib import admin
  1163. from django.contrib.contenttypes import generic
  1164. from myproject.myapp.models import Image, Product
  1165. class ImageInline(generic.GenericTabularInline):
  1166. model = Image
  1167. class ProductAdmin(admin.ModelAdmin):
  1168. inlines = [
  1169. ImageInline,
  1170. ]
  1171. admin.site.register(Product, ProductAdmin)
  1172. See the :doc:`contenttypes documentation </ref/contrib/contenttypes>` for more
  1173. specific information.
  1174. Overriding admin templates
  1175. ==========================
  1176. It is relatively easy to override many of the templates which the admin module
  1177. uses to generate the various pages of an admin site. You can even override a
  1178. few of these templates for a specific app, or a specific model.
  1179. Set up your projects admin template directories
  1180. -----------------------------------------------
  1181. The admin template files are located in the ``contrib/admin/templates/admin``
  1182. directory.
  1183. In order to override one or more of them, first create an ``admin`` directory
  1184. in your project's ``templates`` directory. This can be any of the directories
  1185. you specified in :setting:`TEMPLATE_DIRS`.
  1186. Within this ``admin`` directory, create sub-directories named after your app.
  1187. Within these app subdirectories create sub-directories named after your models.
  1188. Note, that the admin app will lowercase the model name when looking for the
  1189. directory, so make sure you name the directory in all lowercase if you are
  1190. going to run your app on a case-sensitive filesystem.
  1191. To override an admin template for a specific app, copy and edit the template
  1192. from the ``django/contrib/admin/templates/admin`` directory, and save it to one
  1193. of the directories you just created.
  1194. For example, if we wanted to add a tool to the change list view for all the
  1195. models in an app named ``my_app``, we would copy
  1196. ``contrib/admin/templates/admin/change_list.html`` to the
  1197. ``templates/admin/my_app/`` directory of our project, and make any necessary
  1198. changes.
  1199. If we wanted to add a tool to the change list view for only a specific model
  1200. named 'Page', we would copy that same file to the
  1201. ``templates/admin/my_app/page`` directory of our project.
  1202. Overriding vs. replacing an admin template
  1203. ------------------------------------------
  1204. Because of the modular design of the admin templates, it is usually neither
  1205. necessary nor advisable to replace an entire template. It is almost always
  1206. better to override only the section of the template which you need to change.
  1207. To continue the example above, we want to add a new link next to the ``History``
  1208. tool for the ``Page`` model. After looking at ``change_form.html`` we determine
  1209. that we only need to override the ``object-tools`` block. Therefore here is our
  1210. new ``change_form.html`` :
  1211. .. code-block:: html+django
  1212. {% extends "admin/change_form.html" %}
  1213. {% load i18n %}
  1214. {% block object-tools %}
  1215. {% if change %}{% if not is_popup %}
  1216. <ul class="object-tools">
  1217. <li><a href="history/" class="historylink">{% trans "History" %}</a></li>
  1218. <li><a href="mylink/" class="historylink">My Link</a></li>
  1219. {% if has_absolute_url %}
  1220. <li><a href="../../../r/{{ content_type_id }}/{{ object_id }}/" class="viewsitelink">
  1221. {% trans "View on site" %}</a>
  1222. </li>
  1223. {% endif%}
  1224. </ul>
  1225. {% endif %}{% endif %}
  1226. {% endblock %}
  1227. And that's it! If we placed this file in the ``templates/admin/my_app``
  1228. directory, our link would appear on every model's change form.
  1229. Templates which may be overridden per app or model
  1230. --------------------------------------------------
  1231. Not every template in ``contrib/admin/templates/admin`` may be overridden per
  1232. app or per model. The following can:
  1233. * ``app_index.html``
  1234. * ``change_form.html``
  1235. * ``change_list.html``
  1236. * ``delete_confirmation.html``
  1237. * ``object_history.html``
  1238. For those templates that cannot be overridden in this way, you may still
  1239. override them for your entire project. Just place the new version in your
  1240. ``templates/admin`` directory. This is particularly useful to create custom 404
  1241. and 500 pages.
  1242. .. note::
  1243. Some of the admin templates, such as ``change_list_request.html`` are used
  1244. to render custom inclusion tags. These may be overridden, but in such cases
  1245. you are probably better off creating your own version of the tag in
  1246. question and giving it a different name. That way you can use it
  1247. selectively.
  1248. Root and login templates
  1249. ------------------------
  1250. If you wish to change the index, login or logout templates, you are better off
  1251. creating your own ``AdminSite`` instance (see below), and changing the
  1252. :attr:`AdminSite.index_template` , :attr:`AdminSite.login_template` or
  1253. :attr:`AdminSite.logout_template` properties.
  1254. ``AdminSite`` objects
  1255. =====================
  1256. .. class:: AdminSite(name='admin')
  1257. A Django administrative site is represented by an instance of
  1258. ``django.contrib.admin.sites.AdminSite``; by default, an instance of
  1259. this class is created as ``django.contrib.admin.site`` and you can
  1260. register your models and ``ModelAdmin`` instances with it.
  1261. If you'd like to set up your own administrative site with custom
  1262. behavior, however, you're free to subclass ``AdminSite`` and override
  1263. or add anything you like. Then, simply create an instance of your
  1264. ``AdminSite`` subclass (the same way you'd instantiate any other
  1265. Python class), and register your models and ``ModelAdmin`` subclasses
  1266. with it instead of using the default.
  1267. When constructing an instance of an ``AdminSite``, you are able to provide
  1268. a unique instance name using the ``name`` argument to the constructor. This
  1269. instance name is used to identify the instance, especially when
  1270. :ref:`reversing admin URLs <admin-reverse-urls>`. If no instance name is
  1271. provided, a default instance name of ``admin`` will be used.
  1272. ``AdminSite`` attributes
  1273. ------------------------
  1274. Templates can override or extend base admin templates as described in
  1275. `Overriding Admin Templates`_.
  1276. .. attribute:: AdminSite.index_template
  1277. Path to a custom template that will be used by the admin site main index
  1278. view.
  1279. .. attribute:: AdminSite.login_template
  1280. Path to a custom template that will be used by the admin site login view.
  1281. .. attribute:: AdminSite.login_form
  1282. .. versionadded:: 1.3
  1283. Subclass of :class:`~django.contrib.auth.forms.AuthenticationForm` that
  1284. will be used by the admin site login view.
  1285. .. attribute:: AdminSite.logout_template
  1286. .. versionadded:: 1.2
  1287. Path to a custom template that will be used by the admin site logout view.
  1288. .. attribute:: AdminSite.password_change_template
  1289. .. versionadded:: 1.2
  1290. Path to a custom template that will be used by the admin site password
  1291. change view.
  1292. .. attribute:: AdminSite.password_change_done_template
  1293. .. versionadded:: 1.2
  1294. Path to a custom template that will be used by the admin site password
  1295. change done view.
  1296. Hooking ``AdminSite`` instances into your URLconf
  1297. -------------------------------------------------
  1298. The last step in setting up the Django admin is to hook your ``AdminSite``
  1299. instance into your URLconf. Do this by pointing a given URL at the
  1300. ``AdminSite.urls`` method.
  1301. In this example, we register the default ``AdminSite`` instance
  1302. ``django.contrib.admin.site`` at the URL ``/admin/`` ::
  1303. # urls.py
  1304. from django.conf.urls import patterns, url, include
  1305. from django.contrib import admin
  1306. admin.autodiscover()
  1307. urlpatterns = patterns('',
  1308. (r'^admin/', include(admin.site.urls)),
  1309. )
  1310. Above we used ``admin.autodiscover()`` to automatically load the
  1311. :setting:`INSTALLED_APPS` admin.py modules.
  1312. In this example, we register the ``AdminSite`` instance
  1313. ``myproject.admin.admin_site`` at the URL ``/myadmin/`` ::
  1314. # urls.py
  1315. from django.conf.urls import patterns, url, include
  1316. from myproject.admin import admin_site
  1317. urlpatterns = patterns('',
  1318. (r'^myadmin/', include(admin_site.urls)),
  1319. )
  1320. There is really no need to use autodiscover when using your own ``AdminSite``
  1321. instance since you will likely be importing all the per-app admin.py modules
  1322. in your ``myproject.admin`` module.
  1323. Multiple admin sites in the same URLconf
  1324. ----------------------------------------
  1325. It's easy to create multiple instances of the admin site on the same
  1326. Django-powered Web site. Just create multiple instances of ``AdminSite`` and
  1327. root each one at a different URL.
  1328. In this example, the URLs ``/basic-admin/`` and ``/advanced-admin/`` feature
  1329. separate versions of the admin site -- using the ``AdminSite`` instances
  1330. ``myproject.admin.basic_site`` and ``myproject.admin.advanced_site``,
  1331. respectively::
  1332. # urls.py
  1333. from django.conf.urls import patterns, url, include
  1334. from myproject.admin import basic_site, advanced_site
  1335. urlpatterns = patterns('',
  1336. (r'^basic-admin/', include(basic_site.urls)),
  1337. (r'^advanced-admin/', include(advanced_site.urls)),
  1338. )
  1339. ``AdminSite`` instances take a single argument to their constructor, their
  1340. name, which can be anything you like. This argument becomes the prefix to the
  1341. URL names for the purposes of :ref:`reversing them<admin-reverse-urls>`. This
  1342. is only necessary if you are using more than one ``AdminSite``.
  1343. Adding views to admin sites
  1344. ---------------------------
  1345. Just like :class:`ModelAdmin`, :class:`AdminSite` provides a
  1346. :meth:`~django.contrib.admin.ModelAdmin.get_urls()` method
  1347. that can be overridden to define additional views for the site. To add
  1348. a new view to your admin site, extend the base
  1349. :meth:`~django.contrib.admin.ModelAdmin.get_urls()` method to include
  1350. a pattern for your new view.
  1351. .. note::
  1352. Any view you render that uses the admin templates, or extends the base
  1353. admin template, should provide the ``current_app`` argument to
  1354. :class:`~django.template.RequestContext` or
  1355. :class:`~django.template.Context` when rendering the template. It should
  1356. be set to either ``self.name`` if your view is on an ``AdminSite`` or
  1357. ``self.admin_site.name`` if your view is on a ``ModelAdmin``.
  1358. .. _admin-reverse-urls:
  1359. Reversing admin URLs
  1360. ====================
  1361. When an :class:`AdminSite` is deployed, the views provided by that site are
  1362. accessible using Django's :ref:`URL reversing system <naming-url-patterns>`.
  1363. The :class:`AdminSite` provides the following named URL patterns:
  1364. ====================== ======================== =============
  1365. Page URL name Parameters
  1366. ====================== ======================== =============
  1367. Index ``index``
  1368. Logout ``logout``
  1369. Password change ``password_change``
  1370. Password change done ``password_change_done``
  1371. i18n javascript ``jsi18n``
  1372. Application index page ``app_list`` ``app_label``
  1373. ====================== ======================== =============
  1374. Each :class:`ModelAdmin` instance provides an additional set of named URLs:
  1375. ====================== =============================================== =============
  1376. Page URL name Parameters
  1377. ====================== =============================================== =============
  1378. Changelist ``{{ app_label }}_{{ model_name }}_changelist``
  1379. Add ``{{ app_label }}_{{ model_name }}_add``
  1380. History ``{{ app_label }}_{{ model_name }}_history`` ``object_id``
  1381. Delete ``{{ app_label }}_{{ model_name }}_delete`` ``object_id``
  1382. Change ``{{ app_label }}_{{ model_name }}_change`` ``object_id``
  1383. ====================== =============================================== =============
  1384. These named URLs are registered with the application namespace ``admin``, and
  1385. with an instance namespace corresponding to the name of the Site instance.
  1386. So - if you wanted to get a reference to the Change view for a particular
  1387. ``Choice`` object (from the polls application) in the default admin, you would
  1388. call::
  1389. >>> from django.core import urlresolvers
  1390. >>> c = Choice.objects.get(...)
  1391. >>> change_url = urlresolvers.reverse('admin:polls_choice_change', args=(c.id,))
  1392. This will find the first registered instance of the admin application
  1393. (whatever the instance name), and resolve to the view for changing
  1394. ``poll.Choice`` instances in that instance.
  1395. If you want to find a URL in a specific admin instance, provide the name of
  1396. that instance as a ``current_app`` hint to the reverse call. For example,
  1397. if you specifically wanted the admin view from the admin instance named
  1398. ``custom``, you would need to call::
  1399. >>> change_url = urlresolvers.reverse('custom:polls_choice_change', args=(c.id,))
  1400. For more details, see the documentation on :ref:`reversing namespaced URLs
  1401. <topics-http-reversing-url-namespaces>`.