index.txt 87 KB

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