index.txt 44 KB

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