1. =====================
    
  2. The Django admin site
    
  3. =====================
    
  4. 
    
  5. .. module:: django.contrib.admin
    
  6.    :synopsis: Django's admin site.
    
  7. 
    
  8. One of the most powerful parts of Django is the automatic admin interface. It
    
  9. reads metadata from your models to provide a quick, model-centric interface
    
  10. where trusted users can manage content on your site. The admin's recommended
    
  11. use is limited to an organization's internal management tool. It's not intended
    
  12. for building your entire front end around.
    
  13. 
    
  14. The admin has many hooks for customization, but beware of trying to use those
    
  15. hooks exclusively. If you need to provide a more process-centric interface
    
  16. that abstracts away the implementation details of database tables and fields,
    
  17. then it's probably time to write your own views.
    
  18. 
    
  19. In this document we discuss how to activate, use, and customize Django's admin
    
  20. interface.
    
  21. 
    
  22. Overview
    
  23. ========
    
  24. 
    
  25. The admin is enabled in the default project template used by
    
  26. :djadmin:`startproject`.
    
  27. 
    
  28. If you're not using the default project template, here are the requirements:
    
  29. 
    
  30. #. Add ``'django.contrib.admin'`` and its dependencies -
    
  31.    :mod:`django.contrib.auth`, :mod:`django.contrib.contenttypes`,
    
  32.    :mod:`django.contrib.messages`, and :mod:`django.contrib.sessions` - to your
    
  33.    :setting:`INSTALLED_APPS` setting.
    
  34. 
    
  35. #. Configure a :class:`~django.template.backends.django.DjangoTemplates`
    
  36.    backend in your :setting:`TEMPLATES` setting with
    
  37.    ``django.template.context_processors.request``,
    
  38.    ``django.contrib.auth.context_processors.auth``, and
    
  39.    ``django.contrib.messages.context_processors.messages`` in
    
  40.    the ``'context_processors'`` option of :setting:`OPTIONS
    
  41.    <TEMPLATES-OPTIONS>`.
    
  42. 
    
  43. #. If you've customized the :setting:`MIDDLEWARE` setting,
    
  44.    :class:`django.contrib.auth.middleware.AuthenticationMiddleware` and
    
  45.    :class:`django.contrib.messages.middleware.MessageMiddleware` must be
    
  46.    included.
    
  47. 
    
  48. #. :ref:`Hook the admin's URLs into your URLconf
    
  49.    <hooking-adminsite-to-urlconf>`.
    
  50. 
    
  51. After you've taken these steps, you'll be able to use the admin site by
    
  52. visiting the URL you hooked it into (``/admin/``, by default).
    
  53. 
    
  54. If you need to create a user to login with, use the :djadmin:`createsuperuser`
    
  55. command. By default, logging in to the admin requires that the user has the
    
  56. :attr:`~.User.is_staff` attribute set to ``True``.
    
  57. 
    
  58. Finally, determine which of your application's models should be editable in the
    
  59. admin interface. For each of those models, register them with the admin as
    
  60. described in :class:`ModelAdmin`.
    
  61. 
    
  62. Other topics
    
  63. ------------
    
  64. 
    
  65. .. toctree::
    
  66.    :maxdepth: 1
    
  67. 
    
  68.    actions
    
  69.    filters
    
  70.    admindocs
    
  71.    javascript
    
  72. 
    
  73. .. seealso::
    
  74. 
    
  75.     For information about serving the static files (images, JavaScript, and
    
  76.     CSS) associated with the admin in production, see :ref:`serving-files`.
    
  77. 
    
  78.     Having problems?  Try :doc:`/faq/admin`.
    
  79. 
    
  80. ``ModelAdmin`` objects
    
  81. ======================
    
  82. 
    
  83. .. class:: ModelAdmin
    
  84. 
    
  85.     The ``ModelAdmin`` class is the representation of a model in the admin
    
  86.     interface. Usually, these are stored in a file named ``admin.py`` in your
    
  87.     application. Let's take a look at an example of the ``ModelAdmin``::
    
  88. 
    
  89.         from django.contrib import admin
    
  90.         from myapp.models import Author
    
  91. 
    
  92.         class AuthorAdmin(admin.ModelAdmin):
    
  93.             pass
    
  94.         admin.site.register(Author, AuthorAdmin)
    
  95. 
    
  96.     .. admonition:: Do you need a ``ModelAdmin`` object at all?
    
  97. 
    
  98.         In the preceding example, the ``ModelAdmin`` class doesn't define any
    
  99.         custom values (yet). As a result, the default admin interface will be
    
  100.         provided. If you are happy with the default admin interface, you don't
    
  101.         need to define a ``ModelAdmin`` object at all -- you can register the
    
  102.         model class without providing a ``ModelAdmin`` description. The
    
  103.         preceding example could be simplified to::
    
  104. 
    
  105.             from django.contrib import admin
    
  106.             from myapp.models import Author
    
  107. 
    
  108.             admin.site.register(Author)
    
  109. 
    
  110. The ``register`` decorator
    
  111. --------------------------
    
  112. 
    
  113. .. function:: register(*models, site=django.contrib.admin.sites.site)
    
  114. 
    
  115.     There is also a decorator for registering your ``ModelAdmin`` classes::
    
  116. 
    
  117.         from django.contrib import admin
    
  118.         from .models import Author
    
  119. 
    
  120.         @admin.register(Author)
    
  121.         class AuthorAdmin(admin.ModelAdmin):
    
  122.             pass
    
  123. 
    
  124.     It's given one or more model classes to register with the ``ModelAdmin``.
    
  125.     If you're using a custom :class:`AdminSite`, pass it using the ``site`` keyword
    
  126.     argument::
    
  127. 
    
  128.         from django.contrib import admin
    
  129.         from .models import Author, Editor, Reader
    
  130.         from myproject.admin_site import custom_admin_site
    
  131. 
    
  132.         @admin.register(Author, Reader, Editor, site=custom_admin_site)
    
  133.         class PersonAdmin(admin.ModelAdmin):
    
  134.             pass
    
  135. 
    
  136.     You can't use this decorator if you have to reference your model admin
    
  137.     class in its ``__init__()`` method, e.g.
    
  138.     ``super(PersonAdmin, self).__init__(*args, **kwargs)``. You can use
    
  139.     ``super().__init__(*args, **kwargs)``.
    
  140. 
    
  141. Discovery of admin files
    
  142. ------------------------
    
  143. 
    
  144. When you put ``'django.contrib.admin'`` in your :setting:`INSTALLED_APPS`
    
  145. setting, Django automatically looks for an ``admin`` module in each
    
  146. application and imports it.
    
  147. 
    
  148. .. class:: apps.AdminConfig
    
  149. 
    
  150.     This is the default :class:`~django.apps.AppConfig` class for the admin.
    
  151.     It calls :func:`~django.contrib.admin.autodiscover()` when Django starts.
    
  152. 
    
  153. .. class:: apps.SimpleAdminConfig
    
  154. 
    
  155.     This class works like :class:`~django.contrib.admin.apps.AdminConfig`,
    
  156.     except it doesn't call :func:`~django.contrib.admin.autodiscover()`.
    
  157. 
    
  158.     .. attribute:: default_site
    
  159. 
    
  160.         A dotted import path to the default admin site's class or to a callable
    
  161.         that returns a site instance. Defaults to
    
  162.         ``'django.contrib.admin.sites.AdminSite'``. See
    
  163.         :ref:`overriding-default-admin-site` for usage.
    
  164. 
    
  165. .. function:: autodiscover
    
  166. 
    
  167.     This function attempts to import an ``admin`` module in each installed
    
  168.     application. Such modules are expected to register models with the admin.
    
  169. 
    
  170.     Typically you won't need to call this function directly as
    
  171.     :class:`~django.contrib.admin.apps.AdminConfig` calls it when Django starts.
    
  172. 
    
  173. If you are using a custom ``AdminSite``, it is common to import all of the
    
  174. ``ModelAdmin`` subclasses into your code and register them to the custom
    
  175. ``AdminSite``. In that case, in order to disable auto-discovery, you should
    
  176. put ``'django.contrib.admin.apps.SimpleAdminConfig'`` instead of
    
  177. ``'django.contrib.admin'`` in your :setting:`INSTALLED_APPS` setting.
    
  178. 
    
  179. ``ModelAdmin`` options
    
  180. ----------------------
    
  181. 
    
  182. The ``ModelAdmin`` is very flexible. It has several options for dealing with
    
  183. customizing the interface. All options are defined on the ``ModelAdmin``
    
  184. subclass::
    
  185. 
    
  186.     from django.contrib import admin
    
  187. 
    
  188.     class AuthorAdmin(admin.ModelAdmin):
    
  189.         date_hierarchy = 'pub_date'
    
  190. 
    
  191. .. attribute:: ModelAdmin.actions
    
  192. 
    
  193.     A list of actions to make available on the change list page. See
    
  194.     :doc:`/ref/contrib/admin/actions` for details.
    
  195. 
    
  196. .. attribute:: ModelAdmin.actions_on_top
    
  197. .. attribute:: ModelAdmin.actions_on_bottom
    
  198. 
    
  199.     Controls where on the page the actions bar appears. By default, the admin
    
  200.     changelist displays actions at the top of the page (``actions_on_top = True;
    
  201.     actions_on_bottom = False``).
    
  202. 
    
  203. .. attribute:: ModelAdmin.actions_selection_counter
    
  204. 
    
  205.     Controls whether a selection counter is displayed next to the action dropdown.
    
  206.     By default, the admin changelist will display it
    
  207.     (``actions_selection_counter = True``).
    
  208. 
    
  209. .. attribute:: ModelAdmin.date_hierarchy
    
  210. 
    
  211.     Set ``date_hierarchy`` to the name of a ``DateField`` or ``DateTimeField``
    
  212.     in your model, and the change list page will include a date-based drilldown
    
  213.     navigation by that field.
    
  214. 
    
  215.     Example::
    
  216. 
    
  217.         date_hierarchy = 'pub_date'
    
  218. 
    
  219.     You can also specify a field on a related model using the ``__`` lookup,
    
  220.     for example::
    
  221. 
    
  222.         date_hierarchy = 'author__pub_date'
    
  223. 
    
  224.     This will intelligently populate itself based on available data,
    
  225.     e.g. if all the dates are in one month, it'll show the day-level
    
  226.     drill-down only.
    
  227. 
    
  228.     .. note::
    
  229. 
    
  230.         ``date_hierarchy`` uses :meth:`QuerySet.datetimes()
    
  231.         <django.db.models.query.QuerySet.datetimes>` internally. Please refer
    
  232.         to its documentation for some caveats when time zone support is
    
  233.         enabled (:setting:`USE_TZ = True <USE_TZ>`).
    
  234. 
    
  235. .. attribute:: ModelAdmin.empty_value_display
    
  236. 
    
  237.     This attribute overrides the default display value for record's fields that
    
  238.     are empty (``None``, empty string, etc.). The default value is ``-`` (a
    
  239.     dash). For example::
    
  240. 
    
  241.         from django.contrib import admin
    
  242. 
    
  243.         class AuthorAdmin(admin.ModelAdmin):
    
  244.             empty_value_display = '-empty-'
    
  245. 
    
  246.     You can also override ``empty_value_display`` for all admin pages with
    
  247.     :attr:`AdminSite.empty_value_display`, or for specific fields like this::
    
  248. 
    
  249.         from django.contrib import admin
    
  250. 
    
  251.         class AuthorAdmin(admin.ModelAdmin):
    
  252.             list_display = ('name', 'title', 'view_birth_date')
    
  253. 
    
  254.             @admin.display(empty_value='???')
    
  255.             def view_birth_date(self, obj):
    
  256.                 return obj.birth_date
    
  257. 
    
  258. .. attribute:: ModelAdmin.exclude
    
  259. 
    
  260.     This attribute, if given, should be a list of field names to exclude from
    
  261.     the form.
    
  262. 
    
  263.     For example, let's consider the following model::
    
  264. 
    
  265.         from django.db import models
    
  266. 
    
  267.         class Author(models.Model):
    
  268.             name = models.CharField(max_length=100)
    
  269.             title = models.CharField(max_length=3)
    
  270.             birth_date = models.DateField(blank=True, null=True)
    
  271. 
    
  272.     If you want a form for the ``Author`` model that includes only the ``name``
    
  273.     and ``title`` fields, you would specify ``fields`` or ``exclude`` like
    
  274.     this::
    
  275. 
    
  276.         from django.contrib import admin
    
  277. 
    
  278.         class AuthorAdmin(admin.ModelAdmin):
    
  279.             fields = ('name', 'title')
    
  280. 
    
  281.         class AuthorAdmin(admin.ModelAdmin):
    
  282.             exclude = ('birth_date',)
    
  283. 
    
  284.     Since the Author model only has three fields, ``name``, ``title``, and
    
  285.     ``birth_date``, the forms resulting from the above declarations will
    
  286.     contain exactly the same fields.
    
  287. 
    
  288. .. attribute:: ModelAdmin.fields
    
  289. 
    
  290.     Use the ``fields`` option to make simple layout changes in the forms on
    
  291.     the "add" and "change" pages such as showing only a subset of available
    
  292.     fields, modifying their order, or grouping them into rows. For example, you
    
  293.     could define a simpler version of the admin form for the
    
  294.     :class:`django.contrib.flatpages.models.FlatPage` model as follows::
    
  295. 
    
  296.         class FlatPageAdmin(admin.ModelAdmin):
    
  297.             fields = ('url', 'title', 'content')
    
  298. 
    
  299.     In the above example, only the fields ``url``, ``title`` and ``content``
    
  300.     will be displayed, sequentially, in the form. ``fields`` can contain
    
  301.     values defined in :attr:`ModelAdmin.readonly_fields` to be displayed as
    
  302.     read-only.
    
  303. 
    
  304.     For more complex layout needs, see the :attr:`~ModelAdmin.fieldsets` option.
    
  305. 
    
  306.     The ``fields`` option accepts the same types of values as
    
  307.     :attr:`~ModelAdmin.list_display`, except that callables aren't accepted.
    
  308.     Names of model and model admin methods will only be used if they're listed
    
  309.     in :attr:`~ModelAdmin.readonly_fields`.
    
  310. 
    
  311.     To display multiple fields on the same line, wrap those fields in their own
    
  312.     tuple. In this example, the ``url`` and ``title`` fields will display on the
    
  313.     same line and the ``content`` field will be displayed below them on its
    
  314.     own line::
    
  315. 
    
  316.         class FlatPageAdmin(admin.ModelAdmin):
    
  317.             fields = (('url', 'title'), 'content')
    
  318. 
    
  319.     .. admonition:: Note
    
  320. 
    
  321.         This ``fields`` option should not be confused with the ``fields``
    
  322.         dictionary key that is within the :attr:`~ModelAdmin.fieldsets` option,
    
  323.         as described in the next section.
    
  324. 
    
  325.     If neither ``fields`` nor :attr:`~ModelAdmin.fieldsets` options are present,
    
  326.     Django will default to displaying each field that isn't an ``AutoField`` and
    
  327.     has ``editable=True``, in a single fieldset, in the same order as the fields
    
  328.     are defined in the model.
    
  329. 
    
  330. .. attribute:: ModelAdmin.fieldsets
    
  331. 
    
  332.     Set ``fieldsets`` to control the layout of admin "add" and "change" pages.
    
  333. 
    
  334.     ``fieldsets`` is a list of two-tuples, in which each two-tuple represents a
    
  335.     ``<fieldset>`` on the admin form page. (A ``<fieldset>`` is a "section" of
    
  336.     the form.)
    
  337. 
    
  338.     The two-tuples are in the format ``(name, field_options)``, where ``name``
    
  339.     is a string representing the title of the fieldset and ``field_options`` is
    
  340.     a dictionary of information about the fieldset, including a list of fields
    
  341.     to be displayed in it.
    
  342. 
    
  343.     A full example, taken from the
    
  344.     :class:`django.contrib.flatpages.models.FlatPage` model::
    
  345. 
    
  346.         from django.contrib import admin
    
  347. 
    
  348.         class FlatPageAdmin(admin.ModelAdmin):
    
  349.             fieldsets = (
    
  350.                 (None, {
    
  351.                     'fields': ('url', 'title', 'content', 'sites')
    
  352.                 }),
    
  353.                 ('Advanced options', {
    
  354.                     'classes': ('collapse',),
    
  355.                     'fields': ('registration_required', 'template_name'),
    
  356.                 }),
    
  357.             )
    
  358. 
    
  359.     This results in an admin page that looks like:
    
  360. 
    
  361.     .. image:: _images/fieldsets.png
    
  362. 
    
  363.     If neither ``fieldsets`` nor :attr:`~ModelAdmin.fields` options are present,
    
  364.     Django will default to displaying each field that isn't an ``AutoField`` and
    
  365.     has ``editable=True``, in a single fieldset, in the same order as the fields
    
  366.     are defined in the model.
    
  367. 
    
  368.     The ``field_options`` dictionary can have the following keys:
    
  369. 
    
  370.     * ``fields``
    
  371.         A tuple of field names to display in this fieldset. This key is
    
  372.         required.
    
  373. 
    
  374.         Example::
    
  375. 
    
  376.             {
    
  377.             'fields': ('first_name', 'last_name', 'address', 'city', 'state'),
    
  378.             }
    
  379. 
    
  380.         As with the :attr:`~ModelAdmin.fields` option, to display multiple
    
  381.         fields on the same line, wrap those fields in their own tuple. In this
    
  382.         example, the ``first_name`` and ``last_name`` fields will display on
    
  383.         the same line::
    
  384. 
    
  385.             {
    
  386.             'fields': (('first_name', 'last_name'), 'address', 'city', 'state'),
    
  387.             }
    
  388. 
    
  389.         ``fields`` can contain values defined in
    
  390.         :attr:`~ModelAdmin.readonly_fields` to be displayed as read-only.
    
  391. 
    
  392.         If you add the name of a callable to ``fields``, the same rule applies
    
  393.         as with the :attr:`~ModelAdmin.fields` option: the callable must be
    
  394.         listed in :attr:`~ModelAdmin.readonly_fields`.
    
  395. 
    
  396.     * ``classes``
    
  397.         A list or tuple containing extra CSS classes to apply to the fieldset.
    
  398. 
    
  399.         Example::
    
  400. 
    
  401.             {
    
  402.             'classes': ('wide', 'extrapretty'),
    
  403.             }
    
  404. 
    
  405.         Two useful classes defined by the default admin site stylesheet are
    
  406.         ``collapse`` and ``wide``. Fieldsets with the ``collapse`` style
    
  407.         will be initially collapsed in the admin and replaced with a small
    
  408.         "click to expand" link. Fieldsets with the ``wide`` style will be
    
  409.         given extra horizontal space.
    
  410. 
    
  411.     * ``description``
    
  412.         A string of optional extra text to be displayed at the top of each
    
  413.         fieldset, under the heading of the fieldset. This string is not
    
  414.         rendered for :class:`~django.contrib.admin.TabularInline` due to its
    
  415.         layout.
    
  416. 
    
  417.         Note that this value is *not* HTML-escaped when it's displayed in
    
  418.         the admin interface. This lets you include HTML if you so desire.
    
  419.         Alternatively you can use plain text and
    
  420.         :func:`django.utils.html.escape` to escape any HTML special
    
  421.         characters.
    
  422. 
    
  423. .. attribute:: ModelAdmin.filter_horizontal
    
  424. 
    
  425.     By default, a :class:`~django.db.models.ManyToManyField` is displayed in
    
  426.     the admin site with a ``<select multiple>``. However, multiple-select boxes
    
  427.     can be difficult to use when selecting many items. Adding a
    
  428.     :class:`~django.db.models.ManyToManyField` to this list will instead use
    
  429.     a nifty unobtrusive JavaScript "filter" interface that allows searching
    
  430.     within the options. The unselected and selected options appear in two boxes
    
  431.     side by side. See :attr:`~ModelAdmin.filter_vertical` to use a vertical
    
  432.     interface.
    
  433. 
    
  434. .. attribute:: ModelAdmin.filter_vertical
    
  435. 
    
  436.     Same as :attr:`~ModelAdmin.filter_horizontal`, but uses a vertical display
    
  437.     of the filter interface with the box of unselected options appearing above
    
  438.     the box of selected options.
    
  439. 
    
  440. .. attribute:: ModelAdmin.form
    
  441. 
    
  442.     By default a ``ModelForm`` is dynamically created for your model. It is
    
  443.     used to create the form presented on both the add/change pages. You can
    
  444.     easily provide your own ``ModelForm`` to override any default form behavior
    
  445.     on the add/change pages. Alternatively, you can customize the default
    
  446.     form rather than specifying an entirely new one by using the
    
  447.     :meth:`ModelAdmin.get_form` method.
    
  448. 
    
  449.     For an example see the section :ref:`admin-custom-validation`.
    
  450. 
    
  451.     .. admonition:: Note
    
  452. 
    
  453.         If you define the ``Meta.model`` attribute on a
    
  454.         :class:`~django.forms.ModelForm`, you must also define the
    
  455.         ``Meta.fields`` attribute (or the ``Meta.exclude`` attribute). However,
    
  456.         since the admin has its own way of defining fields, the ``Meta.fields``
    
  457.         attribute will be ignored.
    
  458. 
    
  459.         If the ``ModelForm`` is only going to be used for the admin, the easiest
    
  460.         solution is to omit the ``Meta.model`` attribute, since ``ModelAdmin``
    
  461.         will provide the correct model to use. Alternatively, you can set
    
  462.         ``fields = []`` in the ``Meta`` class to satisfy the validation on the
    
  463.         ``ModelForm``.
    
  464. 
    
  465.     .. admonition:: Note
    
  466. 
    
  467.         If your ``ModelForm`` and ``ModelAdmin`` both define an ``exclude``
    
  468.         option then ``ModelAdmin`` takes precedence::
    
  469. 
    
  470.             from django import forms
    
  471.             from django.contrib import admin
    
  472.             from myapp.models import Person
    
  473. 
    
  474.             class PersonForm(forms.ModelForm):
    
  475. 
    
  476.                 class Meta:
    
  477.                     model = Person
    
  478.                     exclude = ['name']
    
  479. 
    
  480.             class PersonAdmin(admin.ModelAdmin):
    
  481.                 exclude = ['age']
    
  482.                 form = PersonForm
    
  483. 
    
  484.         In the above example, the "age" field will be excluded but the "name"
    
  485.         field will be included in the generated form.
    
  486. 
    
  487. .. attribute:: ModelAdmin.formfield_overrides
    
  488. 
    
  489.     This provides a quick-and-dirty way to override some of the
    
  490.     :class:`~django.forms.Field` options for use in the admin.
    
  491.     ``formfield_overrides`` is a dictionary mapping a field class to a dict of
    
  492.     arguments to pass to the field at construction time.
    
  493. 
    
  494.     Since that's a bit abstract, let's look at a concrete example. The most
    
  495.     common use of ``formfield_overrides`` is to add a custom widget for a
    
  496.     certain type of field. So, imagine we've written a ``RichTextEditorWidget``
    
  497.     that we'd like to use for large text fields instead of the default
    
  498.     ``<textarea>``. Here's how we'd do that::
    
  499. 
    
  500.         from django.contrib import admin
    
  501.         from django.db import models
    
  502. 
    
  503.         # Import our custom widget and our model from where they're defined
    
  504.         from myapp.models import MyModel
    
  505.         from myapp.widgets import RichTextEditorWidget
    
  506. 
    
  507.         class MyModelAdmin(admin.ModelAdmin):
    
  508.             formfield_overrides = {
    
  509.                 models.TextField: {'widget': RichTextEditorWidget},
    
  510.             }
    
  511. 
    
  512.     Note that the key in the dictionary is the actual field class, *not* a
    
  513.     string. The value is another dictionary; these arguments will be passed to
    
  514.     the form field's ``__init__()`` method. See :doc:`/ref/forms/api` for
    
  515.     details.
    
  516. 
    
  517.     .. warning::
    
  518. 
    
  519.         If you want to use a custom widget with a relation field (i.e.
    
  520.         :class:`~django.db.models.ForeignKey` or
    
  521.         :class:`~django.db.models.ManyToManyField`), make sure you haven't
    
  522.         included that field's name in ``raw_id_fields``, ``radio_fields``, or
    
  523.         ``autocomplete_fields``.
    
  524. 
    
  525.         ``formfield_overrides`` won't let you change the widget on relation
    
  526.         fields that have ``raw_id_fields``, ``radio_fields``, or
    
  527.         ``autocomplete_fields`` set. That's because ``raw_id_fields``,
    
  528.         ``radio_fields``, and ``autocomplete_fields`` imply custom widgets of
    
  529.         their own.
    
  530. 
    
  531. .. attribute:: ModelAdmin.inlines
    
  532. 
    
  533.     See :class:`InlineModelAdmin` objects below as well as
    
  534.     :meth:`ModelAdmin.get_formsets_with_inlines`.
    
  535. 
    
  536. .. attribute:: ModelAdmin.list_display
    
  537. 
    
  538.     Set ``list_display`` to control which fields are displayed on the change
    
  539.     list page of the admin.
    
  540. 
    
  541.     Example::
    
  542. 
    
  543.         list_display = ('first_name', 'last_name')
    
  544. 
    
  545.     If you don't set ``list_display``, the admin site will display a single
    
  546.     column that displays the ``__str__()`` representation of each object.
    
  547. 
    
  548.     There are four types of values that can be used in ``list_display``. All
    
  549.     but the simplest may use the  :func:`~django.contrib.admin.display`
    
  550.     decorator, which is used to customize how the field is presented:
    
  551. 
    
  552.     * The name of a model field. For example::
    
  553. 
    
  554.           class PersonAdmin(admin.ModelAdmin):
    
  555.               list_display = ('first_name', 'last_name')
    
  556. 
    
  557.     * A callable that accepts one argument, the model instance. For example::
    
  558. 
    
  559.           @admin.display(description='Name')
    
  560.           def upper_case_name(obj):
    
  561.               return ("%s %s" % (obj.first_name, obj.last_name)).upper()
    
  562. 
    
  563.           class PersonAdmin(admin.ModelAdmin):
    
  564.               list_display = (upper_case_name,)
    
  565. 
    
  566.     * A string representing a ``ModelAdmin`` method that accepts one argument,
    
  567.       the model instance. For example::
    
  568. 
    
  569.           class PersonAdmin(admin.ModelAdmin):
    
  570.               list_display = ('upper_case_name',)
    
  571. 
    
  572.               @admin.display(description='Name')
    
  573.               def upper_case_name(self, obj):
    
  574.                   return ("%s %s" % (obj.first_name, obj.last_name)).upper()
    
  575. 
    
  576.     * A string representing a model attribute or method (without any required
    
  577.       arguments). For example::
    
  578. 
    
  579.           from django.contrib import admin
    
  580.           from django.db import models
    
  581. 
    
  582.           class Person(models.Model):
    
  583.               name = models.CharField(max_length=50)
    
  584.               birthday = models.DateField()
    
  585. 
    
  586.               @admin.display(description='Birth decade')
    
  587.               def decade_born_in(self):
    
  588.                   return '%d’s' % (self.birthday.year // 10 * 10)
    
  589. 
    
  590.           class PersonAdmin(admin.ModelAdmin):
    
  591.               list_display = ('name', 'decade_born_in')
    
  592. 
    
  593.     A few special cases to note about ``list_display``:
    
  594. 
    
  595.     * If the field is a ``ForeignKey``, Django will display the
    
  596.       ``__str__()`` of the related object.
    
  597. 
    
  598.     * ``ManyToManyField`` fields aren't supported, because that would
    
  599.       entail executing a separate SQL statement for each row in the table.
    
  600.       If you want to do this nonetheless, give your model a custom method,
    
  601.       and add that method's name to ``list_display``. (See below for more
    
  602.       on custom methods in ``list_display``.)
    
  603. 
    
  604.     * If the field is a ``BooleanField``, Django will display a pretty "yes",
    
  605.       "no", or "unknown" icon instead of ``True``, ``False``, or ``None``.
    
  606. 
    
  607.     * If the string given is a method of the model, ``ModelAdmin`` or a
    
  608.       callable, Django will HTML-escape the output by default. To escape
    
  609.       user input and allow your own unescaped tags, use
    
  610.       :func:`~django.utils.html.format_html`.
    
  611. 
    
  612.       Here's a full example model::
    
  613. 
    
  614.           from django.contrib import admin
    
  615.           from django.db import models
    
  616.           from django.utils.html import format_html
    
  617. 
    
  618.           class Person(models.Model):
    
  619.               first_name = models.CharField(max_length=50)
    
  620.               last_name = models.CharField(max_length=50)
    
  621.               color_code = models.CharField(max_length=6)
    
  622. 
    
  623.               @admin.display
    
  624.               def colored_name(self):
    
  625.                   return format_html(
    
  626.                       '<span style="color: #{};">{} {}</span>',
    
  627.                       self.color_code,
    
  628.                       self.first_name,
    
  629.                       self.last_name,
    
  630.                   )
    
  631. 
    
  632.           class PersonAdmin(admin.ModelAdmin):
    
  633.               list_display = ('first_name', 'last_name', 'colored_name')
    
  634. 
    
  635.     * As some examples have already demonstrated, when using a callable, a
    
  636.       model method, or a ``ModelAdmin`` method, you can customize the column's
    
  637.       title by wrapping the callable with the
    
  638.       :func:`~django.contrib.admin.display` decorator and passing the
    
  639.       ``description`` argument.
    
  640. 
    
  641.     * If the value of a field is ``None``, an empty string, or an iterable
    
  642.       without elements, Django will display ``-`` (a dash). You can override
    
  643.       this with :attr:`AdminSite.empty_value_display`::
    
  644. 
    
  645.           from django.contrib import admin
    
  646. 
    
  647.           admin.site.empty_value_display = '(None)'
    
  648. 
    
  649.       You can also use :attr:`ModelAdmin.empty_value_display`::
    
  650. 
    
  651.           class PersonAdmin(admin.ModelAdmin):
    
  652.               empty_value_display = 'unknown'
    
  653. 
    
  654.       Or on a field level::
    
  655. 
    
  656.           class PersonAdmin(admin.ModelAdmin):
    
  657.               list_display = ('name', 'birth_date_view')
    
  658. 
    
  659.               @admin.display(empty_value='unknown')
    
  660.               def birth_date_view(self, obj):
    
  661.                    return obj.birth_date
    
  662. 
    
  663.     * If the string given is a method of the model, ``ModelAdmin`` or a
    
  664.       callable that returns ``True``, ``False``, or ``None``, Django will
    
  665.       display a pretty "yes", "no", or "unknown" icon if you wrap the method
    
  666.       with the :func:`~django.contrib.admin.display` decorator passing the
    
  667.       ``boolean`` argument with the value set to ``True``::
    
  668. 
    
  669.           from django.contrib import admin
    
  670.           from django.db import models
    
  671. 
    
  672.           class Person(models.Model):
    
  673.               first_name = models.CharField(max_length=50)
    
  674.               birthday = models.DateField()
    
  675. 
    
  676.               @admin.display(boolean=True)
    
  677.               def born_in_fifties(self):
    
  678.                   return 1950 <= self.birthday.year < 1960
    
  679. 
    
  680.           class PersonAdmin(admin.ModelAdmin):
    
  681.               list_display = ('name', 'born_in_fifties')
    
  682. 
    
  683.     * The ``__str__()`` method is just as valid in ``list_display`` as any
    
  684.       other model method, so it's perfectly OK to do this::
    
  685. 
    
  686.           list_display = ('__str__', 'some_other_field')
    
  687. 
    
  688.     * Usually, elements of ``list_display`` that aren't actual database
    
  689.       fields can't be used in sorting (because Django does all the sorting
    
  690.       at the database level).
    
  691. 
    
  692.       However, if an element of ``list_display`` represents a certain database
    
  693.       field, you can indicate this fact by using the
    
  694.       :func:`~django.contrib.admin.display` decorator on the method, passing
    
  695.       the ``ordering`` argument::
    
  696. 
    
  697.           from django.contrib import admin
    
  698.           from django.db import models
    
  699.           from django.utils.html import format_html
    
  700. 
    
  701.           class Person(models.Model):
    
  702.               first_name = models.CharField(max_length=50)
    
  703.               color_code = models.CharField(max_length=6)
    
  704. 
    
  705.               @admin.display(ordering='first_name')
    
  706.               def colored_first_name(self):
    
  707.                   return format_html(
    
  708.                       '<span style="color: #{};">{}</span>',
    
  709.                       self.color_code,
    
  710.                       self.first_name,
    
  711.                   )
    
  712. 
    
  713.           class PersonAdmin(admin.ModelAdmin):
    
  714.               list_display = ('first_name', 'colored_first_name')
    
  715. 
    
  716.       The above will tell Django to order by the ``first_name`` field when
    
  717.       trying to sort by ``colored_first_name`` in the admin.
    
  718. 
    
  719.       To indicate descending order with the ``ordering`` argument you can use a
    
  720.       hyphen prefix on the field name. Using the above example, this would look
    
  721.       like::
    
  722. 
    
  723.           @admin.display(ordering='-first_name')
    
  724. 
    
  725.       The ``ordering`` argument supports query lookups to sort by values on
    
  726.       related models. This example includes an "author first name" column in
    
  727.       the list display and allows sorting it by first name::
    
  728. 
    
  729.           class Blog(models.Model):
    
  730.               title = models.CharField(max_length=255)
    
  731.               author = models.ForeignKey(Person, on_delete=models.CASCADE)
    
  732. 
    
  733.           class BlogAdmin(admin.ModelAdmin):
    
  734.               list_display = ('title', 'author', 'author_first_name')
    
  735. 
    
  736.               @admin.display(ordering='author__first_name')
    
  737.               def author_first_name(self, obj):
    
  738.                   return obj.author.first_name
    
  739. 
    
  740.       :doc:`Query expressions </ref/models/expressions>` may be used with the
    
  741.       ``ordering`` argument::
    
  742. 
    
  743.           from django.db.models import Value
    
  744.           from django.db.models.functions import Concat
    
  745. 
    
  746.           class Person(models.Model):
    
  747.               first_name = models.CharField(max_length=50)
    
  748.               last_name = models.CharField(max_length=50)
    
  749. 
    
  750.               @admin.display(ordering=Concat('first_name', Value(' '), 'last_name'))
    
  751.               def full_name(self):
    
  752.                   return self.first_name + ' ' + self.last_name
    
  753. 
    
  754.     * Elements of ``list_display`` can also be properties::
    
  755. 
    
  756.           class Person(models.Model):
    
  757.               first_name = models.CharField(max_length=50)
    
  758.               last_name = models.CharField(max_length=50)
    
  759. 
    
  760.               @property
    
  761.               @admin.display(
    
  762.                   ordering='last_name',
    
  763.                   description='Full name of the person',
    
  764.               )
    
  765.               def full_name(self):
    
  766.                   return self.first_name + ' ' + self.last_name
    
  767. 
    
  768.           class PersonAdmin(admin.ModelAdmin):
    
  769.               list_display = ('full_name',)
    
  770. 
    
  771.       Note that ``@property`` must be above ``@display``. If you're using the
    
  772.       old way -- setting the display-related attributes directly rather than
    
  773.       using the :func:`~django.contrib.admin.display` decorator --  be aware
    
  774.       that the ``property()`` function and **not** the ``@property`` decorator
    
  775.       must be used::
    
  776. 
    
  777.           def my_property(self):
    
  778.               return self.first_name + ' ' + self.last_name
    
  779.           my_property.short_description = "Full name of the person"
    
  780.           my_property.admin_order_field = 'last_name'
    
  781. 
    
  782.           full_name = property(my_property)
    
  783. 
    
  784.     * The field names in ``list_display`` will also appear as CSS classes in
    
  785.       the HTML output, in the form of ``column-<field_name>`` on each ``<th>``
    
  786.       element. This can be used to set column widths in a CSS file for example.
    
  787. 
    
  788.     * Django will try to interpret every element of ``list_display`` in this
    
  789.       order:
    
  790. 
    
  791.       * A field of the model.
    
  792.       * A callable.
    
  793.       * A string representing a ``ModelAdmin`` attribute.
    
  794.       * A string representing a model attribute.
    
  795. 
    
  796.       For example if you have ``first_name`` as a model field and
    
  797.       as a ``ModelAdmin`` attribute, the model field will be used.
    
  798. 
    
  799. 
    
  800. .. attribute:: ModelAdmin.list_display_links
    
  801. 
    
  802.     Use ``list_display_links`` to control if and which fields in
    
  803.     :attr:`list_display` should be linked to the "change" page for an object.
    
  804. 
    
  805.     By default, the change list page will link the first column -- the first
    
  806.     field specified in ``list_display`` -- to the change page for each item.
    
  807.     But ``list_display_links`` lets you change this:
    
  808. 
    
  809.     * Set it to ``None`` to get no links at all.
    
  810.     * Set it to a list or tuple of fields (in the same format as
    
  811.       ``list_display``) whose columns you want converted to links.
    
  812. 
    
  813.       You can specify one or many fields. As long as the fields appear in
    
  814.       ``list_display``, Django doesn't care how many (or how few) fields are
    
  815.       linked. The only requirement is that if you want to use
    
  816.       ``list_display_links`` in this fashion, you must define ``list_display``.
    
  817. 
    
  818.     In this example, the ``first_name`` and ``last_name`` fields will be
    
  819.     linked on the change list page::
    
  820. 
    
  821.         class PersonAdmin(admin.ModelAdmin):
    
  822.             list_display = ('first_name', 'last_name', 'birthday')
    
  823.             list_display_links = ('first_name', 'last_name')
    
  824. 
    
  825.     In this example, the change list page grid will have no links::
    
  826. 
    
  827.         class AuditEntryAdmin(admin.ModelAdmin):
    
  828.             list_display = ('timestamp', 'message')
    
  829.             list_display_links = None
    
  830. 
    
  831. .. _admin-list-editable:
    
  832. 
    
  833. .. attribute:: ModelAdmin.list_editable
    
  834. 
    
  835.     Set ``list_editable`` to a list of field names on the model which will
    
  836.     allow editing on the change list page. That is, fields listed in
    
  837.     ``list_editable`` will be displayed as form widgets on the change list
    
  838.     page, allowing users to edit and save multiple rows at once.
    
  839. 
    
  840.     .. note::
    
  841. 
    
  842.         ``list_editable`` interacts with a couple of other options in
    
  843.         particular ways; you should note the following rules:
    
  844. 
    
  845.         * Any field in ``list_editable`` must also be in ``list_display``.
    
  846.           You can't edit a field that's not displayed!
    
  847. 
    
  848.         * The same field can't be listed in both ``list_editable`` and
    
  849.           ``list_display_links`` -- a field can't be both a form and
    
  850.           a link.
    
  851. 
    
  852.         You'll get a validation error if either of these rules are broken.
    
  853. 
    
  854. .. attribute:: ModelAdmin.list_filter
    
  855. 
    
  856.     Set ``list_filter`` to activate filters in the right sidebar of the change
    
  857.     list page of the admin.
    
  858. 
    
  859.     At it's simplest ``list_filter`` takes a list or tuple of field names to
    
  860.     activate filtering upon, but several more advanced options as available.
    
  861.     See :ref:`modeladmin-list-filters` for the details.
    
  862. 
    
  863. .. attribute:: ModelAdmin.list_max_show_all
    
  864. 
    
  865.     Set ``list_max_show_all`` to control how many items can appear on a "Show
    
  866.     all" admin change list page. The admin will display a "Show all" link on the
    
  867.     change list only if the total result count is less than or equal to this
    
  868.     setting. By default, this is set to ``200``.
    
  869. 
    
  870. .. attribute:: ModelAdmin.list_per_page
    
  871. 
    
  872.     Set ``list_per_page`` to control how many items appear on each paginated
    
  873.     admin change list page. By default, this is set to ``100``.
    
  874. 
    
  875. .. attribute:: ModelAdmin.list_select_related
    
  876. 
    
  877.     Set ``list_select_related`` to tell Django to use
    
  878.     :meth:`~django.db.models.query.QuerySet.select_related` in retrieving
    
  879.     the list of objects on the admin change list page. This can save you a
    
  880.     bunch of database queries.
    
  881. 
    
  882.     The value should be either a boolean, a list or a tuple. Default is
    
  883.     ``False``.
    
  884. 
    
  885.     When value is ``True``, ``select_related()`` will always be called. When
    
  886.     value is set to ``False``, Django will look at ``list_display`` and call
    
  887.     ``select_related()`` if any ``ForeignKey`` is present.
    
  888. 
    
  889.     If you need more fine-grained control, use a tuple (or list) as value for
    
  890.     ``list_select_related``. Empty tuple will prevent Django from calling
    
  891.     ``select_related`` at all. Any other tuple will be passed directly to
    
  892.     ``select_related`` as parameters. For example::
    
  893. 
    
  894.         class ArticleAdmin(admin.ModelAdmin):
    
  895.             list_select_related = ('author', 'category')
    
  896. 
    
  897.     will call ``select_related('author', 'category')``.
    
  898. 
    
  899.     If you need to specify a dynamic value based on the request, you can
    
  900.     implement a :meth:`~ModelAdmin.get_list_select_related` method.
    
  901. 
    
  902.     .. note::
    
  903. 
    
  904.         ``ModelAdmin`` ignores this attribute when
    
  905.         :meth:`~django.db.models.query.QuerySet.select_related` was already
    
  906.         called on the changelist's ``QuerySet``.
    
  907. 
    
  908. .. attribute:: ModelAdmin.ordering
    
  909. 
    
  910.     Set ``ordering`` to specify how lists of objects should be ordered in the
    
  911.     Django admin views. This should be a list or tuple in the same format as a
    
  912.     model's :attr:`~django.db.models.Options.ordering` parameter.
    
  913. 
    
  914.     If this isn't provided, the Django admin will use the model's default
    
  915.     ordering.
    
  916. 
    
  917.     If you need to specify a dynamic order (for example depending on user or
    
  918.     language) you can implement a :meth:`~ModelAdmin.get_ordering` method.
    
  919. 
    
  920.     .. admonition:: Performance considerations with ordering and sorting
    
  921. 
    
  922.         To ensure a deterministic ordering of results, the changelist adds
    
  923.         ``pk`` to the ordering if it can't find a single or unique together set
    
  924.         of fields that provide total ordering.
    
  925. 
    
  926.         For example, if the default ordering is by a non-unique ``name`` field,
    
  927.         then the changelist is sorted by ``name`` and ``pk``. This could
    
  928.         perform poorly if you have a lot of rows and don't have an index on
    
  929.         ``name`` and ``pk``.
    
  930. 
    
  931. .. attribute:: ModelAdmin.paginator
    
  932. 
    
  933.     The paginator class to be used for pagination. By default,
    
  934.     :class:`django.core.paginator.Paginator` is used. If the custom paginator
    
  935.     class doesn't have the same constructor interface as
    
  936.     :class:`django.core.paginator.Paginator`, you will also need to
    
  937.     provide an implementation for :meth:`ModelAdmin.get_paginator`.
    
  938. 
    
  939. .. attribute:: ModelAdmin.prepopulated_fields
    
  940. 
    
  941.     Set ``prepopulated_fields`` to a dictionary mapping field names to the
    
  942.     fields it should prepopulate from::
    
  943. 
    
  944.         class ArticleAdmin(admin.ModelAdmin):
    
  945.             prepopulated_fields = {"slug": ("title",)}
    
  946. 
    
  947.     When set, the given fields will use a bit of JavaScript to populate from
    
  948.     the fields assigned. The main use for this functionality is to
    
  949.     automatically generate the value for ``SlugField`` fields from one or more
    
  950.     other fields. The generated value is produced by concatenating the values
    
  951.     of the source fields, and then by transforming that result into a valid
    
  952.     slug (e.g. substituting dashes for spaces and lowercasing ASCII letters).
    
  953. 
    
  954.     Prepopulated fields aren't modified by JavaScript after a value has been
    
  955.     saved. It's usually undesired that slugs change (which would cause an
    
  956.     object's URL to change if the slug is used in it).
    
  957. 
    
  958.     ``prepopulated_fields`` doesn't accept ``DateTimeField``, ``ForeignKey``,
    
  959.     ``OneToOneField``, and ``ManyToManyField`` fields.
    
  960. 
    
  961. .. attribute:: ModelAdmin.preserve_filters
    
  962. 
    
  963.     By default, applied filters are preserved on the list view after creating,
    
  964.     editing, or deleting an object. You can have filters cleared by setting
    
  965.     this attribute to ``False``.
    
  966. 
    
  967. .. attribute:: ModelAdmin.radio_fields
    
  968. 
    
  969.     By default, Django's admin uses a select-box interface (<select>) for
    
  970.     fields that are ``ForeignKey`` or have ``choices`` set. If a field is
    
  971.     present in ``radio_fields``, Django will use a radio-button interface
    
  972.     instead. Assuming ``group`` is a ``ForeignKey`` on the ``Person`` model::
    
  973. 
    
  974.         class PersonAdmin(admin.ModelAdmin):
    
  975.             radio_fields = {"group": admin.VERTICAL}
    
  976. 
    
  977.     You have the choice of using ``HORIZONTAL`` or ``VERTICAL`` from the
    
  978.     ``django.contrib.admin`` module.
    
  979. 
    
  980.     Don't include a field in ``radio_fields`` unless it's a ``ForeignKey`` or has
    
  981.     ``choices`` set.
    
  982. 
    
  983. .. attribute:: ModelAdmin.autocomplete_fields
    
  984. 
    
  985.     ``autocomplete_fields`` is a list of ``ForeignKey`` and/or
    
  986.     ``ManyToManyField`` fields you would like to change to `Select2
    
  987.     <https://select2.org/>`_ autocomplete inputs.
    
  988. 
    
  989.     By default, the admin uses a select-box interface (``<select>``) for
    
  990.     those fields. Sometimes you don't want to incur the overhead of selecting
    
  991.     all the related instances to display in the dropdown.
    
  992. 
    
  993.     The Select2 input looks similar to the default input but comes with a
    
  994.     search feature that loads the options asynchronously. This is faster and
    
  995.     more user-friendly if the related model has many instances.
    
  996. 
    
  997.     You must define :attr:`~ModelAdmin.search_fields` on the related object's
    
  998.     ``ModelAdmin`` because the autocomplete search uses it.
    
  999. 
    
  1000.     To avoid unauthorized data disclosure, users must have the ``view`` or
    
  1001.     ``change`` permission to the related object in order to use autocomplete.
    
  1002. 
    
  1003.     Ordering and pagination of the results are controlled by the related
    
  1004.     ``ModelAdmin``'s :meth:`~ModelAdmin.get_ordering` and
    
  1005.     :meth:`~ModelAdmin.get_paginator` methods.
    
  1006. 
    
  1007.     In the following example, ``ChoiceAdmin`` has an autocomplete field for the
    
  1008.     ``ForeignKey`` to the ``Question``. The results are filtered by the
    
  1009.     ``question_text`` field and ordered by the ``date_created`` field::
    
  1010. 
    
  1011.         class QuestionAdmin(admin.ModelAdmin):
    
  1012.             ordering = ['date_created']
    
  1013.             search_fields = ['question_text']
    
  1014. 
    
  1015.         class ChoiceAdmin(admin.ModelAdmin):
    
  1016.             autocomplete_fields = ['question']
    
  1017. 
    
  1018.     .. admonition:: Performance considerations for large datasets
    
  1019. 
    
  1020.         Ordering using :attr:`ModelAdmin.ordering` may cause performance
    
  1021.         problems as sorting on a large queryset will be slow.
    
  1022. 
    
  1023.         Also, if your search fields include fields that aren't indexed by the
    
  1024.         database, you might encounter poor performance on extremely large
    
  1025.         tables.
    
  1026. 
    
  1027.         For those cases, it's a good idea to write your own
    
  1028.         :func:`ModelAdmin.get_search_results` implementation using a
    
  1029.         full-text indexed search.
    
  1030. 
    
  1031.         You may also want to change the ``Paginator`` on very large tables
    
  1032.         as the default paginator always performs a ``count()`` query.
    
  1033.         For example, you could override the default implementation of the
    
  1034.         ``Paginator.count`` property.
    
  1035. 
    
  1036. .. attribute:: ModelAdmin.raw_id_fields
    
  1037. 
    
  1038.     By default, Django's admin uses a select-box interface (<select>) for
    
  1039.     fields that are ``ForeignKey``. Sometimes you don't want to incur the
    
  1040.     overhead of having to select all the related instances to display in the
    
  1041.     drop-down.
    
  1042. 
    
  1043.     ``raw_id_fields`` is a list of fields you would like to change
    
  1044.     into an ``Input`` widget for either a ``ForeignKey`` or
    
  1045.     ``ManyToManyField``::
    
  1046. 
    
  1047.         class ArticleAdmin(admin.ModelAdmin):
    
  1048.             raw_id_fields = ("newspaper",)
    
  1049. 
    
  1050.     The ``raw_id_fields`` ``Input`` widget should contain a primary key if the
    
  1051.     field is a ``ForeignKey`` or a comma separated list of values if the field
    
  1052.     is a ``ManyToManyField``.  The ``raw_id_fields`` widget shows a magnifying
    
  1053.     glass button next to the field which allows users to search for and select
    
  1054.     a value:
    
  1055. 
    
  1056.     .. image:: _images/raw_id_fields.png
    
  1057. 
    
  1058. .. attribute:: ModelAdmin.readonly_fields
    
  1059. 
    
  1060.     By default the admin shows all fields as editable. Any fields in this
    
  1061.     option (which should be a ``list`` or ``tuple``) will display its data
    
  1062.     as-is and non-editable; they are also excluded from the
    
  1063.     :class:`~django.forms.ModelForm` used for creating and editing. Note that
    
  1064.     when specifying :attr:`ModelAdmin.fields` or :attr:`ModelAdmin.fieldsets`
    
  1065.     the read-only fields must be present to be shown (they are ignored
    
  1066.     otherwise).
    
  1067. 
    
  1068.     If ``readonly_fields`` is used without defining explicit ordering through
    
  1069.     :attr:`ModelAdmin.fields` or :attr:`ModelAdmin.fieldsets` they will be
    
  1070.     added last after all editable fields.
    
  1071. 
    
  1072.     A read-only field can not only display data from a model's field, it can
    
  1073.     also display the output of a model's method or a method of the
    
  1074.     ``ModelAdmin`` class itself. This is very similar to the way
    
  1075.     :attr:`ModelAdmin.list_display` behaves. This provides a way to use the
    
  1076.     admin interface to provide feedback on the status of the objects being
    
  1077.     edited, for example::
    
  1078. 
    
  1079.         from django.contrib import admin
    
  1080.         from django.utils.html import format_html_join
    
  1081.         from django.utils.safestring import mark_safe
    
  1082. 
    
  1083.         class PersonAdmin(admin.ModelAdmin):
    
  1084.             readonly_fields = ('address_report',)
    
  1085. 
    
  1086.             # description functions like a model field's verbose_name
    
  1087.             @admin.display(description='Address')
    
  1088.             def address_report(self, instance):
    
  1089.                 # assuming get_full_address() returns a list of strings
    
  1090.                 # for each line of the address and you want to separate each
    
  1091.                 # line by a linebreak
    
  1092.                 return format_html_join(
    
  1093.                     mark_safe('<br>'),
    
  1094.                     '{}',
    
  1095.                     ((line,) for line in instance.get_full_address()),
    
  1096.                 ) or mark_safe("<span class='errors'>I can't determine this address.</span>")
    
  1097. 
    
  1098. .. attribute:: ModelAdmin.save_as
    
  1099. 
    
  1100.     Set ``save_as`` to enable a "save as new" feature on admin change forms.
    
  1101. 
    
  1102.     Normally, objects have three save options: "Save", "Save and continue
    
  1103.     editing", and "Save and add another". If ``save_as`` is ``True``, "Save
    
  1104.     and add another" will be replaced by a "Save as new" button that creates a
    
  1105.     new object (with a new ID) rather than updating the existing object.
    
  1106. 
    
  1107.     By default, ``save_as`` is set to ``False``.
    
  1108. 
    
  1109. .. attribute:: ModelAdmin.save_as_continue
    
  1110. 
    
  1111.     When :attr:`save_as=True <save_as>`, the default redirect after saving the
    
  1112.     new object is to the change view for that object. If you set
    
  1113.     ``save_as_continue=False``, the redirect will be to the changelist view.
    
  1114. 
    
  1115.     By default, ``save_as_continue`` is set to ``True``.
    
  1116. 
    
  1117. .. attribute:: ModelAdmin.save_on_top
    
  1118. 
    
  1119.     Set ``save_on_top`` to add save buttons across the top of your admin change
    
  1120.     forms.
    
  1121. 
    
  1122.     Normally, the save buttons appear only at the bottom of the forms. If you
    
  1123.     set ``save_on_top``, the buttons will appear both on the top and the
    
  1124.     bottom.
    
  1125. 
    
  1126.     By default, ``save_on_top`` is set to ``False``.
    
  1127. 
    
  1128. .. attribute:: ModelAdmin.search_fields
    
  1129. 
    
  1130.     Set ``search_fields`` to enable a search box on the admin change list page.
    
  1131.     This should be set to a list of field names that will be searched whenever
    
  1132.     somebody submits a search query in that text box.
    
  1133. 
    
  1134.     These fields should be some kind of text field, such as ``CharField`` or
    
  1135.     ``TextField``. You can also perform a related lookup on a ``ForeignKey`` or
    
  1136.     ``ManyToManyField`` with the lookup API "follow" notation::
    
  1137. 
    
  1138.         search_fields = ['foreign_key__related_fieldname']
    
  1139. 
    
  1140.     For example, if you have a blog entry with an author, the following
    
  1141.     definition would enable searching blog entries by the email address of the
    
  1142.     author::
    
  1143. 
    
  1144.         search_fields = ['user__email']
    
  1145. 
    
  1146.     When somebody does a search in the admin search box, Django splits the
    
  1147.     search query into words and returns all objects that contain each of the
    
  1148.     words, case-insensitive (using the :lookup:`icontains` lookup), where each
    
  1149.     word must be in at least one of ``search_fields``. For example, if
    
  1150.     ``search_fields`` is set to ``['first_name', 'last_name']`` and a user
    
  1151.     searches for ``john lennon``, Django will do the equivalent of this SQL
    
  1152.     ``WHERE`` clause:
    
  1153. 
    
  1154.     .. code-block:: sql
    
  1155. 
    
  1156.         WHERE (first_name ILIKE '%john%' OR last_name ILIKE '%john%')
    
  1157.         AND (first_name ILIKE '%lennon%' OR last_name ILIKE '%lennon%')
    
  1158. 
    
  1159.     The search query can contain quoted phrases with spaces. For example, if a
    
  1160.     user searches for ``"john winston"`` or ``'john winston'``, Django will do
    
  1161.     the equivalent of this SQL ``WHERE`` clause:
    
  1162. 
    
  1163.     .. code-block:: sql
    
  1164. 
    
  1165.         WHERE (first_name ILIKE '%john winston%' OR last_name ILIKE '%john winston%')
    
  1166. 
    
  1167.     If you don't want to use ``icontains`` as the lookup, you can use any
    
  1168.     lookup by appending it the field. For example, you could use :lookup:`exact`
    
  1169.     by setting ``search_fields`` to ``['first_name__exact']``.
    
  1170. 
    
  1171.     Some (older) shortcuts for specifying a field lookup are also available.
    
  1172.     You can prefix a field in ``search_fields`` with the following characters
    
  1173.     and it's equivalent to adding ``__<lookup>`` to the field:
    
  1174. 
    
  1175.     ======  ====================
    
  1176.     Prefix  Lookup
    
  1177.     ======  ====================
    
  1178.     ^       :lookup:`startswith`
    
  1179.     =       :lookup:`iexact`
    
  1180.     @       :lookup:`search`
    
  1181.     None    :lookup:`icontains`
    
  1182.     ======  ====================
    
  1183. 
    
  1184.     If you need to customize search you can use
    
  1185.     :meth:`ModelAdmin.get_search_results` to provide additional or alternate
    
  1186.     search behavior.
    
  1187. 
    
  1188.     .. versionchanged:: 4.1
    
  1189. 
    
  1190.         Searches using multiple search terms are now applied in a single call
    
  1191.         to ``filter()``, rather than in sequential ``filter()`` calls.
    
  1192. 
    
  1193.         For multi-valued relationships, this means that rows from the related
    
  1194.         model must match all terms rather than any term. For example, if
    
  1195.         ``search_fields`` is set to ``['child__name', 'child__age']``, and a
    
  1196.         user searches for ``'Jamal 17'``, parent rows will be returned only if
    
  1197.         there is a relationship to some 17-year-old child named Jamal, rather
    
  1198.         than also returning parents who merely have a younger or older child
    
  1199.         named Jamal in addition to some other 17-year-old.
    
  1200. 
    
  1201.         See the :ref:`spanning-multi-valued-relationships` topic for more
    
  1202.         discussion of this difference.
    
  1203. 
    
  1204. .. attribute:: ModelAdmin.search_help_text
    
  1205. 
    
  1206.     .. versionadded:: 4.0
    
  1207. 
    
  1208.     Set ``search_help_text`` to specify a descriptive text for the search box
    
  1209.     which will be displayed below it.
    
  1210. 
    
  1211. .. attribute:: ModelAdmin.show_full_result_count
    
  1212. 
    
  1213.     Set ``show_full_result_count`` to control whether the full count of objects
    
  1214.     should be displayed on a filtered admin page (e.g. ``99 results (103 total)``).
    
  1215.     If this option is set to ``False``, a text like ``99 results (Show all)``
    
  1216.     is displayed instead.
    
  1217. 
    
  1218.     The default of ``show_full_result_count=True`` generates a query to perform
    
  1219.     a full count on the table which can be expensive if the table contains a
    
  1220.     large number of rows.
    
  1221. 
    
  1222. .. attribute:: ModelAdmin.sortable_by
    
  1223. 
    
  1224.     By default, the change list page allows sorting by all model fields (and
    
  1225.     callables that use the ``ordering`` argument to the
    
  1226.     :func:`~django.contrib.admin.display` decorator or have the
    
  1227.     ``admin_order_field`` attribute) specified in :attr:`list_display`.
    
  1228. 
    
  1229.     If you want to disable sorting for some columns, set ``sortable_by`` to
    
  1230.     a collection (e.g. ``list``, ``tuple``, or ``set``) of the subset of
    
  1231.     :attr:`list_display` that you want to be sortable. An empty collection
    
  1232.     disables sorting for all columns.
    
  1233. 
    
  1234.     If you need to specify this list dynamically, implement a
    
  1235.     :meth:`~ModelAdmin.get_sortable_by` method instead.
    
  1236. 
    
  1237. .. attribute:: ModelAdmin.view_on_site
    
  1238. 
    
  1239.     Set ``view_on_site`` to control whether or not to display the "View on site" link.
    
  1240.     This link should bring you to a URL where you can display the saved object.
    
  1241. 
    
  1242.     This value can be either a boolean flag or a callable. If ``True`` (the
    
  1243.     default), the object's :meth:`~django.db.models.Model.get_absolute_url`
    
  1244.     method will be used to generate the url.
    
  1245. 
    
  1246.     If your model has a :meth:`~django.db.models.Model.get_absolute_url` method
    
  1247.     but you don't want the "View on site" button to appear, you only need to set
    
  1248.     ``view_on_site`` to ``False``::
    
  1249. 
    
  1250.         from django.contrib import admin
    
  1251. 
    
  1252.         class PersonAdmin(admin.ModelAdmin):
    
  1253.             view_on_site = False
    
  1254. 
    
  1255.     In case it is a callable, it accepts the model instance as a parameter.
    
  1256.     For example::
    
  1257. 
    
  1258.         from django.contrib import admin
    
  1259.         from django.urls import reverse
    
  1260. 
    
  1261.         class PersonAdmin(admin.ModelAdmin):
    
  1262.             def view_on_site(self, obj):
    
  1263.                 url = reverse('person-detail', kwargs={'slug': obj.slug})
    
  1264.                 return 'https://example.com' + url
    
  1265. 
    
  1266. Custom template options
    
  1267. ~~~~~~~~~~~~~~~~~~~~~~~
    
  1268. 
    
  1269. The :ref:`admin-overriding-templates` section describes how to override or extend
    
  1270. the default admin templates.  Use the following options to override the default
    
  1271. templates used by the :class:`ModelAdmin` views:
    
  1272. 
    
  1273. .. attribute:: ModelAdmin.add_form_template
    
  1274. 
    
  1275.     Path to a custom template, used by :meth:`add_view`.
    
  1276. 
    
  1277. .. attribute:: ModelAdmin.change_form_template
    
  1278. 
    
  1279.     Path to a custom template, used by :meth:`change_view`.
    
  1280. 
    
  1281. .. attribute:: ModelAdmin.change_list_template
    
  1282. 
    
  1283.     Path to a custom template, used by :meth:`changelist_view`.
    
  1284. 
    
  1285. .. attribute:: ModelAdmin.delete_confirmation_template
    
  1286. 
    
  1287.     Path to a custom template, used by :meth:`delete_view` for displaying a
    
  1288.     confirmation page when deleting one or more objects.
    
  1289. 
    
  1290. .. attribute:: ModelAdmin.delete_selected_confirmation_template
    
  1291. 
    
  1292.     Path to a custom template, used by the ``delete_selected`` action method
    
  1293.     for displaying a confirmation page when deleting one or more objects. See
    
  1294.     the :doc:`actions documentation</ref/contrib/admin/actions>`.
    
  1295. 
    
  1296. .. attribute:: ModelAdmin.object_history_template
    
  1297. 
    
  1298.     Path to a custom template, used by :meth:`history_view`.
    
  1299. 
    
  1300. .. attribute:: ModelAdmin.popup_response_template
    
  1301. 
    
  1302.     Path to a custom template, used by :meth:`response_add`,
    
  1303.     :meth:`response_change`, and :meth:`response_delete`.
    
  1304. 
    
  1305. .. _model-admin-methods:
    
  1306. 
    
  1307. ``ModelAdmin`` methods
    
  1308. ----------------------
    
  1309. 
    
  1310. .. warning::
    
  1311. 
    
  1312.     When overriding :meth:`ModelAdmin.save_model` and
    
  1313.     :meth:`ModelAdmin.delete_model`, your code must save/delete the
    
  1314.     object. They aren't meant for veto purposes, rather they allow you to
    
  1315.     perform extra operations.
    
  1316. 
    
  1317. .. method:: ModelAdmin.save_model(request, obj, form, change)
    
  1318. 
    
  1319.     The ``save_model`` method is given the ``HttpRequest``, a model instance,
    
  1320.     a ``ModelForm`` instance, and a boolean value based on whether it is adding
    
  1321.     or changing the object. Overriding this method allows doing pre- or
    
  1322.     post-save operations. Call ``super().save_model()`` to save the object
    
  1323.     using :meth:`.Model.save`.
    
  1324. 
    
  1325.     For example to attach ``request.user`` to the object prior to saving::
    
  1326. 
    
  1327.         from django.contrib import admin
    
  1328. 
    
  1329.         class ArticleAdmin(admin.ModelAdmin):
    
  1330.             def save_model(self, request, obj, form, change):
    
  1331.                 obj.user = request.user
    
  1332.                 super().save_model(request, obj, form, change)
    
  1333. 
    
  1334. .. method:: ModelAdmin.delete_model(request, obj)
    
  1335. 
    
  1336.     The ``delete_model`` method is given the ``HttpRequest`` and a model
    
  1337.     instance. Overriding this method allows doing pre- or post-delete
    
  1338.     operations. Call ``super().delete_model()`` to delete the object using
    
  1339.     :meth:`.Model.delete`.
    
  1340. 
    
  1341. .. method:: ModelAdmin.delete_queryset(request, queryset)
    
  1342. 
    
  1343.     The ``delete_queryset()`` method is given the ``HttpRequest`` and a
    
  1344.     ``QuerySet`` of objects to be deleted. Override this method to customize
    
  1345.     the deletion process for the "delete selected objects" :doc:`action
    
  1346.     <actions>`.
    
  1347. 
    
  1348. .. method:: ModelAdmin.save_formset(request, form, formset, change)
    
  1349. 
    
  1350.     The ``save_formset`` method is given the ``HttpRequest``, the parent
    
  1351.     ``ModelForm`` instance and a boolean value based on whether it is adding or
    
  1352.     changing the parent object.
    
  1353. 
    
  1354.     For example, to attach ``request.user`` to each changed formset
    
  1355.     model instance::
    
  1356. 
    
  1357.         class ArticleAdmin(admin.ModelAdmin):
    
  1358.             def save_formset(self, request, form, formset, change):
    
  1359.                 instances = formset.save(commit=False)
    
  1360.                 for obj in formset.deleted_objects:
    
  1361.                     obj.delete()
    
  1362.                 for instance in instances:
    
  1363.                     instance.user = request.user
    
  1364.                     instance.save()
    
  1365.                 formset.save_m2m()
    
  1366. 
    
  1367.     See also :ref:`saving-objects-in-the-formset`.
    
  1368. 
    
  1369. .. method:: ModelAdmin.get_ordering(request)
    
  1370. 
    
  1371.     The ``get_ordering`` method takes a ``request`` as parameter and
    
  1372.     is expected to return a ``list`` or ``tuple`` for ordering similar
    
  1373.     to the :attr:`ordering` attribute. For example::
    
  1374. 
    
  1375.         class PersonAdmin(admin.ModelAdmin):
    
  1376. 
    
  1377.             def get_ordering(self, request):
    
  1378.                 if request.user.is_superuser:
    
  1379.                     return ['name', 'rank']
    
  1380.                 else:
    
  1381.                     return ['name']
    
  1382. 
    
  1383. .. method:: ModelAdmin.get_search_results(request, queryset, search_term)
    
  1384. 
    
  1385.     The ``get_search_results`` method modifies the list of objects displayed
    
  1386.     into those that match the provided search term. It accepts the request, a
    
  1387.     queryset that applies the current filters, and the user-provided search term.
    
  1388.     It returns a tuple containing a queryset modified to implement the search, and
    
  1389.     a boolean indicating if the results may contain duplicates.
    
  1390. 
    
  1391.     The default implementation searches the fields named in :attr:`ModelAdmin.search_fields`.
    
  1392. 
    
  1393.     This method may be overridden with your own custom search method. For
    
  1394.     example, you might wish to search by an integer field, or use an external
    
  1395.     tool such as `Solr`_ or `Haystack`_. You must establish if the queryset
    
  1396.     changes implemented by your search method may introduce duplicates into the
    
  1397.     results, and return ``True`` in the second element of the return value.
    
  1398. 
    
  1399.     For example, to search by ``name`` and ``age``, you could use::
    
  1400. 
    
  1401.         class PersonAdmin(admin.ModelAdmin):
    
  1402.             list_display = ('name', 'age')
    
  1403.             search_fields = ('name',)
    
  1404. 
    
  1405.             def get_search_results(self, request, queryset, search_term):
    
  1406.                 queryset, may_have_duplicates = super().get_search_results(
    
  1407.                     request, queryset, search_term,
    
  1408.                 )
    
  1409.                 try:
    
  1410.                     search_term_as_int = int(search_term)
    
  1411.                 except ValueError:
    
  1412.                     pass
    
  1413.                 else:
    
  1414.                     queryset |= self.model.objects.filter(age=search_term_as_int)
    
  1415.                 return queryset, may_have_duplicates
    
  1416. 
    
  1417.     This implementation is more efficient than ``search_fields =
    
  1418.     ('name', '=age')`` which results in a string comparison for the numeric
    
  1419.     field, for example ``... OR UPPER("polls_choice"."votes"::text) = UPPER('4')``
    
  1420.     on PostgreSQL.
    
  1421. 
    
  1422.     .. versionchanged:: 4.1
    
  1423. 
    
  1424.         Searches using multiple search terms are now applied in a single call
    
  1425.         to ``filter()``, rather than in sequential ``filter()`` calls.
    
  1426. 
    
  1427.         For multi-valued relationships, this means that rows from the related
    
  1428.         model must match all terms rather than any term. For example, if
    
  1429.         ``search_fields`` is set to ``['child__name', 'child__age']``, and a
    
  1430.         user searches for ``'Jamal 17'``, parent rows will be returned only if
    
  1431.         there is a relationship to some 17-year-old child named Jamal, rather
    
  1432.         than also returning parents who merely have a younger or older child
    
  1433.         named Jamal in addition to some other 17-year-old.
    
  1434. 
    
  1435.         See the :ref:`spanning-multi-valued-relationships` topic for more
    
  1436.         discussion of this difference.
    
  1437. 
    
  1438. .. _Solr: https://solr.apache.org
    
  1439. .. _Haystack: https://haystacksearch.org
    
  1440. 
    
  1441. .. method:: ModelAdmin.save_related(request, form, formsets, change)
    
  1442. 
    
  1443.     The ``save_related`` method is given the ``HttpRequest``, the parent
    
  1444.     ``ModelForm`` instance, the list of inline formsets and a boolean value
    
  1445.     based on whether the parent is being added or changed. Here you can do any
    
  1446.     pre- or post-save operations for objects related to the parent. Note
    
  1447.     that at this point the parent object and its form have already been saved.
    
  1448. 
    
  1449. .. method:: ModelAdmin.get_autocomplete_fields(request)
    
  1450. 
    
  1451.     The ``get_autocomplete_fields()`` method is given the ``HttpRequest`` and is
    
  1452.     expected to return a ``list`` or ``tuple`` of field names that will be
    
  1453.     displayed with an autocomplete widget as described above in the
    
  1454.     :attr:`ModelAdmin.autocomplete_fields` section.
    
  1455. 
    
  1456. .. method:: ModelAdmin.get_readonly_fields(request, obj=None)
    
  1457. 
    
  1458.     The ``get_readonly_fields`` method is given the ``HttpRequest`` and the
    
  1459.     ``obj`` being edited (or ``None`` on an add form) and is expected to return
    
  1460.     a ``list`` or ``tuple`` of field names that will be displayed as read-only,
    
  1461.     as described above in the :attr:`ModelAdmin.readonly_fields` section.
    
  1462. 
    
  1463. .. method:: ModelAdmin.get_prepopulated_fields(request, obj=None)
    
  1464. 
    
  1465.     The ``get_prepopulated_fields`` method is given the ``HttpRequest`` and the
    
  1466.     ``obj`` being edited (or ``None`` on an add form) and is expected to return
    
  1467.     a ``dictionary``, as described above in the :attr:`ModelAdmin.prepopulated_fields`
    
  1468.     section.
    
  1469. 
    
  1470. .. method:: ModelAdmin.get_list_display(request)
    
  1471. 
    
  1472.     The ``get_list_display`` method is given the ``HttpRequest`` and is
    
  1473.     expected to return a ``list`` or ``tuple`` of field names that will be
    
  1474.     displayed on the changelist view as described above in the
    
  1475.     :attr:`ModelAdmin.list_display` section.
    
  1476. 
    
  1477. .. method:: ModelAdmin.get_list_display_links(request, list_display)
    
  1478. 
    
  1479.     The ``get_list_display_links`` method is given the ``HttpRequest`` and
    
  1480.     the ``list`` or ``tuple`` returned by :meth:`ModelAdmin.get_list_display`.
    
  1481.     It is expected to return either ``None`` or a ``list`` or ``tuple`` of field
    
  1482.     names on the changelist that will be linked to the change view, as described
    
  1483.     in the :attr:`ModelAdmin.list_display_links` section.
    
  1484. 
    
  1485. .. method:: ModelAdmin.get_exclude(request, obj=None)
    
  1486. 
    
  1487.     The ``get_exclude`` method is given the ``HttpRequest`` and the ``obj``
    
  1488.     being edited (or ``None`` on an add form) and is expected to return a list
    
  1489.     of fields, as described in :attr:`ModelAdmin.exclude`.
    
  1490. 
    
  1491. .. method:: ModelAdmin.get_fields(request, obj=None)
    
  1492. 
    
  1493.     The ``get_fields`` method is given the ``HttpRequest`` and the ``obj``
    
  1494.     being edited (or ``None`` on an add form) and is expected to return a list
    
  1495.     of fields, as described above in the :attr:`ModelAdmin.fields` section.
    
  1496. 
    
  1497. .. method:: ModelAdmin.get_fieldsets(request, obj=None)
    
  1498. 
    
  1499.     The ``get_fieldsets`` method is given the ``HttpRequest`` and the ``obj``
    
  1500.     being edited (or ``None`` on an add form) and is expected to return a list
    
  1501.     of two-tuples, in which each two-tuple represents a ``<fieldset>`` on the
    
  1502.     admin form page, as described above in the :attr:`ModelAdmin.fieldsets` section.
    
  1503. 
    
  1504. .. method:: ModelAdmin.get_list_filter(request)
    
  1505. 
    
  1506.     The ``get_list_filter`` method is given the ``HttpRequest`` and is expected
    
  1507.     to return the same kind of sequence type as for the
    
  1508.     :attr:`~ModelAdmin.list_filter` attribute.
    
  1509. 
    
  1510. .. method:: ModelAdmin.get_list_select_related(request)
    
  1511. 
    
  1512.     The ``get_list_select_related`` method is given the ``HttpRequest`` and
    
  1513.     should return a boolean or list as :attr:`ModelAdmin.list_select_related`
    
  1514.     does.
    
  1515. 
    
  1516. .. method:: ModelAdmin.get_search_fields(request)
    
  1517. 
    
  1518.     The ``get_search_fields`` method is given the ``HttpRequest`` and is expected
    
  1519.     to return the same kind of sequence type as for the
    
  1520.     :attr:`~ModelAdmin.search_fields` attribute.
    
  1521. 
    
  1522. .. method:: ModelAdmin.get_sortable_by(request)
    
  1523. 
    
  1524.     The ``get_sortable_by()`` method is passed the ``HttpRequest`` and is
    
  1525.     expected to return a collection (e.g. ``list``, ``tuple``, or ``set``) of
    
  1526.     field names that will be sortable in the change list page.
    
  1527. 
    
  1528.     Its default implementation returns :attr:`sortable_by` if it's set,
    
  1529.     otherwise it defers to :meth:`get_list_display`.
    
  1530. 
    
  1531.     For example, to prevent one or more columns from being sortable::
    
  1532. 
    
  1533.         class PersonAdmin(admin.ModelAdmin):
    
  1534. 
    
  1535.             def get_sortable_by(self, request):
    
  1536.                 return {*self.get_list_display(request)} - {'rank'}
    
  1537. 
    
  1538. .. method:: ModelAdmin.get_inline_instances(request, obj=None)
    
  1539. 
    
  1540.     The ``get_inline_instances`` method is given the ``HttpRequest`` and the
    
  1541.     ``obj`` being edited (or ``None`` on an add form) and is expected to return
    
  1542.     a ``list`` or ``tuple`` of :class:`~django.contrib.admin.InlineModelAdmin`
    
  1543.     objects, as described below in the :class:`~django.contrib.admin.InlineModelAdmin`
    
  1544.     section. For example, the following would return inlines without the default
    
  1545.     filtering based on add, change, delete, and view permissions::
    
  1546. 
    
  1547.         class MyModelAdmin(admin.ModelAdmin):
    
  1548.             inlines = (MyInline,)
    
  1549. 
    
  1550.             def get_inline_instances(self, request, obj=None):
    
  1551.                 return [inline(self.model, self.admin_site) for inline in self.inlines]
    
  1552. 
    
  1553.     If you override this method, make sure that the returned inlines are
    
  1554.     instances of the classes defined in :attr:`inlines` or you might encounter
    
  1555.     a "Bad Request" error when adding related objects.
    
  1556. 
    
  1557. .. method:: ModelAdmin.get_inlines(request, obj)
    
  1558. 
    
  1559.     The ``get_inlines`` method is given the ``HttpRequest`` and the
    
  1560.     ``obj`` being edited (or ``None`` on an add form) and is expected to return
    
  1561.     an iterable of inlines. You can override this method to dynamically add
    
  1562.     inlines based on the request or model instance instead of specifying them
    
  1563.     in :attr:`ModelAdmin.inlines`.
    
  1564. 
    
  1565. .. method:: ModelAdmin.get_urls()
    
  1566. 
    
  1567.     The ``get_urls`` method on a ``ModelAdmin`` returns the URLs to be used for
    
  1568.     that ModelAdmin in the same way as a URLconf.  Therefore you can extend
    
  1569.     them as documented in :doc:`/topics/http/urls`, using the
    
  1570.     ``AdminSite.admin_view()`` wrapper on your views::
    
  1571. 
    
  1572.         from django.contrib import admin
    
  1573.         from django.template.response import TemplateResponse
    
  1574.         from django.urls import path
    
  1575. 
    
  1576.         class MyModelAdmin(admin.ModelAdmin):
    
  1577.             def get_urls(self):
    
  1578.                 urls = super().get_urls()
    
  1579.                 my_urls = [
    
  1580.                     path('my_view/', self.admin_site.admin_view(self.my_view))
    
  1581.                 ]
    
  1582.                 return my_urls + urls
    
  1583. 
    
  1584.             def my_view(self, request):
    
  1585.                 # ...
    
  1586.                 context = dict(
    
  1587.                    # Include common variables for rendering the admin template.
    
  1588.                    self.admin_site.each_context(request),
    
  1589.                    # Anything else you want in the context...
    
  1590.                    key=value,
    
  1591.                 )
    
  1592.                 return TemplateResponse(request, "sometemplate.html", context)
    
  1593. 
    
  1594.     If you want to use the admin layout, extend from ``admin/base_site.html``:
    
  1595. 
    
  1596.     .. code-block:: html+django
    
  1597. 
    
  1598.        {% extends "admin/base_site.html" %}
    
  1599.        {% block content %}
    
  1600.        ...
    
  1601.        {% endblock %}
    
  1602. 
    
  1603.     .. note::
    
  1604. 
    
  1605.         Notice how the ``self.my_view`` function is wrapped in
    
  1606.         ``self.admin_site.admin_view``. This is important, since it ensures two
    
  1607.         things:
    
  1608. 
    
  1609.         #. Permission checks are run, ensuring only active staff users can
    
  1610.            access the view.
    
  1611.         #. The :func:`django.views.decorators.cache.never_cache` decorator is
    
  1612.            applied to prevent caching, ensuring the returned information is
    
  1613.            up-to-date.
    
  1614. 
    
  1615.     .. note::
    
  1616. 
    
  1617.         Notice that the custom patterns are included *before* the regular admin
    
  1618.         URLs: the admin URL patterns are very permissive and will match nearly
    
  1619.         anything, so you'll usually want to prepend your custom URLs to the
    
  1620.         built-in ones.
    
  1621. 
    
  1622.         In this example, ``my_view`` will be accessed at
    
  1623.         ``/admin/myapp/mymodel/my_view/`` (assuming the admin URLs are included
    
  1624.         at ``/admin/``.)
    
  1625. 
    
  1626.     If the page is cacheable, but you still want the permission check to be
    
  1627.     performed, you can pass a ``cacheable=True`` argument to
    
  1628.     ``AdminSite.admin_view()``::
    
  1629. 
    
  1630.         path('my_view/', self.admin_site.admin_view(self.my_view, cacheable=True))
    
  1631. 
    
  1632.     ``ModelAdmin`` views have ``model_admin`` attributes. Other
    
  1633.     ``AdminSite`` views have ``admin_site`` attributes.
    
  1634. 
    
  1635. .. method:: ModelAdmin.get_form(request, obj=None, **kwargs)
    
  1636. 
    
  1637.     Returns a :class:`~django.forms.ModelForm` class for use in the admin add
    
  1638.     and change views, see :meth:`add_view` and :meth:`change_view`.
    
  1639. 
    
  1640.     The base implementation uses :func:`~django.forms.models.modelform_factory`
    
  1641.     to subclass :attr:`~form`, modified by attributes such as :attr:`~fields`
    
  1642.     and :attr:`~exclude`. So, for example, if you wanted to offer additional
    
  1643.     fields to superusers, you could swap in a different base form like so::
    
  1644. 
    
  1645.         class MyModelAdmin(admin.ModelAdmin):
    
  1646.             def get_form(self, request, obj=None, **kwargs):
    
  1647.                 if request.user.is_superuser:
    
  1648.                     kwargs['form'] = MySuperuserForm
    
  1649.                 return super().get_form(request, obj, **kwargs)
    
  1650. 
    
  1651.     You may also return a custom :class:`~django.forms.ModelForm` class
    
  1652.     directly.
    
  1653. 
    
  1654. .. method:: ModelAdmin.get_formsets_with_inlines(request, obj=None)
    
  1655. 
    
  1656.     Yields (``FormSet``, :class:`InlineModelAdmin`) pairs for use in admin add
    
  1657.     and change views.
    
  1658. 
    
  1659.     For example if you wanted to display a particular inline only in the change
    
  1660.     view, you could override ``get_formsets_with_inlines`` as follows::
    
  1661. 
    
  1662.         class MyModelAdmin(admin.ModelAdmin):
    
  1663.             inlines = [MyInline, SomeOtherInline]
    
  1664. 
    
  1665.             def get_formsets_with_inlines(self, request, obj=None):
    
  1666.                 for inline in self.get_inline_instances(request, obj):
    
  1667.                     # hide MyInline in the add view
    
  1668.                     if not isinstance(inline, MyInline) or obj is not None:
    
  1669.                         yield inline.get_formset(request, obj), inline
    
  1670. 
    
  1671. .. method:: ModelAdmin.formfield_for_foreignkey(db_field, request, **kwargs)
    
  1672. 
    
  1673.     The ``formfield_for_foreignkey`` method on a ``ModelAdmin`` allows you to
    
  1674.     override the default formfield for a foreign keys field. For example, to
    
  1675.     return a subset of objects for this foreign key field based on the user::
    
  1676. 
    
  1677.         class MyModelAdmin(admin.ModelAdmin):
    
  1678.             def formfield_for_foreignkey(self, db_field, request, **kwargs):
    
  1679.                 if db_field.name == "car":
    
  1680.                     kwargs["queryset"] = Car.objects.filter(owner=request.user)
    
  1681.                 return super().formfield_for_foreignkey(db_field, request, **kwargs)
    
  1682. 
    
  1683.     This uses the ``HttpRequest`` instance to filter the ``Car`` foreign key
    
  1684.     field to only display the cars owned by the ``User`` instance.
    
  1685. 
    
  1686.     For more complex filters, you can use ``ModelForm.__init__()`` method to
    
  1687.     filter based on an ``instance`` of your model (see
    
  1688.     :ref:`fields-which-handle-relationships`). For example::
    
  1689. 
    
  1690.         class CountryAdminForm(forms.ModelForm):
    
  1691.             def __init__(self, *args, **kwargs):
    
  1692.                 super().__init__(*args, **kwargs)
    
  1693.                 self.fields['capital'].queryset = self.instance.cities.all()
    
  1694. 
    
  1695.         class CountryAdmin(admin.ModelAdmin):
    
  1696.             form = CountryAdminForm
    
  1697. 
    
  1698. .. method:: ModelAdmin.formfield_for_manytomany(db_field, request, **kwargs)
    
  1699. 
    
  1700.     Like the ``formfield_for_foreignkey`` method, the
    
  1701.     ``formfield_for_manytomany`` method can be overridden to change the
    
  1702.     default formfield for a many to many field. For example, if an owner can
    
  1703.     own multiple cars and cars can belong to multiple owners -- a many to
    
  1704.     many relationship -- you could filter the ``Car`` foreign key field to
    
  1705.     only display the cars owned by the ``User``::
    
  1706. 
    
  1707.         class MyModelAdmin(admin.ModelAdmin):
    
  1708.             def formfield_for_manytomany(self, db_field, request, **kwargs):
    
  1709.                 if db_field.name == "cars":
    
  1710.                     kwargs["queryset"] = Car.objects.filter(owner=request.user)
    
  1711.                 return super().formfield_for_manytomany(db_field, request, **kwargs)
    
  1712. 
    
  1713. .. method:: ModelAdmin.formfield_for_choice_field(db_field, request, **kwargs)
    
  1714. 
    
  1715.     Like the ``formfield_for_foreignkey`` and ``formfield_for_manytomany``
    
  1716.     methods, the ``formfield_for_choice_field`` method can be overridden to
    
  1717.     change the default formfield for a field that has declared choices. For
    
  1718.     example, if the choices available to a superuser should be different than
    
  1719.     those available to regular staff, you could proceed as follows::
    
  1720. 
    
  1721.         class MyModelAdmin(admin.ModelAdmin):
    
  1722.             def formfield_for_choice_field(self, db_field, request, **kwargs):
    
  1723.                 if db_field.name == "status":
    
  1724.                     kwargs['choices'] = (
    
  1725.                         ('accepted', 'Accepted'),
    
  1726.                         ('denied', 'Denied'),
    
  1727.                     )
    
  1728.                     if request.user.is_superuser:
    
  1729.                         kwargs['choices'] += (('ready', 'Ready for deployment'),)
    
  1730.                 return super().formfield_for_choice_field(db_field, request, **kwargs)
    
  1731. 
    
  1732.     .. admonition:: Note
    
  1733. 
    
  1734.         Any ``choices`` attribute set on the formfield will be limited to the
    
  1735.         form field only. If the corresponding field on the model has choices
    
  1736.         set, the choices provided to the form must be a valid subset of those
    
  1737.         choices, otherwise the form submission will fail with
    
  1738.         a :exc:`~django.core.exceptions.ValidationError` when the model itself
    
  1739.         is validated before saving.
    
  1740. 
    
  1741. .. method:: ModelAdmin.get_changelist(request, **kwargs)
    
  1742. 
    
  1743.     Returns the ``Changelist`` class to be used for listing. By default,
    
  1744.     ``django.contrib.admin.views.main.ChangeList`` is used. By inheriting this
    
  1745.     class you can change the behavior of the listing.
    
  1746. 
    
  1747. .. method:: ModelAdmin.get_changelist_form(request, **kwargs)
    
  1748. 
    
  1749.     Returns a :class:`~django.forms.ModelForm` class for use in the ``Formset``
    
  1750.     on the changelist page. To use a custom form, for example::
    
  1751. 
    
  1752.         from django import forms
    
  1753. 
    
  1754.         class MyForm(forms.ModelForm):
    
  1755.             pass
    
  1756. 
    
  1757.         class MyModelAdmin(admin.ModelAdmin):
    
  1758.             def get_changelist_form(self, request, **kwargs):
    
  1759.                 return MyForm
    
  1760. 
    
  1761.     .. admonition:: Note
    
  1762. 
    
  1763.         If you define the ``Meta.model`` attribute on a
    
  1764.         :class:`~django.forms.ModelForm`, you must also define the
    
  1765.         ``Meta.fields`` attribute (or the ``Meta.exclude`` attribute). However,
    
  1766.         ``ModelAdmin`` ignores this value, overriding it with the
    
  1767.         :attr:`ModelAdmin.list_editable` attribute. The easiest solution is to
    
  1768.         omit the ``Meta.model`` attribute, since ``ModelAdmin`` will provide the
    
  1769.         correct model to use.
    
  1770. 
    
  1771. .. method::  ModelAdmin.get_changelist_formset(request, **kwargs)
    
  1772. 
    
  1773.     Returns a :ref:`ModelFormSet <model-formsets>` class for use on the
    
  1774.     changelist page if :attr:`~ModelAdmin.list_editable` is used. To use a
    
  1775.     custom formset, for example::
    
  1776. 
    
  1777.         from django.forms import BaseModelFormSet
    
  1778. 
    
  1779.         class MyAdminFormSet(BaseModelFormSet):
    
  1780.             pass
    
  1781. 
    
  1782.         class MyModelAdmin(admin.ModelAdmin):
    
  1783.             def get_changelist_formset(self, request, **kwargs):
    
  1784.                 kwargs['formset'] = MyAdminFormSet
    
  1785.                 return super().get_changelist_formset(request, **kwargs)
    
  1786. 
    
  1787. .. method:: ModelAdmin.lookup_allowed(lookup, value)
    
  1788. 
    
  1789.     The objects in the changelist page can be filtered with lookups from the
    
  1790.     URL's query string. This is how :attr:`list_filter` works, for example. The
    
  1791.     lookups are similar to what's used in :meth:`.QuerySet.filter` (e.g.
    
  1792.     ``[email protected]``). Since the lookups in the query string
    
  1793.     can be manipulated by the user, they must be sanitized to prevent
    
  1794.     unauthorized data exposure.
    
  1795. 
    
  1796.     The ``lookup_allowed()`` method is given a lookup path from the query string
    
  1797.     (e.g. ``'user__email'``) and the corresponding value
    
  1798.     (e.g. ``'[email protected]'``), and returns a boolean indicating whether
    
  1799.     filtering the changelist's ``QuerySet`` using the parameters is permitted.
    
  1800.     If ``lookup_allowed()`` returns ``False``, ``DisallowedModelAdminLookup``
    
  1801.     (subclass of :exc:`~django.core.exceptions.SuspiciousOperation`) is raised.
    
  1802. 
    
  1803.     By default, ``lookup_allowed()`` allows access to a model's local fields,
    
  1804.     field paths used in :attr:`~ModelAdmin.list_filter` (but not paths from
    
  1805.     :meth:`~ModelAdmin.get_list_filter`), and lookups required for
    
  1806.     :attr:`~django.db.models.ForeignKey.limit_choices_to` to function
    
  1807.     correctly in :attr:`~django.contrib.admin.ModelAdmin.raw_id_fields`.
    
  1808. 
    
  1809.     Override this method to customize the lookups permitted for your
    
  1810.     :class:`~django.contrib.admin.ModelAdmin` subclass.
    
  1811. 
    
  1812. .. method:: ModelAdmin.has_view_permission(request, obj=None)
    
  1813. 
    
  1814.     Should return ``True`` if viewing ``obj`` is permitted, ``False`` otherwise.
    
  1815.     If obj is ``None``, should return ``True`` or ``False`` to indicate whether
    
  1816.     viewing of objects of this type is permitted in general (e.g., ``False``
    
  1817.     will be interpreted as meaning that the current user is not permitted to
    
  1818.     view any object of this type).
    
  1819. 
    
  1820.     The default implementation returns ``True`` if the user has either the
    
  1821.     "change" or "view" permission.
    
  1822. 
    
  1823. .. method:: ModelAdmin.has_add_permission(request)
    
  1824. 
    
  1825.     Should return ``True`` if adding an object is permitted, ``False``
    
  1826.     otherwise.
    
  1827. 
    
  1828. .. method:: ModelAdmin.has_change_permission(request, obj=None)
    
  1829. 
    
  1830.     Should return ``True`` if editing ``obj`` is permitted, ``False``
    
  1831.     otherwise. If ``obj`` is ``None``, should return ``True`` or ``False`` to
    
  1832.     indicate whether editing of objects of this type is permitted in general
    
  1833.     (e.g., ``False`` will be interpreted as meaning that the current user is
    
  1834.     not permitted to edit any object of this type).
    
  1835. 
    
  1836. .. method:: ModelAdmin.has_delete_permission(request, obj=None)
    
  1837. 
    
  1838.     Should return ``True`` if deleting ``obj`` is permitted, ``False``
    
  1839.     otherwise. If ``obj`` is ``None``, should return ``True`` or ``False`` to
    
  1840.     indicate whether deleting objects of this type is permitted in general
    
  1841.     (e.g., ``False`` will be interpreted as meaning that the current user is
    
  1842.     not permitted to delete any object of this type).
    
  1843. 
    
  1844. .. method:: ModelAdmin.has_module_permission(request)
    
  1845. 
    
  1846.     Should return ``True`` if displaying the module on the admin index page and
    
  1847.     accessing the module's index page is permitted, ``False`` otherwise.
    
  1848.     Uses :meth:`User.has_module_perms()
    
  1849.     <django.contrib.auth.models.User.has_module_perms>` by default. Overriding
    
  1850.     it does not restrict access to the view, add, change, or delete views,
    
  1851.     :meth:`~ModelAdmin.has_view_permission`,
    
  1852.     :meth:`~ModelAdmin.has_add_permission`,
    
  1853.     :meth:`~ModelAdmin.has_change_permission`, and
    
  1854.     :meth:`~ModelAdmin.has_delete_permission` should be used for that.
    
  1855. 
    
  1856. .. method:: ModelAdmin.get_queryset(request)
    
  1857. 
    
  1858.     The ``get_queryset`` method on a ``ModelAdmin`` returns a
    
  1859.     :class:`~django.db.models.query.QuerySet` of all model instances that
    
  1860.     can be edited by the admin site. One use case for overriding this method
    
  1861.     is to show objects owned by the logged-in user::
    
  1862. 
    
  1863.         class MyModelAdmin(admin.ModelAdmin):
    
  1864.             def get_queryset(self, request):
    
  1865.                 qs = super().get_queryset(request)
    
  1866.                 if request.user.is_superuser:
    
  1867.                     return qs
    
  1868.                 return qs.filter(author=request.user)
    
  1869. 
    
  1870. .. method:: ModelAdmin.message_user(request, message, level=messages.INFO, extra_tags='', fail_silently=False)
    
  1871. 
    
  1872.     Sends a message to the user using the :mod:`django.contrib.messages`
    
  1873.     backend.  See the :ref:`custom ModelAdmin example <custom-admin-action>`.
    
  1874. 
    
  1875.     Keyword arguments allow you to change the message level, add extra CSS
    
  1876.     tags, or fail silently if the ``contrib.messages`` framework is not
    
  1877.     installed. These keyword arguments match those for
    
  1878.     :func:`django.contrib.messages.add_message`, see that function's
    
  1879.     documentation for more details. One difference is that the level may be
    
  1880.     passed as a string label in addition to integer/constant.
    
  1881. 
    
  1882. .. method:: ModelAdmin.get_paginator(request, queryset, per_page, orphans=0, allow_empty_first_page=True)
    
  1883. 
    
  1884.     Returns an instance of the paginator to use for this view. By default,
    
  1885.     instantiates an instance of :attr:`paginator`.
    
  1886. 
    
  1887. .. method:: ModelAdmin.response_add(request, obj, post_url_continue=None)
    
  1888. 
    
  1889.     Determines the :class:`~django.http.HttpResponse` for the
    
  1890.     :meth:`add_view` stage.
    
  1891. 
    
  1892.     ``response_add`` is called after the admin form is submitted and
    
  1893.     just after the object and all the related instances have
    
  1894.     been created and saved. You can override it to change the default behavior
    
  1895.     after the object has been created.
    
  1896. 
    
  1897. .. method:: ModelAdmin.response_change(request, obj)
    
  1898. 
    
  1899.     Determines the :class:`~django.http.HttpResponse` for the
    
  1900.     :meth:`change_view` stage.
    
  1901. 
    
  1902.     ``response_change`` is called after the admin form is submitted and
    
  1903.     just after the object and all the related instances have
    
  1904.     been saved. You can override it to change the default
    
  1905.     behavior after the object has been changed.
    
  1906. 
    
  1907. .. method:: ModelAdmin.response_delete(request, obj_display, obj_id)
    
  1908. 
    
  1909.     Determines the :class:`~django.http.HttpResponse` for the
    
  1910.     :meth:`delete_view` stage.
    
  1911. 
    
  1912.     ``response_delete`` is called after the object has been
    
  1913.     deleted. You can override it to change the default
    
  1914.     behavior after the object has been deleted.
    
  1915. 
    
  1916.     ``obj_display`` is a string with the name of the deleted
    
  1917.     object.
    
  1918. 
    
  1919.     ``obj_id`` is the serialized identifier used to retrieve the object to be
    
  1920.     deleted.
    
  1921. 
    
  1922. .. method:: ModelAdmin.get_formset_kwargs(request, obj, inline, prefix)
    
  1923. 
    
  1924.     .. versionadded:: 4.0
    
  1925. 
    
  1926.     A hook for customizing the keyword arguments passed to the constructor of a
    
  1927.     formset. For example, to pass ``request`` to formset forms::
    
  1928. 
    
  1929.         class MyModelAdmin(admin.ModelAdmin):
    
  1930.             def get_formset_kwargs(self, request, obj, inline, prefix):
    
  1931.                 return {
    
  1932.                     **super().get_formset_kwargs(request, obj, inline, prefix),
    
  1933.                     'form_kwargs': {'request': request},
    
  1934.                 }
    
  1935. 
    
  1936.     You can also use it to set ``initial`` for formset forms.
    
  1937. 
    
  1938. .. method:: ModelAdmin.get_changeform_initial_data(request)
    
  1939. 
    
  1940.     A hook for the initial data on admin change forms. By default, fields are
    
  1941.     given initial values from ``GET`` parameters. For instance,
    
  1942.     ``?name=initial_value`` will set the ``name`` field's initial value to be
    
  1943.     ``initial_value``.
    
  1944. 
    
  1945.     This method should return a dictionary in the form
    
  1946.     ``{'fieldname': 'fieldval'}``::
    
  1947. 
    
  1948.         def get_changeform_initial_data(self, request):
    
  1949.             return {'name': 'custom_initial_value'}
    
  1950. 
    
  1951. .. method:: ModelAdmin.get_deleted_objects(objs, request)
    
  1952. 
    
  1953.     A hook for customizing the deletion process of the :meth:`delete_view` and
    
  1954.     the "delete selected" :doc:`action <actions>`.
    
  1955. 
    
  1956.     The ``objs`` argument is a homogeneous iterable of objects (a ``QuerySet``
    
  1957.     or a list of model instances) to be deleted, and ``request`` is the
    
  1958.     :class:`~django.http.HttpRequest`.
    
  1959. 
    
  1960.     This method must return a 4-tuple of
    
  1961.     ``(deleted_objects, model_count, perms_needed, protected)``.
    
  1962. 
    
  1963.     ``deleted_objects`` is a list of strings representing all the objects that
    
  1964.     will be deleted. If there are any related objects to be deleted, the list
    
  1965.     is nested and includes those related objects. The list is formatted in the
    
  1966.     template using the :tfilter:`unordered_list` filter.
    
  1967. 
    
  1968.     ``model_count`` is a dictionary mapping each model's
    
  1969.     :attr:`~django.db.models.Options.verbose_name_plural` to the number of
    
  1970.     objects that will be deleted.
    
  1971. 
    
  1972.     ``perms_needed`` is a set of :attr:`~django.db.models.Options.verbose_name`\s
    
  1973.     of the models that the user doesn't have permission to delete.
    
  1974. 
    
  1975.     ``protected`` is a list of strings representing of all the protected
    
  1976.     related objects that can't be deleted. The list is displayed in the
    
  1977.     template.
    
  1978. 
    
  1979. Other methods
    
  1980. ~~~~~~~~~~~~~
    
  1981. 
    
  1982. .. method:: ModelAdmin.add_view(request, form_url='', extra_context=None)
    
  1983. 
    
  1984.     Django view for the model instance addition page. See note below.
    
  1985. 
    
  1986. .. method:: ModelAdmin.change_view(request, object_id, form_url='', extra_context=None)
    
  1987. 
    
  1988.     Django view for the model instance editing page. See note below.
    
  1989. 
    
  1990. .. method:: ModelAdmin.changelist_view(request, extra_context=None)
    
  1991. 
    
  1992.     Django view for the model instances change list/actions page. See note
    
  1993.     below.
    
  1994. 
    
  1995. .. method:: ModelAdmin.delete_view(request, object_id, extra_context=None)
    
  1996. 
    
  1997.     Django view for the model instance(s) deletion confirmation page. See note
    
  1998.     below.
    
  1999. 
    
  2000. .. method:: ModelAdmin.history_view(request, object_id, extra_context=None)
    
  2001. 
    
  2002.     Django view for the page that shows the modification history for a given
    
  2003.     model instance.
    
  2004. 
    
  2005.     .. versionchanged:: 4.1
    
  2006. 
    
  2007.         Pagination was added.
    
  2008. 
    
  2009. Unlike the hook-type ``ModelAdmin`` methods detailed in the previous section,
    
  2010. these five methods are in reality designed to be invoked as Django views from
    
  2011. the admin application URL dispatching handler to render the pages that deal
    
  2012. with model instances CRUD operations. As a result, completely overriding these
    
  2013. methods will significantly change the behavior of the admin application.
    
  2014. 
    
  2015. One common reason for overriding these methods is to augment the context data
    
  2016. that is provided to the template that renders the view. In the following
    
  2017. example, the change view is overridden so that the rendered template is
    
  2018. provided some extra mapping data that would not otherwise be available::
    
  2019. 
    
  2020.     class MyModelAdmin(admin.ModelAdmin):
    
  2021. 
    
  2022.         # A template for a very customized change view:
    
  2023.         change_form_template = 'admin/myapp/extras/openstreetmap_change_form.html'
    
  2024. 
    
  2025.         def get_osm_info(self):
    
  2026.             # ...
    
  2027.             pass
    
  2028. 
    
  2029.         def change_view(self, request, object_id, form_url='', extra_context=None):
    
  2030.             extra_context = extra_context or {}
    
  2031.             extra_context['osm_data'] = self.get_osm_info()
    
  2032.             return super().change_view(
    
  2033.                 request, object_id, form_url, extra_context=extra_context,
    
  2034.             )
    
  2035. 
    
  2036. These views return :class:`~django.template.response.TemplateResponse`
    
  2037. instances which allow you to easily customize the response data before
    
  2038. rendering. For more details, see the :doc:`TemplateResponse documentation
    
  2039. </ref/template-response>`.
    
  2040. 
    
  2041. .. _modeladmin-asset-definitions:
    
  2042. 
    
  2043. ``ModelAdmin`` asset definitions
    
  2044. --------------------------------
    
  2045. 
    
  2046. There are times where you would like add a bit of CSS and/or JavaScript to
    
  2047. the add/change views. This can be accomplished by using a ``Media`` inner class
    
  2048. on your ``ModelAdmin``::
    
  2049. 
    
  2050.     class ArticleAdmin(admin.ModelAdmin):
    
  2051.         class Media:
    
  2052.             css = {
    
  2053.                 "all": ("my_styles.css",)
    
  2054.             }
    
  2055.             js = ("my_code.js",)
    
  2056. 
    
  2057. The :doc:`staticfiles app </ref/contrib/staticfiles>` prepends
    
  2058. :setting:`STATIC_URL` (or :setting:`MEDIA_URL` if :setting:`STATIC_URL` is
    
  2059. ``None``) to any asset paths. The same rules apply as :ref:`regular asset
    
  2060. definitions on forms <form-asset-paths>`.
    
  2061. 
    
  2062. .. _contrib-admin-jquery:
    
  2063. 
    
  2064. jQuery
    
  2065. ~~~~~~
    
  2066. 
    
  2067. Django admin JavaScript makes use of the `jQuery`_ library.
    
  2068. 
    
  2069. To avoid conflicts with user-supplied scripts or libraries, Django's jQuery
    
  2070. (version 3.6.0) is namespaced as ``django.jQuery``. If you want to use jQuery
    
  2071. in your own admin JavaScript without including a second copy, you can use the
    
  2072. ``django.jQuery`` object on changelist and add/edit views. Also, your own admin
    
  2073. forms or widgets depending on ``django.jQuery`` must specify
    
  2074. ``js=['admin/js/jquery.init.js', …]`` when :ref:`declaring form media assets
    
  2075. <assets-as-a-static-definition>`.
    
  2076. 
    
  2077. .. versionchanged:: 4.0
    
  2078. 
    
  2079.     jQuery was upgraded from 3.5.1 to 3.6.0.
    
  2080. 
    
  2081. The :class:`ModelAdmin` class requires jQuery by default, so there is no need
    
  2082. to add jQuery to your ``ModelAdmin``’s list of media resources unless you have
    
  2083. a specific need. For example, if you require the jQuery library to be in the
    
  2084. global namespace (for example when using third-party jQuery plugins) or if you
    
  2085. need a newer version of jQuery, you will have to include your own copy.
    
  2086. 
    
  2087. Django provides both uncompressed and 'minified' versions of jQuery, as
    
  2088. ``jquery.js`` and ``jquery.min.js`` respectively.
    
  2089. 
    
  2090. :class:`ModelAdmin` and :class:`InlineModelAdmin` have a ``media`` property
    
  2091. that returns a list of ``Media`` objects which store paths to the JavaScript
    
  2092. files for the forms and/or formsets. If :setting:`DEBUG` is ``True`` it will
    
  2093. return the uncompressed versions of the various JavaScript files, including
    
  2094. ``jquery.js``; if not, it will return the 'minified' versions.
    
  2095. 
    
  2096. .. _jQuery: https://jquery.com
    
  2097. 
    
  2098. .. _admin-custom-validation:
    
  2099. 
    
  2100. Adding custom validation to the admin
    
  2101. -------------------------------------
    
  2102. 
    
  2103. You can also add custom validation of data in the admin. The automatic admin
    
  2104. interface reuses :mod:`django.forms`, and the ``ModelAdmin`` class gives you
    
  2105. the ability to define your own form::
    
  2106. 
    
  2107.     class ArticleAdmin(admin.ModelAdmin):
    
  2108.         form = MyArticleAdminForm
    
  2109. 
    
  2110. ``MyArticleAdminForm`` can be defined anywhere as long as you import where
    
  2111. needed. Now within your form you can add your own custom validation for
    
  2112. any field::
    
  2113. 
    
  2114.     class MyArticleAdminForm(forms.ModelForm):
    
  2115.         def clean_name(self):
    
  2116.             # do something that validates your data
    
  2117.             return self.cleaned_data["name"]
    
  2118. 
    
  2119. It is important you use a ``ModelForm`` here otherwise things can break. See
    
  2120. the :doc:`forms </ref/forms/index>` documentation on :doc:`custom validation
    
  2121. </ref/forms/validation>` and, more specifically, the
    
  2122. :ref:`model form validation notes <overriding-modelform-clean-method>` for more
    
  2123. information.
    
  2124. 
    
  2125. .. _admin-inlines:
    
  2126. 
    
  2127. ``InlineModelAdmin`` objects
    
  2128. ============================
    
  2129. 
    
  2130. .. class:: InlineModelAdmin
    
  2131. .. class:: TabularInline
    
  2132. .. class:: StackedInline
    
  2133. 
    
  2134.     The admin interface has the ability to edit models on the same page as a
    
  2135.     parent model. These are called inlines. Suppose you have these two models::
    
  2136. 
    
  2137.          from django.db import models
    
  2138. 
    
  2139.          class Author(models.Model):
    
  2140.             name = models.CharField(max_length=100)
    
  2141. 
    
  2142.          class Book(models.Model):
    
  2143.             author = models.ForeignKey(Author, on_delete=models.CASCADE)
    
  2144.             title = models.CharField(max_length=100)
    
  2145. 
    
  2146.     You can edit the books authored by an author on the author page. You add
    
  2147.     inlines to a model by specifying them in a ``ModelAdmin.inlines``::
    
  2148. 
    
  2149.         from django.contrib import admin
    
  2150. 
    
  2151.         class BookInline(admin.TabularInline):
    
  2152.             model = Book
    
  2153. 
    
  2154.         class AuthorAdmin(admin.ModelAdmin):
    
  2155.             inlines = [
    
  2156.                 BookInline,
    
  2157.             ]
    
  2158. 
    
  2159.     Django provides two subclasses of ``InlineModelAdmin`` and they are:
    
  2160. 
    
  2161.     * :class:`~django.contrib.admin.TabularInline`
    
  2162.     * :class:`~django.contrib.admin.StackedInline`
    
  2163. 
    
  2164.     The difference between these two is merely the template used to render
    
  2165.     them.
    
  2166. 
    
  2167. ``InlineModelAdmin`` options
    
  2168. -----------------------------
    
  2169. 
    
  2170. ``InlineModelAdmin`` shares many of the same features as ``ModelAdmin``, and
    
  2171. adds some of its own (the shared features are actually defined in the
    
  2172. ``BaseModelAdmin`` superclass). The shared features are:
    
  2173. 
    
  2174. - :attr:`~InlineModelAdmin.form`
    
  2175. - :attr:`~ModelAdmin.fieldsets`
    
  2176. - :attr:`~ModelAdmin.fields`
    
  2177. - :attr:`~ModelAdmin.formfield_overrides`
    
  2178. - :attr:`~ModelAdmin.exclude`
    
  2179. - :attr:`~ModelAdmin.filter_horizontal`
    
  2180. - :attr:`~ModelAdmin.filter_vertical`
    
  2181. - :attr:`~ModelAdmin.ordering`
    
  2182. - :attr:`~ModelAdmin.prepopulated_fields`
    
  2183. - :meth:`~ModelAdmin.get_fieldsets`
    
  2184. - :meth:`~ModelAdmin.get_queryset`
    
  2185. - :attr:`~ModelAdmin.radio_fields`
    
  2186. - :attr:`~ModelAdmin.readonly_fields`
    
  2187. - :attr:`~InlineModelAdmin.raw_id_fields`
    
  2188. - :meth:`~ModelAdmin.formfield_for_choice_field`
    
  2189. - :meth:`~ModelAdmin.formfield_for_foreignkey`
    
  2190. - :meth:`~ModelAdmin.formfield_for_manytomany`
    
  2191. - :meth:`~ModelAdmin.has_module_permission`
    
  2192. 
    
  2193. The ``InlineModelAdmin`` class adds or customizes:
    
  2194. 
    
  2195. .. attribute:: InlineModelAdmin.model
    
  2196. 
    
  2197.     The model which the inline is using. This is required.
    
  2198. 
    
  2199. .. attribute:: InlineModelAdmin.fk_name
    
  2200. 
    
  2201.     The name of the foreign key on the model. In most cases this will be dealt
    
  2202.     with automatically, but ``fk_name`` must be specified explicitly if there
    
  2203.     are more than one foreign key to the same parent model.
    
  2204. 
    
  2205. .. attribute:: InlineModelAdmin.formset
    
  2206. 
    
  2207.     This defaults to :class:`~django.forms.models.BaseInlineFormSet`. Using
    
  2208.     your own formset can give you many possibilities of customization. Inlines
    
  2209.     are built around :ref:`model formsets <model-formsets>`.
    
  2210. 
    
  2211. .. attribute:: InlineModelAdmin.form
    
  2212. 
    
  2213.     The value for ``form`` defaults to ``ModelForm``. This is what is passed
    
  2214.     through to :func:`~django.forms.models.inlineformset_factory` when
    
  2215.     creating the formset for this inline.
    
  2216. 
    
  2217. .. warning::
    
  2218.     When writing custom validation for ``InlineModelAdmin`` forms, be cautious
    
  2219.     of writing validation that relies on features of the parent model. If the
    
  2220.     parent model fails to validate, it may be left in an inconsistent state as
    
  2221.     described in the warning in :ref:`validation-on-modelform`.
    
  2222. 
    
  2223. .. attribute:: InlineModelAdmin.classes
    
  2224. 
    
  2225.     A list or tuple containing extra CSS classes to apply to the fieldset that
    
  2226.     is rendered for the inlines. Defaults to ``None``. As with classes
    
  2227.     configured in :attr:`~ModelAdmin.fieldsets`, inlines with a ``collapse``
    
  2228.     class will be initially collapsed and their header will have a small "show"
    
  2229.     link.
    
  2230. 
    
  2231. .. attribute:: InlineModelAdmin.extra
    
  2232. 
    
  2233.     This controls the number of extra forms the formset will display in
    
  2234.     addition to the initial forms. Defaults to 3. See the
    
  2235.     :doc:`formsets documentation </topics/forms/formsets>` for more
    
  2236.     information.
    
  2237. 
    
  2238.     For users with JavaScript-enabled browsers, an "Add another" link is
    
  2239.     provided to enable any number of additional inlines to be added in addition
    
  2240.     to those provided as a result of the ``extra`` argument.
    
  2241. 
    
  2242.     The dynamic link will not appear if the number of currently displayed forms
    
  2243.     exceeds ``max_num``, or if the user does not have JavaScript enabled.
    
  2244. 
    
  2245.     :meth:`InlineModelAdmin.get_extra` also allows you to customize the number
    
  2246.     of extra forms.
    
  2247. 
    
  2248. .. attribute:: InlineModelAdmin.max_num
    
  2249. 
    
  2250.     This controls the maximum number of forms to show in the inline. This
    
  2251.     doesn't directly correlate to the number of objects, but can if the value
    
  2252.     is small enough. See :ref:`model-formsets-max-num` for more information.
    
  2253. 
    
  2254.     :meth:`InlineModelAdmin.get_max_num` also allows you to customize the
    
  2255.     maximum number of extra forms.
    
  2256. 
    
  2257. .. attribute:: InlineModelAdmin.min_num
    
  2258. 
    
  2259.     This controls the minimum number of forms to show in the inline.
    
  2260.     See :func:`~django.forms.models.modelformset_factory` for more information.
    
  2261. 
    
  2262.     :meth:`InlineModelAdmin.get_min_num` also allows you to customize the
    
  2263.     minimum number of displayed forms.
    
  2264. 
    
  2265. .. attribute:: InlineModelAdmin.raw_id_fields
    
  2266. 
    
  2267.     By default, Django's admin uses a select-box interface (<select>) for
    
  2268.     fields that are ``ForeignKey``. Sometimes you don't want to incur the
    
  2269.     overhead of having to select all the related instances to display in the
    
  2270.     drop-down.
    
  2271. 
    
  2272.     ``raw_id_fields`` is a list of fields you would like to change into an
    
  2273.     ``Input`` widget for either a ``ForeignKey`` or ``ManyToManyField``::
    
  2274. 
    
  2275.         class BookInline(admin.TabularInline):
    
  2276.             model = Book
    
  2277.             raw_id_fields = ("pages",)
    
  2278. 
    
  2279. 
    
  2280. .. attribute:: InlineModelAdmin.template
    
  2281. 
    
  2282.     The template used to render the inline on the page.
    
  2283. 
    
  2284. .. attribute:: InlineModelAdmin.verbose_name
    
  2285. 
    
  2286.     An override to the :attr:`~django.db.models.Options.verbose_name` from the
    
  2287.     model's inner ``Meta`` class.
    
  2288. 
    
  2289. .. attribute:: InlineModelAdmin.verbose_name_plural
    
  2290. 
    
  2291.     An override to the :attr:`~django.db.models.Options.verbose_name_plural`
    
  2292.     from the model's inner ``Meta`` class. If this isn't given and the
    
  2293.     :attr:`.InlineModelAdmin.verbose_name` is defined, Django will use
    
  2294.     :attr:`.InlineModelAdmin.verbose_name` + ``'s'``.
    
  2295. 
    
  2296.     .. versionchanged:: 4.0
    
  2297. 
    
  2298.         The fallback to :attr:`.InlineModelAdmin.verbose_name` was added.
    
  2299. 
    
  2300. .. attribute:: InlineModelAdmin.can_delete
    
  2301. 
    
  2302.     Specifies whether or not inline objects can be deleted in the inline.
    
  2303.     Defaults to ``True``.
    
  2304. 
    
  2305. .. attribute:: InlineModelAdmin.show_change_link
    
  2306. 
    
  2307.     Specifies whether or not inline objects that can be changed in the
    
  2308.     admin have a link to the change form. Defaults to ``False``.
    
  2309. 
    
  2310. .. method:: InlineModelAdmin.get_formset(request, obj=None, **kwargs)
    
  2311. 
    
  2312.     Returns a :class:`~django.forms.models.BaseInlineFormSet` class for use in
    
  2313.     admin add/change views. ``obj`` is the parent object being edited or
    
  2314.     ``None`` when adding a new parent. See the example for
    
  2315.     :class:`ModelAdmin.get_formsets_with_inlines`.
    
  2316. 
    
  2317. .. method:: InlineModelAdmin.get_extra(request, obj=None, **kwargs)
    
  2318. 
    
  2319.     Returns the number of extra inline forms to use. By default, returns the
    
  2320.     :attr:`InlineModelAdmin.extra` attribute.
    
  2321. 
    
  2322.     Override this method to programmatically determine the number of extra
    
  2323.     inline forms. For example, this may be based on the model instance
    
  2324.     (passed as the keyword argument ``obj``)::
    
  2325. 
    
  2326.         class BinaryTreeAdmin(admin.TabularInline):
    
  2327.             model = BinaryTree
    
  2328. 
    
  2329.             def get_extra(self, request, obj=None, **kwargs):
    
  2330.                 extra = 2
    
  2331.                 if obj:
    
  2332.                     return extra - obj.binarytree_set.count()
    
  2333.                 return extra
    
  2334. 
    
  2335. .. method:: InlineModelAdmin.get_max_num(request, obj=None, **kwargs)
    
  2336. 
    
  2337.     Returns the maximum number of extra inline forms to use. By default,
    
  2338.     returns the :attr:`InlineModelAdmin.max_num` attribute.
    
  2339. 
    
  2340.     Override this method to programmatically determine the maximum number of
    
  2341.     inline forms. For example, this may be based on the model instance
    
  2342.     (passed as the keyword argument ``obj``)::
    
  2343. 
    
  2344.         class BinaryTreeAdmin(admin.TabularInline):
    
  2345.             model = BinaryTree
    
  2346. 
    
  2347.             def get_max_num(self, request, obj=None, **kwargs):
    
  2348.                 max_num = 10
    
  2349.                 if obj and obj.parent:
    
  2350.                     return max_num - 5
    
  2351.                 return max_num
    
  2352. 
    
  2353. .. method:: InlineModelAdmin.get_min_num(request, obj=None, **kwargs)
    
  2354. 
    
  2355.     Returns the minimum number of inline forms to use. By default,
    
  2356.     returns the :attr:`InlineModelAdmin.min_num` attribute.
    
  2357. 
    
  2358.     Override this method to programmatically determine the minimum number of
    
  2359.     inline forms. For example, this may be based on the model instance
    
  2360.     (passed as the keyword argument ``obj``).
    
  2361. 
    
  2362. .. method:: InlineModelAdmin.has_add_permission(request, obj)
    
  2363. 
    
  2364.     Should return ``True`` if adding an inline object is permitted, ``False``
    
  2365.     otherwise. ``obj`` is the parent object being edited or ``None`` when
    
  2366.     adding a new parent.
    
  2367. 
    
  2368. .. method:: InlineModelAdmin.has_change_permission(request, obj=None)
    
  2369. 
    
  2370.     Should return ``True`` if editing an inline object is permitted, ``False``
    
  2371.     otherwise. ``obj`` is the parent object being edited.
    
  2372. 
    
  2373. .. method:: InlineModelAdmin.has_delete_permission(request, obj=None)
    
  2374. 
    
  2375.     Should return ``True`` if deleting an inline object is permitted, ``False``
    
  2376.     otherwise. ``obj`` is the parent object being edited.
    
  2377. 
    
  2378. .. note::
    
  2379.     The ``obj`` argument passed to ``InlineModelAdmin`` methods is the parent
    
  2380.     object being edited or ``None`` when adding a new parent.
    
  2381. 
    
  2382. Working with a model with two or more foreign keys to the same parent model
    
  2383. ---------------------------------------------------------------------------
    
  2384. 
    
  2385. It is sometimes possible to have more than one foreign key to the same model.
    
  2386. Take this model for instance::
    
  2387. 
    
  2388.     from django.db import models
    
  2389. 
    
  2390.     class Friendship(models.Model):
    
  2391.         to_person = models.ForeignKey(Person, on_delete=models.CASCADE, related_name="friends")
    
  2392.         from_person = models.ForeignKey(Person, on_delete=models.CASCADE, related_name="from_friends")
    
  2393. 
    
  2394. If you wanted to display an inline on the ``Person`` admin add/change pages
    
  2395. you need to explicitly define the foreign key since it is unable to do so
    
  2396. automatically::
    
  2397. 
    
  2398.     from django.contrib import admin
    
  2399.     from myapp.models import Friendship
    
  2400. 
    
  2401.     class FriendshipInline(admin.TabularInline):
    
  2402.         model = Friendship
    
  2403.         fk_name = "to_person"
    
  2404. 
    
  2405.     class PersonAdmin(admin.ModelAdmin):
    
  2406.         inlines = [
    
  2407.             FriendshipInline,
    
  2408.         ]
    
  2409. 
    
  2410. Working with many-to-many models
    
  2411. --------------------------------
    
  2412. 
    
  2413. By default, admin widgets for many-to-many relations will be displayed
    
  2414. on whichever model contains the actual reference to the
    
  2415. :class:`~django.db.models.ManyToManyField`. Depending on your ``ModelAdmin``
    
  2416. definition, each many-to-many field in your model will be represented by a
    
  2417. standard HTML ``<select multiple>``, a horizontal or vertical filter, or a
    
  2418. ``raw_id_fields`` widget. However, it is also possible to replace these
    
  2419. widgets with inlines.
    
  2420. 
    
  2421. Suppose we have the following models::
    
  2422. 
    
  2423.     from django.db import models
    
  2424. 
    
  2425.     class Person(models.Model):
    
  2426.         name = models.CharField(max_length=128)
    
  2427. 
    
  2428.     class Group(models.Model):
    
  2429.         name = models.CharField(max_length=128)
    
  2430.         members = models.ManyToManyField(Person, related_name='groups')
    
  2431. 
    
  2432. If you want to display many-to-many relations using an inline, you can do
    
  2433. so by defining an ``InlineModelAdmin`` object for the relationship::
    
  2434. 
    
  2435.     from django.contrib import admin
    
  2436. 
    
  2437.     class MembershipInline(admin.TabularInline):
    
  2438.         model = Group.members.through
    
  2439. 
    
  2440.     class PersonAdmin(admin.ModelAdmin):
    
  2441.         inlines = [
    
  2442.             MembershipInline,
    
  2443.         ]
    
  2444. 
    
  2445.     class GroupAdmin(admin.ModelAdmin):
    
  2446.         inlines = [
    
  2447.             MembershipInline,
    
  2448.         ]
    
  2449.         exclude = ('members',)
    
  2450. 
    
  2451. There are two features worth noting in this example.
    
  2452. 
    
  2453. Firstly - the ``MembershipInline`` class references ``Group.members.through``.
    
  2454. The ``through`` attribute is a reference to the model that manages the
    
  2455. many-to-many relation. This model is automatically created by Django when you
    
  2456. define a many-to-many field.
    
  2457. 
    
  2458. Secondly, the ``GroupAdmin`` must manually exclude the ``members`` field.
    
  2459. Django displays an admin widget for a many-to-many field on the model that
    
  2460. defines the relation (in this case, ``Group``). If you want to use an inline
    
  2461. model to represent the many-to-many relationship, you must tell Django's admin
    
  2462. to *not* display this widget - otherwise you will end up with two widgets on
    
  2463. your admin page for managing the relation.
    
  2464. 
    
  2465. Note that when using this technique the
    
  2466. :data:`~django.db.models.signals.m2m_changed` signals aren't triggered. This
    
  2467. is because as far as the admin is concerned, ``through`` is just a model with
    
  2468. two foreign key fields rather than a many-to-many relation.
    
  2469. 
    
  2470. In all other respects, the ``InlineModelAdmin`` is exactly the same as any
    
  2471. other. You can customize the appearance using any of the normal
    
  2472. ``ModelAdmin`` properties.
    
  2473. 
    
  2474. Working with many-to-many intermediary models
    
  2475. ---------------------------------------------
    
  2476. 
    
  2477. When you specify an intermediary model using the ``through`` argument to a
    
  2478. :class:`~django.db.models.ManyToManyField`, the admin will not display a
    
  2479. widget by default. This is because each instance of that intermediary model
    
  2480. requires more information than could be displayed in a single widget, and the
    
  2481. layout required for multiple widgets will vary depending on the intermediate
    
  2482. model.
    
  2483. 
    
  2484. However, we still want to be able to edit that information inline. Fortunately,
    
  2485. we can do this with inline admin models. Suppose we have the following models::
    
  2486. 
    
  2487.     from django.db import models
    
  2488. 
    
  2489.     class Person(models.Model):
    
  2490.         name = models.CharField(max_length=128)
    
  2491. 
    
  2492.     class Group(models.Model):
    
  2493.         name = models.CharField(max_length=128)
    
  2494.         members = models.ManyToManyField(Person, through='Membership')
    
  2495. 
    
  2496.     class Membership(models.Model):
    
  2497.         person = models.ForeignKey(Person, on_delete=models.CASCADE)
    
  2498.         group = models.ForeignKey(Group, on_delete=models.CASCADE)
    
  2499.         date_joined = models.DateField()
    
  2500.         invite_reason = models.CharField(max_length=64)
    
  2501. 
    
  2502. The first step in displaying this intermediate model in the admin is to
    
  2503. define an inline class for the ``Membership`` model::
    
  2504. 
    
  2505.     class MembershipInline(admin.TabularInline):
    
  2506.         model = Membership
    
  2507.         extra = 1
    
  2508. 
    
  2509. This example uses the default ``InlineModelAdmin`` values for the
    
  2510. ``Membership`` model, and limits the extra add forms to one. This could be
    
  2511. customized using any of the options available to ``InlineModelAdmin`` classes.
    
  2512. 
    
  2513. Now create admin views for the ``Person`` and ``Group`` models::
    
  2514. 
    
  2515.     class PersonAdmin(admin.ModelAdmin):
    
  2516.         inlines = (MembershipInline,)
    
  2517. 
    
  2518.     class GroupAdmin(admin.ModelAdmin):
    
  2519.         inlines = (MembershipInline,)
    
  2520. 
    
  2521. Finally, register your ``Person`` and ``Group`` models with the admin site::
    
  2522. 
    
  2523.     admin.site.register(Person, PersonAdmin)
    
  2524.     admin.site.register(Group, GroupAdmin)
    
  2525. 
    
  2526. Now your admin site is set up to edit ``Membership`` objects inline from
    
  2527. either the ``Person`` or the ``Group`` detail pages.
    
  2528. 
    
  2529. .. _using-generic-relations-as-an-inline:
    
  2530. 
    
  2531. Using generic relations as an inline
    
  2532. ------------------------------------
    
  2533. 
    
  2534. It is possible to use an inline with generically related objects. Let's say
    
  2535. you have the following models::
    
  2536. 
    
  2537.     from django.contrib.contenttypes.fields import GenericForeignKey
    
  2538.     from django.db import models
    
  2539. 
    
  2540.     class Image(models.Model):
    
  2541.         image = models.ImageField(upload_to="images")
    
  2542.         content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    
  2543.         object_id = models.PositiveIntegerField()
    
  2544.         content_object = GenericForeignKey("content_type", "object_id")
    
  2545. 
    
  2546.     class Product(models.Model):
    
  2547.         name = models.CharField(max_length=100)
    
  2548. 
    
  2549. If you want to allow editing and creating an ``Image`` instance on the
    
  2550. ``Product``, add/change views you can use
    
  2551. :class:`~django.contrib.contenttypes.admin.GenericTabularInline`
    
  2552. or :class:`~django.contrib.contenttypes.admin.GenericStackedInline` (both
    
  2553. subclasses of :class:`~django.contrib.contenttypes.admin.GenericInlineModelAdmin`)
    
  2554. provided by :mod:`~django.contrib.contenttypes.admin`. They implement tabular
    
  2555. and stacked visual layouts for the forms representing the inline objects,
    
  2556. respectively, just like their non-generic counterparts. They behave just like
    
  2557. any other inline. In your ``admin.py`` for this example app::
    
  2558. 
    
  2559.     from django.contrib import admin
    
  2560.     from django.contrib.contenttypes.admin import GenericTabularInline
    
  2561. 
    
  2562.     from myapp.models import Image, Product
    
  2563. 
    
  2564.     class ImageInline(GenericTabularInline):
    
  2565.         model = Image
    
  2566. 
    
  2567.     class ProductAdmin(admin.ModelAdmin):
    
  2568.         inlines = [
    
  2569.             ImageInline,
    
  2570.         ]
    
  2571. 
    
  2572.     admin.site.register(Product, ProductAdmin)
    
  2573. 
    
  2574. See the :doc:`contenttypes documentation </ref/contrib/contenttypes>` for more
    
  2575. specific information.
    
  2576. 
    
  2577. .. _admin-overriding-templates:
    
  2578. 
    
  2579. Overriding admin templates
    
  2580. ==========================
    
  2581. 
    
  2582. You can override many of the templates which the admin module uses to generate
    
  2583. the various pages of an admin site. You can even override a few of these
    
  2584. templates for a specific app, or a specific model.
    
  2585. 
    
  2586. Set up your projects admin template directories
    
  2587. -----------------------------------------------
    
  2588. 
    
  2589. The admin template files are located in the ``contrib/admin/templates/admin``
    
  2590. directory.
    
  2591. 
    
  2592. In order to override one or more of them, first create an ``admin`` directory
    
  2593. in your project's ``templates`` directory. This can be any of the directories
    
  2594. you specified in the :setting:`DIRS <TEMPLATES-DIRS>` option of the
    
  2595. ``DjangoTemplates`` backend in the :setting:`TEMPLATES` setting. If you have
    
  2596. customized the ``'loaders'`` option, be sure
    
  2597. ``'django.template.loaders.filesystem.Loader'`` appears before
    
  2598. ``'django.template.loaders.app_directories.Loader'`` so that your custom
    
  2599. templates will be found by the template loading system before those that are
    
  2600. included with :mod:`django.contrib.admin`.
    
  2601. 
    
  2602. Within this ``admin`` directory, create sub-directories named after your app.
    
  2603. Within these app subdirectories create sub-directories named after your models.
    
  2604. Note, that the admin app will lowercase the model name when looking for the
    
  2605. directory, so make sure you name the directory in all lowercase if you are
    
  2606. going to run your app on a case-sensitive filesystem.
    
  2607. 
    
  2608. To override an admin template for a specific app, copy and edit the template
    
  2609. from the ``django/contrib/admin/templates/admin`` directory, and save it to one
    
  2610. of the directories you just created.
    
  2611. 
    
  2612. For example, if we wanted to add a tool to the change list view for all the
    
  2613. models in an app named ``my_app``, we would copy
    
  2614. ``contrib/admin/templates/admin/change_list.html`` to the
    
  2615. ``templates/admin/my_app/`` directory of our project, and make any necessary
    
  2616. changes.
    
  2617. 
    
  2618. If we wanted to add a tool to the change list view for only a specific model
    
  2619. named 'Page', we would copy that same file to the
    
  2620. ``templates/admin/my_app/page`` directory of our project.
    
  2621. 
    
  2622. Overriding vs. replacing an admin template
    
  2623. ------------------------------------------
    
  2624. 
    
  2625. Because of the modular design of the admin templates, it is usually neither
    
  2626. necessary nor advisable to replace an entire template. It is almost always
    
  2627. better to override only the section of the template which you need to change.
    
  2628. 
    
  2629. To continue the example above, we want to add a new link next to the
    
  2630. ``History`` tool for the ``Page`` model. After looking at ``change_form.html``
    
  2631. we determine that we only need to override the ``object-tools-items`` block.
    
  2632. Therefore here is our new ``change_form.html`` :
    
  2633. 
    
  2634. .. code-block:: html+django
    
  2635. 
    
  2636.     {% extends "admin/change_form.html" %}
    
  2637.     {% load i18n admin_urls %}
    
  2638.     {% block object-tools-items %}
    
  2639.         <li>
    
  2640.             <a href="{% url opts|admin_urlname:'history' original.pk|admin_urlquote %}" class="historylink">{% translate "History" %}</a>
    
  2641.         </li>
    
  2642.         <li>
    
  2643.             <a href="mylink/" class="historylink">My Link</a>
    
  2644.         </li>
    
  2645.         {% if has_absolute_url %}
    
  2646.             <li>
    
  2647.                 <a href="{% url 'admin:view_on_site' content_type_id original.pk %}" class="viewsitelink">{% translate "View on site" %}</a>
    
  2648.             </li>
    
  2649.         {% endif %}
    
  2650.     {% endblock %}
    
  2651. 
    
  2652. And that's it! If we placed this file in the ``templates/admin/my_app``
    
  2653. directory, our link would appear on the change form for all models within
    
  2654. my_app.
    
  2655. 
    
  2656. .. _admin-templates-overridden-per-app-or-model:
    
  2657. 
    
  2658. Templates which may be overridden per app or model
    
  2659. --------------------------------------------------
    
  2660. 
    
  2661. Not every template in ``contrib/admin/templates/admin`` may be overridden per
    
  2662. app or per model. The following can:
    
  2663. 
    
  2664. * ``actions.html``
    
  2665. * ``app_index.html``
    
  2666. * ``change_form.html``
    
  2667. * ``change_form_object_tools.html``
    
  2668. * ``change_list.html``
    
  2669. * ``change_list_object_tools.html``
    
  2670. * ``change_list_results.html``
    
  2671. * ``date_hierarchy.html``
    
  2672. * ``delete_confirmation.html``
    
  2673. * ``object_history.html``
    
  2674. * ``pagination.html``
    
  2675. * ``popup_response.html``
    
  2676. * ``prepopulated_fields_js.html``
    
  2677. * ``search_form.html``
    
  2678. * ``submit_line.html``
    
  2679. 
    
  2680. For those templates that cannot be overridden in this way, you may still
    
  2681. override them for your entire project by placing the new version in your
    
  2682. ``templates/admin`` directory. This is particularly useful to create custom 404
    
  2683. and 500 pages.
    
  2684. 
    
  2685. .. note::
    
  2686. 
    
  2687.     Some of the admin templates, such as ``change_list_results.html`` are used
    
  2688.     to render custom inclusion tags. These may be overridden, but in such cases
    
  2689.     you are probably better off creating your own version of the tag in
    
  2690.     question and giving it a different name. That way you can use it
    
  2691.     selectively.
    
  2692. 
    
  2693. Root and login templates
    
  2694. ------------------------
    
  2695. 
    
  2696. If you wish to change the index, login or logout templates, you are better off
    
  2697. creating your own ``AdminSite`` instance (see below), and changing the
    
  2698. :attr:`AdminSite.index_template` , :attr:`AdminSite.login_template` or
    
  2699. :attr:`AdminSite.logout_template` properties.
    
  2700. 
    
  2701. .. _admin-theming:
    
  2702. 
    
  2703. Theming support
    
  2704. ===============
    
  2705. 
    
  2706. The admin uses CSS variables to define colors. This allows changing colors
    
  2707. without having to override many individual CSS rules. For example, if you
    
  2708. preferred purple instead of blue you could add a ``admin/base.html`` template
    
  2709. override to your project:
    
  2710. 
    
  2711. .. code-block:: html+django
    
  2712. 
    
  2713.     {% extends 'admin/base.html' %}
    
  2714. 
    
  2715.     {% block extrastyle %}{{ block.super }}
    
  2716.     <style>
    
  2717.     :root {
    
  2718.       --primary: #9774d5;
    
  2719.       --secondary: #785cab;
    
  2720.       --link-fg: #7c449b;
    
  2721.       --link-selected-fg: #8f5bb2;
    
  2722.     }
    
  2723.     </style>
    
  2724.     {% endblock %}
    
  2725. 
    
  2726. The list of CSS variables are defined at
    
  2727. :file:`django/contrib/admin/static/admin/css/base.css`.
    
  2728. 
    
  2729. Dark mode variables, respecting the `prefers-color-scheme`_ media query, are
    
  2730. defined at :file:`django/contrib/admin/static/admin/css/dark_mode.css`. This is
    
  2731. linked to the document in ``{% block dark-mode-vars %}``.
    
  2732. 
    
  2733. .. _prefers-color-scheme: https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme
    
  2734. 
    
  2735. .. versionchanged:: 4.1
    
  2736. 
    
  2737.     The dark mode variables were moved to a separate stylesheet and template
    
  2738.     block.
    
  2739. 
    
  2740. ``AdminSite`` objects
    
  2741. =====================
    
  2742. 
    
  2743. .. class:: AdminSite(name='admin')
    
  2744. 
    
  2745.     A Django administrative site is represented by an instance of
    
  2746.     ``django.contrib.admin.sites.AdminSite``; by default, an instance of
    
  2747.     this class is created as ``django.contrib.admin.site`` and you can
    
  2748.     register your models and ``ModelAdmin`` instances with it.
    
  2749. 
    
  2750.     If you want to customize the default admin site, you can :ref:`override it
    
  2751.     <overriding-default-admin-site>`.
    
  2752. 
    
  2753.     When constructing an instance of an ``AdminSite``, you can provide
    
  2754.     a unique instance name using the ``name`` argument to the constructor. This
    
  2755.     instance name is used to identify the instance, especially when
    
  2756.     :ref:`reversing admin URLs <admin-reverse-urls>`. If no instance name is
    
  2757.     provided, a default instance name of ``admin`` will be used.
    
  2758.     See :ref:`customizing-adminsite` for an example of customizing the
    
  2759.     :class:`AdminSite` class.
    
  2760. 
    
  2761. ``AdminSite`` attributes
    
  2762. ------------------------
    
  2763. 
    
  2764. Templates can override or extend base admin templates as described in
    
  2765. :ref:`admin-overriding-templates`.
    
  2766. 
    
  2767. .. attribute:: AdminSite.site_header
    
  2768. 
    
  2769.     The text to put at the top of each admin page, as an ``<h1>`` (a string).
    
  2770.     By default, this is "Django administration".
    
  2771. 
    
  2772. .. attribute:: AdminSite.site_title
    
  2773. 
    
  2774.     The text to put at the end of each admin page's ``<title>`` (a string). By
    
  2775.     default, this is "Django site admin".
    
  2776. 
    
  2777. .. attribute:: AdminSite.site_url
    
  2778. 
    
  2779.     The URL for the "View site" link at the top of each admin page. By default,
    
  2780.     ``site_url`` is ``/``. Set it to ``None`` to remove the link.
    
  2781. 
    
  2782.     For sites running on a subpath, the :meth:`each_context` method checks if
    
  2783.     the current request has ``request.META['SCRIPT_NAME']`` set and uses that
    
  2784.     value if ``site_url`` isn't set to something other than ``/``.
    
  2785. 
    
  2786. .. attribute:: AdminSite.index_title
    
  2787. 
    
  2788.     The text to put at the top of the admin index page (a string). By default,
    
  2789.     this is "Site administration".
    
  2790. 
    
  2791. .. attribute:: AdminSite.index_template
    
  2792. 
    
  2793.     Path to a custom template that will be used by the admin site main index
    
  2794.     view.
    
  2795. 
    
  2796. .. attribute:: AdminSite.app_index_template
    
  2797. 
    
  2798.     Path to a custom template that will be used by the admin site app index view.
    
  2799. 
    
  2800. .. attribute:: AdminSite.empty_value_display
    
  2801. 
    
  2802.     The string to use for displaying empty values in the admin site's change
    
  2803.     list. Defaults to a dash. The value can also be overridden on a per
    
  2804.     ``ModelAdmin`` basis and on a custom field within a ``ModelAdmin`` by
    
  2805.     setting an ``empty_value_display`` attribute on the field. See
    
  2806.     :attr:`ModelAdmin.empty_value_display` for examples.
    
  2807. 
    
  2808. .. attribute:: AdminSite.enable_nav_sidebar
    
  2809. 
    
  2810.     A boolean value that determines whether to show the navigation sidebar
    
  2811.     on larger screens. By default, it is set to ``True``.
    
  2812. 
    
  2813. .. attribute:: AdminSite.final_catch_all_view
    
  2814. 
    
  2815.     A boolean value that determines whether to add a final catch-all view to
    
  2816.     the admin that redirects unauthenticated users to the login page. By
    
  2817.     default, it is set to ``True``.
    
  2818. 
    
  2819.     .. warning::
    
  2820. 
    
  2821.         Setting this to ``False`` is not recommended as the view protects
    
  2822.         against a potential model enumeration privacy issue.
    
  2823. 
    
  2824. .. attribute:: AdminSite.login_template
    
  2825. 
    
  2826.     Path to a custom template that will be used by the admin site login view.
    
  2827. 
    
  2828. .. attribute:: AdminSite.login_form
    
  2829. 
    
  2830.     Subclass of :class:`~django.contrib.auth.forms.AuthenticationForm` that
    
  2831.     will be used by the admin site login view.
    
  2832. 
    
  2833. .. attribute:: AdminSite.logout_template
    
  2834. 
    
  2835.     Path to a custom template that will be used by the admin site logout view.
    
  2836. 
    
  2837. .. attribute:: AdminSite.password_change_template
    
  2838. 
    
  2839.     Path to a custom template that will be used by the admin site password
    
  2840.     change view.
    
  2841. 
    
  2842. .. attribute:: AdminSite.password_change_done_template
    
  2843. 
    
  2844.     Path to a custom template that will be used by the admin site password
    
  2845.     change done view.
    
  2846. 
    
  2847. ``AdminSite`` methods
    
  2848. ---------------------
    
  2849. 
    
  2850. .. method:: AdminSite.each_context(request)
    
  2851. 
    
  2852.     Returns a dictionary of variables to put in the template context for
    
  2853.     every page in the admin site.
    
  2854. 
    
  2855.     Includes the following variables and values by default:
    
  2856. 
    
  2857.     * ``site_header``: :attr:`AdminSite.site_header`
    
  2858.     * ``site_title``: :attr:`AdminSite.site_title`
    
  2859.     * ``site_url``: :attr:`AdminSite.site_url`
    
  2860.     * ``has_permission``: :meth:`AdminSite.has_permission`
    
  2861.     * ``available_apps``: a list of applications from the :doc:`application registry
    
  2862.       </ref/applications/>` available for the current user. Each entry in the
    
  2863.       list is a dict representing an application with the following keys:
    
  2864. 
    
  2865.       * ``app_label``: the application label
    
  2866.       * ``app_url``: the URL of the application index in the admin
    
  2867.       * ``has_module_perms``: a boolean indicating if displaying and accessing of
    
  2868.         the module's index page is permitted for the current user
    
  2869.       * ``models``: a list of the models available in the application
    
  2870. 
    
  2871.       Each model is a dict with the following keys:
    
  2872. 
    
  2873.       * ``model``: the model class
    
  2874.       * ``object_name``: class name of the model
    
  2875.       * ``name``: plural name of the model
    
  2876.       * ``perms``: a ``dict`` tracking ``add``, ``change``, ``delete``, and
    
  2877.         ``view`` permissions
    
  2878.       * ``admin_url``: admin changelist URL for the model
    
  2879.       * ``add_url``: admin URL to add a new model instance
    
  2880. 
    
  2881.     .. versionchanged:: 4.0
    
  2882. 
    
  2883.         The ``model`` variable for each model was added.
    
  2884. 
    
  2885. .. method:: AdminSite.get_app_list(request, app_label=None)
    
  2886. 
    
  2887.     Returns a list of applications from the :doc:`application registry
    
  2888.     </ref/applications/>` available for the current user. You can optionally
    
  2889.     pass an ``app_label`` argument to get details for a single app. Each entry
    
  2890.     in the list is a dictionary representing an application with the following
    
  2891.     keys:
    
  2892. 
    
  2893.     * ``app_label``: the application label
    
  2894.     * ``app_url``: the URL of the application index in the admin
    
  2895.     * ``has_module_perms``: a boolean indicating if displaying and accessing of
    
  2896.       the module's index page is permitted for the current user
    
  2897.     * ``models``: a list of the models available in the application
    
  2898.     * ``name``: name of the application
    
  2899. 
    
  2900.     Each model is a dictionary with the following keys:
    
  2901. 
    
  2902.     * ``model``: the model class
    
  2903.     * ``object_name``: class name of the model
    
  2904.     * ``name``: plural name of the model
    
  2905.     * ``perms``: a ``dict`` tracking ``add``, ``change``, ``delete``, and
    
  2906.       ``view`` permissions
    
  2907.     * ``admin_url``: admin changelist URL for the model
    
  2908.     * ``add_url``: admin URL to add a new model instance
    
  2909. 
    
  2910.     Lists of applications and models are sorted alphabetically by their names.
    
  2911.     You can override this method to change the default order on the admin index
    
  2912.     page.
    
  2913. 
    
  2914.     .. versionchanged:: 4.1
    
  2915. 
    
  2916.         The ``app_label`` argument was added.
    
  2917. 
    
  2918. .. method:: AdminSite.has_permission(request)
    
  2919. 
    
  2920.     Returns ``True`` if the user for the given ``HttpRequest`` has permission
    
  2921.     to view at least one page in the admin site. Defaults to requiring both
    
  2922.     :attr:`User.is_active <django.contrib.auth.models.User.is_active>` and
    
  2923.     :attr:`User.is_staff <django.contrib.auth.models.User.is_staff>` to be
    
  2924.     ``True``.
    
  2925. 
    
  2926. .. method:: AdminSite.register(model_or_iterable, admin_class=None, **options)
    
  2927. 
    
  2928.     Registers the given model class (or iterable of classes) with the given
    
  2929.     ``admin_class``. ``admin_class`` defaults to
    
  2930.     :class:`~django.contrib.admin.ModelAdmin` (the default admin options). If
    
  2931.     keyword arguments are given -- e.g. ``list_display`` -- they'll be applied
    
  2932.     as options to the admin class.
    
  2933. 
    
  2934.     Raises :class:`~django.core.exceptions.ImproperlyConfigured` if a model is
    
  2935.     abstract. and ``django.contrib.admin.sites.AlreadyRegistered`` if a model
    
  2936.     is already registered.
    
  2937. 
    
  2938. .. method:: AdminSite.unregister(model_or_iterable)
    
  2939. 
    
  2940.     Unregisters the given model class (or iterable of classes).
    
  2941. 
    
  2942.     Raises ``django.contrib.admin.sites.NotRegistered`` if a model isn't
    
  2943.     already registered.
    
  2944. 
    
  2945. .. _hooking-adminsite-to-urlconf:
    
  2946. 
    
  2947. Hooking ``AdminSite`` instances into your URLconf
    
  2948. -------------------------------------------------
    
  2949. 
    
  2950. The last step in setting up the Django admin is to hook your ``AdminSite``
    
  2951. instance into your URLconf. Do this by pointing a given URL at the
    
  2952. ``AdminSite.urls`` method. It is not necessary to use
    
  2953. :func:`~django.urls.include()`.
    
  2954. 
    
  2955. In this example, we register the default ``AdminSite`` instance
    
  2956. ``django.contrib.admin.site`` at the URL ``/admin/`` ::
    
  2957. 
    
  2958.     # urls.py
    
  2959.     from django.contrib import admin
    
  2960.     from django.urls import path
    
  2961. 
    
  2962.     urlpatterns = [
    
  2963.         path('admin/', admin.site.urls),
    
  2964.     ]
    
  2965. 
    
  2966. .. _customizing-adminsite:
    
  2967. 
    
  2968. Customizing the :class:`AdminSite` class
    
  2969. ----------------------------------------
    
  2970. 
    
  2971. If you'd like to set up your own admin site with custom behavior, you're free
    
  2972. to subclass ``AdminSite`` and override or add anything you like. Then, create
    
  2973. an instance of your ``AdminSite`` subclass (the same way you'd instantiate any
    
  2974. other Python class) and register your models and ``ModelAdmin`` subclasses with
    
  2975. it instead of with the default site. Finally, update :file:`myproject/urls.py`
    
  2976. to reference your :class:`AdminSite` subclass.
    
  2977. 
    
  2978. .. code-block:: python
    
  2979.     :caption: ``myapp/admin.py``
    
  2980. 
    
  2981.     from django.contrib import admin
    
  2982. 
    
  2983.     from .models import MyModel
    
  2984. 
    
  2985.     class MyAdminSite(admin.AdminSite):
    
  2986.         site_header = 'Monty Python administration'
    
  2987. 
    
  2988.     admin_site = MyAdminSite(name='myadmin')
    
  2989.     admin_site.register(MyModel)
    
  2990. 
    
  2991. 
    
  2992. .. code-block:: python
    
  2993.     :caption: ``myproject/urls.py``
    
  2994. 
    
  2995.     from django.urls import path
    
  2996. 
    
  2997.     from myapp.admin import admin_site
    
  2998. 
    
  2999.     urlpatterns = [
    
  3000.         path('myadmin/', admin_site.urls),
    
  3001.     ]
    
  3002. 
    
  3003. Note that you may not want autodiscovery of ``admin`` modules when using your
    
  3004. own ``AdminSite`` instance since you will likely be importing all the per-app
    
  3005. ``admin`` modules in your ``myproject.admin`` module. This means you need to
    
  3006. put ``'django.contrib.admin.apps.SimpleAdminConfig'`` instead of
    
  3007. ``'django.contrib.admin'`` in your :setting:`INSTALLED_APPS` setting.
    
  3008. 
    
  3009. .. _overriding-default-admin-site:
    
  3010. 
    
  3011. Overriding the default admin site
    
  3012. ---------------------------------
    
  3013. 
    
  3014. You can override the default ``django.contrib.admin.site`` by setting the
    
  3015. :attr:`~.SimpleAdminConfig.default_site` attribute of a custom ``AppConfig``
    
  3016. to the dotted import path of either a ``AdminSite`` subclass or a callable that
    
  3017. returns a site instance.
    
  3018. 
    
  3019. .. code-block:: python
    
  3020.     :caption: ``myproject/admin.py``
    
  3021. 
    
  3022.     from django.contrib import admin
    
  3023. 
    
  3024.     class MyAdminSite(admin.AdminSite):
    
  3025.         ...
    
  3026. 
    
  3027. .. code-block:: python
    
  3028.     :caption: ``myproject/apps.py``
    
  3029. 
    
  3030.     from django.contrib.admin.apps import AdminConfig
    
  3031. 
    
  3032.     class MyAdminConfig(AdminConfig):
    
  3033.         default_site = 'myproject.admin.MyAdminSite'
    
  3034. 
    
  3035. .. code-block:: python
    
  3036.     :caption: ``myproject/settings.py``
    
  3037. 
    
  3038.     INSTALLED_APPS = [
    
  3039.         ...
    
  3040.         'myproject.apps.MyAdminConfig',  # replaces 'django.contrib.admin'
    
  3041.         ...
    
  3042.     ]
    
  3043. 
    
  3044. .. _multiple-admin-sites:
    
  3045. 
    
  3046. Multiple admin sites in the same URLconf
    
  3047. ----------------------------------------
    
  3048. 
    
  3049. You can create multiple instances of the admin site on the same Django-powered
    
  3050. website. Create multiple instances of ``AdminSite`` and place each one at a
    
  3051. different URL.
    
  3052. 
    
  3053. In this example, the URLs ``/basic-admin/`` and ``/advanced-admin/`` feature
    
  3054. separate versions of the admin site -- using the ``AdminSite`` instances
    
  3055. ``myproject.admin.basic_site`` and ``myproject.admin.advanced_site``,
    
  3056. respectively::
    
  3057. 
    
  3058.     # urls.py
    
  3059.     from django.urls import path
    
  3060.     from myproject.admin import advanced_site, basic_site
    
  3061. 
    
  3062.     urlpatterns = [
    
  3063.         path('basic-admin/', basic_site.urls),
    
  3064.         path('advanced-admin/', advanced_site.urls),
    
  3065.     ]
    
  3066. 
    
  3067. ``AdminSite`` instances take a single argument to their constructor, their
    
  3068. name, which can be anything you like. This argument becomes the prefix to the
    
  3069. URL names for the purposes of :ref:`reversing them<admin-reverse-urls>`. This
    
  3070. is only necessary if you are using more than one ``AdminSite``.
    
  3071. 
    
  3072. Adding views to admin sites
    
  3073. ---------------------------
    
  3074. 
    
  3075. Just like :class:`ModelAdmin`, :class:`AdminSite` provides a
    
  3076. :meth:`~django.contrib.admin.ModelAdmin.get_urls()` method
    
  3077. that can be overridden to define additional views for the site. To add
    
  3078. a new view to your admin site, extend the base
    
  3079. :meth:`~django.contrib.admin.ModelAdmin.get_urls()` method to include
    
  3080. a pattern for your new view.
    
  3081. 
    
  3082. .. note::
    
  3083. 
    
  3084.     Any view you render that uses the admin templates, or extends the base
    
  3085.     admin template, should set ``request.current_app`` before rendering the
    
  3086.     template. It should be set to either ``self.name`` if your view is on an
    
  3087.     ``AdminSite`` or ``self.admin_site.name`` if your view is on a
    
  3088.     ``ModelAdmin``.
    
  3089. 
    
  3090. .. _auth_password_reset:
    
  3091. 
    
  3092. Adding a password reset feature
    
  3093. -------------------------------
    
  3094. 
    
  3095. You can add a password reset feature to the admin site by adding a few lines to
    
  3096. your URLconf. Specifically, add these four patterns::
    
  3097. 
    
  3098.     from django.contrib.auth import views as auth_views
    
  3099. 
    
  3100.     path(
    
  3101.         'admin/password_reset/',
    
  3102.         auth_views.PasswordResetView.as_view(),
    
  3103.         name='admin_password_reset',
    
  3104.     ),
    
  3105.     path(
    
  3106.         'admin/password_reset/done/',
    
  3107.         auth_views.PasswordResetDoneView.as_view(),
    
  3108.         name='password_reset_done',
    
  3109.     ),
    
  3110.     path(
    
  3111.         'reset/<uidb64>/<token>/',
    
  3112.         auth_views.PasswordResetConfirmView.as_view(),
    
  3113.         name='password_reset_confirm',
    
  3114.     ),
    
  3115.     path(
    
  3116.         'reset/done/',
    
  3117.         auth_views.PasswordResetCompleteView.as_view(),
    
  3118.         name='password_reset_complete',
    
  3119.     ),
    
  3120. 
    
  3121. (This assumes you've added the admin at ``admin/`` and requires that you put
    
  3122. the URLs starting with ``^admin/`` before the line that includes the admin app
    
  3123. itself).
    
  3124. 
    
  3125. The presence of the ``admin_password_reset`` named URL will cause a "forgotten
    
  3126. your password?" link to appear on the default admin log-in page under the
    
  3127. password box.
    
  3128. 
    
  3129. ``LogEntry`` objects
    
  3130. ====================
    
  3131. 
    
  3132. .. class:: models.LogEntry
    
  3133. 
    
  3134.     The ``LogEntry`` class tracks additions, changes, and deletions of objects
    
  3135.     done through the admin interface.
    
  3136. 
    
  3137. .. currentmodule:: django.contrib.admin.models
    
  3138. 
    
  3139. ``LogEntry`` attributes
    
  3140. -----------------------
    
  3141. 
    
  3142. .. attribute:: LogEntry.action_time
    
  3143. 
    
  3144.     The date and time of the action.
    
  3145. 
    
  3146. .. attribute:: LogEntry.user
    
  3147. 
    
  3148.     The user (an :setting:`AUTH_USER_MODEL` instance) who performed the
    
  3149.     action.
    
  3150. 
    
  3151. .. attribute:: LogEntry.content_type
    
  3152. 
    
  3153.     The :class:`~django.contrib.contenttypes.models.ContentType` of the
    
  3154.     modified object.
    
  3155. 
    
  3156. .. attribute:: LogEntry.object_id
    
  3157. 
    
  3158.     The textual representation of the modified object's primary key.
    
  3159. 
    
  3160. .. attribute:: LogEntry.object_repr
    
  3161. 
    
  3162.     The object`s ``repr()`` after the modification.
    
  3163. 
    
  3164. .. attribute:: LogEntry.action_flag
    
  3165. 
    
  3166.     The type of action logged: ``ADDITION``, ``CHANGE``, ``DELETION``.
    
  3167. 
    
  3168.     For example, to get a list of all additions done through the admin::
    
  3169. 
    
  3170.         from django.contrib.admin.models import ADDITION, LogEntry
    
  3171. 
    
  3172.         LogEntry.objects.filter(action_flag=ADDITION)
    
  3173. 
    
  3174. .. attribute:: LogEntry.change_message
    
  3175. 
    
  3176.     The detailed description of the modification. In the case of an edit, for
    
  3177.     example, the message contains a list of the edited fields. The Django admin
    
  3178.     site formats this content as a JSON structure, so that
    
  3179.     :meth:`get_change_message` can recompose a message translated in the current
    
  3180.     user language. Custom code might set this as a plain string though. You are
    
  3181.     advised to use the :meth:`get_change_message` method to retrieve this value
    
  3182.     instead of accessing it directly.
    
  3183. 
    
  3184. ``LogEntry`` methods
    
  3185. --------------------
    
  3186. 
    
  3187. .. method:: LogEntry.get_edited_object()
    
  3188. 
    
  3189.     A shortcut that returns the referenced object.
    
  3190. 
    
  3191. .. method:: LogEntry.get_change_message()
    
  3192. 
    
  3193.     Formats and translates :attr:`change_message` into the current user
    
  3194.     language. Messages created before Django 1.10 will always be displayed in
    
  3195.     the language in which they were logged.
    
  3196. 
    
  3197. .. currentmodule:: django.contrib.admin
    
  3198. 
    
  3199. .. _admin-reverse-urls:
    
  3200. 
    
  3201. Reversing admin URLs
    
  3202. ====================
    
  3203. 
    
  3204. When an :class:`AdminSite` is deployed, the views provided by that site are
    
  3205. accessible using Django's :ref:`URL reversing system <naming-url-patterns>`.
    
  3206. 
    
  3207. The :class:`AdminSite` provides the following named URL patterns:
    
  3208. 
    
  3209. =========================  ========================  ==================================
    
  3210. Page                       URL name                  Parameters
    
  3211. =========================  ========================  ==================================
    
  3212. Index                      ``index``
    
  3213. Login                      ``login``
    
  3214. Logout                     ``logout``
    
  3215. Password change            ``password_change``
    
  3216. Password change done       ``password_change_done``
    
  3217. i18n JavaScript            ``jsi18n``
    
  3218. Application index page     ``app_list``              ``app_label``
    
  3219. Redirect to object's page  ``view_on_site``          ``content_type_id``, ``object_id``
    
  3220. =========================  ========================  ==================================
    
  3221. 
    
  3222. Each :class:`ModelAdmin` instance provides an additional set of named URLs:
    
  3223. 
    
  3224. ======================  ===============================================   =============
    
  3225. Page                    URL name                                          Parameters
    
  3226. ======================  ===============================================   =============
    
  3227. Changelist              ``{{ app_label }}_{{ model_name }}_changelist``
    
  3228. Add                     ``{{ app_label }}_{{ model_name }}_add``
    
  3229. History                 ``{{ app_label }}_{{ model_name }}_history``      ``object_id``
    
  3230. Delete                  ``{{ app_label }}_{{ model_name }}_delete``       ``object_id``
    
  3231. Change                  ``{{ app_label }}_{{ model_name }}_change``       ``object_id``
    
  3232. ======================  ===============================================   =============
    
  3233. 
    
  3234. The ``UserAdmin`` provides a named URL:
    
  3235. 
    
  3236. ======================  ===============================================   =============
    
  3237. Page                    URL name                                          Parameters
    
  3238. ======================  ===============================================   =============
    
  3239. Password change         ``auth_user_password_change``                     ``user_id``
    
  3240. ======================  ===============================================   =============
    
  3241. 
    
  3242. These named URLs are registered with the application namespace ``admin``, and
    
  3243. with an instance namespace corresponding to the name of the Site instance.
    
  3244. 
    
  3245. So - if you wanted to get a reference to the Change view for a particular
    
  3246. ``Choice`` object (from the polls application) in the default admin, you would
    
  3247. call::
    
  3248. 
    
  3249.     >>> from django.urls import reverse
    
  3250.     >>> c = Choice.objects.get(...)
    
  3251.     >>> change_url = reverse('admin:polls_choice_change', args=(c.id,))
    
  3252. 
    
  3253. This will find the first registered instance of the admin application
    
  3254. (whatever the instance name), and resolve to the view for changing
    
  3255. ``poll.Choice`` instances in that instance.
    
  3256. 
    
  3257. If you want to find a URL in a specific admin instance, provide the name of
    
  3258. that instance as a ``current_app`` hint to the reverse call. For example,
    
  3259. if you specifically wanted the admin view from the admin instance named
    
  3260. ``custom``, you would need to call::
    
  3261. 
    
  3262.     >>> change_url = reverse('admin:polls_choice_change', args=(c.id,), current_app='custom')
    
  3263. 
    
  3264. For more details, see the documentation on :ref:`reversing namespaced URLs
    
  3265. <topics-http-reversing-url-namespaces>`.
    
  3266. 
    
  3267. To allow easier reversing of the admin urls in templates, Django provides an
    
  3268. ``admin_urlname`` filter which takes an action as argument:
    
  3269. 
    
  3270. .. code-block:: html+django
    
  3271. 
    
  3272.     {% load admin_urls %}
    
  3273.     <a href="{% url opts|admin_urlname:'add' %}">Add user</a>
    
  3274.     <a href="{% url opts|admin_urlname:'delete' user.pk %}">Delete this user</a>
    
  3275. 
    
  3276. The action in the examples above match the last part of the URL names for
    
  3277. :class:`ModelAdmin` instances described above. The ``opts`` variable can be any
    
  3278. object which has an ``app_label`` and ``model_name`` attributes and is usually
    
  3279. supplied by the admin views for the current model.
    
  3280. 
    
  3281. The ``display`` decorator
    
  3282. =========================
    
  3283. 
    
  3284. .. function:: display(*, boolean=None, ordering=None, description=None, empty_value=None)
    
  3285. 
    
  3286.     This decorator can be used for setting specific attributes on custom
    
  3287.     display functions that can be used with
    
  3288.     :attr:`~django.contrib.admin.ModelAdmin.list_display` or
    
  3289.     :attr:`~django.contrib.admin.ModelAdmin.readonly_fields`::
    
  3290. 
    
  3291.         @admin.display(
    
  3292.             boolean=True,
    
  3293.             ordering='-publish_date',
    
  3294.             description='Is Published?',
    
  3295.         )
    
  3296.         def is_published(self, obj):
    
  3297.             return obj.publish_date is not None
    
  3298. 
    
  3299.     This is equivalent to setting some attributes (with the original, longer
    
  3300.     names) on the function directly::
    
  3301. 
    
  3302.         def is_published(self, obj):
    
  3303.             return obj.publish_date is not None
    
  3304.         is_published.boolean = True
    
  3305.         is_published.admin_order_field = '-publish_date'
    
  3306.         is_published.short_description = 'Is Published?'
    
  3307. 
    
  3308.     Also note that the ``empty_value`` decorator parameter maps to the
    
  3309.     ``empty_value_display`` attribute assigned directly to the function. It
    
  3310.     cannot be used in conjunction with ``boolean`` -- they are mutually
    
  3311.     exclusive.
    
  3312. 
    
  3313.     Use of this decorator is not compulsory to make a display function, but it
    
  3314.     can be useful to use it without arguments as a marker in your source to
    
  3315.     identify the purpose of the function::
    
  3316. 
    
  3317.         @admin.display
    
  3318.         def published_year(self, obj):
    
  3319.             return obj.publish_date.year
    
  3320. 
    
  3321.     In this case it will add no attributes to the function.
    
  3322. 
    
  3323. .. currentmodule:: django.contrib.admin.views.decorators
    
  3324. 
    
  3325. The ``staff_member_required`` decorator
    
  3326. =======================================
    
  3327. 
    
  3328. .. function:: staff_member_required(redirect_field_name='next', login_url='admin:login')
    
  3329. 
    
  3330.     This decorator is used on the admin views that require authorization. A
    
  3331.     view decorated with this function will have the following behavior:
    
  3332. 
    
  3333.     * If the user is logged in, is a staff member (``User.is_staff=True``), and
    
  3334.       is active (``User.is_active=True``), execute the view normally.
    
  3335. 
    
  3336.     * Otherwise, the request will be redirected to the URL specified by the
    
  3337.       ``login_url`` parameter, with the originally requested path in a query
    
  3338.       string variable specified by ``redirect_field_name``. For example:
    
  3339.       ``/admin/login/?next=/admin/polls/question/3/``.
    
  3340. 
    
  3341.     Example usage::
    
  3342. 
    
  3343.         from django.contrib.admin.views.decorators import staff_member_required
    
  3344. 
    
  3345.         @staff_member_required
    
  3346.         def my_view(request):
    
  3347.             ...