index.txt 92 KB

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