index.txt 83 KB

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