index.txt 112 KB

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