index.txt 101 KB

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