index.txt 52 KB

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