index.txt 80 KB

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