index.txt 111 KB

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