===================== The Django admin site ===================== .. module:: django.contrib.admin :synopsis: Django's admin site. One of the most powerful parts of Django is the automatic admin interface. It reads metadata from your models to provide a quick, model-centric interface where trusted users can manage content on your site. The admin's recommended use is limited to an organization's internal management tool. It's not intended for building your entire front end around. The admin has many hooks for customization, but beware of trying to use those hooks exclusively. If you need to provide a more process-centric interface that abstracts away the implementation details of database tables and fields, then it's probably time to write your own views. In this document we discuss how to activate, use, and customize Django's admin interface. Overview ======== The admin is enabled in the default project template used by :djadmin:`startproject`. For reference, here are the requirements: 1. Add ``'django.contrib.admin'`` to your :setting:`INSTALLED_APPS` setting. 2. The admin has four dependencies - :mod:`django.contrib.auth`, :mod:`django.contrib.contenttypes`, :mod:`django.contrib.messages` and :mod:`django.contrib.sessions`. If these applications are not in your :setting:`INSTALLED_APPS` list, add them. 3. Add ``django.contrib.auth.context_processors.auth`` and ``django.contrib.messages.context_processors.messages`` to the ``'context_processors'`` option of the ``DjangoTemplates`` backend defined in your :setting:`TEMPLATES` as well as :class:`django.contrib.auth.middleware.AuthenticationMiddleware` and :class:`django.contrib.messages.middleware.MessageMiddleware` to :setting:`MIDDLEWARE`. These are all active by default, so you only need to do this if you've manually tweaked the settings. 4. Determine which of your application's models should be editable in the admin interface. 5. For each of those models, optionally create a ``ModelAdmin`` class that encapsulates the customized admin functionality and options for that particular model. 6. Instantiate an ``AdminSite`` and tell it about each of your models and ``ModelAdmin`` classes. 7. Hook the ``AdminSite`` instance into your URLconf. After you've taken these steps, you'll be able to use your Django admin site by visiting the URL you hooked it into (``/admin/``, by default). If you need to create a user to login with, you can use the :djadmin:`createsuperuser` command. Other topics ------------ .. toctree:: :maxdepth: 1 actions admindocs javascript .. seealso:: For information about serving the static files (images, JavaScript, and CSS) associated with the admin in production, see :ref:`serving-files`. Having problems? Try :doc:`/faq/admin`. ``ModelAdmin`` objects ====================== .. class:: ModelAdmin The ``ModelAdmin`` class is the representation of a model in the admin interface. Usually, these are stored in a file named ``admin.py`` in your application. Let's take a look at a very simple example of the ``ModelAdmin``:: from django.contrib import admin from myproject.myapp.models import Author class AuthorAdmin(admin.ModelAdmin): pass admin.site.register(Author, AuthorAdmin) .. admonition:: Do you need a ``ModelAdmin`` object at all? In the preceding example, the ``ModelAdmin`` class doesn't define any custom values (yet). As a result, the default admin interface will be provided. If you are happy with the default admin interface, you don't need to define a ``ModelAdmin`` object at all -- you can register the model class without providing a ``ModelAdmin`` description. The preceding example could be simplified to:: from django.contrib import admin from myproject.myapp.models import Author admin.site.register(Author) The ``register`` decorator -------------------------- .. function:: register(*models, site=django.admin.sites.site) There is also a decorator for registering your ``ModelAdmin`` classes:: from django.contrib import admin from .models import Author @admin.register(Author) class AuthorAdmin(admin.ModelAdmin): pass It's given one or more model classes to register with the ``ModelAdmin``. If you're using a custom :class:`AdminSite`, pass it using the ``site`` keyword argument:: from django.contrib import admin from .models import Author, Reader, Editor from myproject.admin_site import custom_admin_site @admin.register(Author, Reader, Editor, site=custom_admin_site) class PersonAdmin(admin.ModelAdmin): pass You can't use this decorator if you have to reference your model admin class in its ``__init__()`` method, e.g. ``super(PersonAdmin, self).__init__(*args, **kwargs)``. You can use ``super().__init__(*args, **kwargs)``. Discovery of admin files ------------------------ When you put ``'django.contrib.admin'`` in your :setting:`INSTALLED_APPS` setting, Django automatically looks for an ``admin`` module in each application and imports it. .. class:: apps.AdminConfig This is the default :class:`~django.apps.AppConfig` class for the admin. It calls :func:`~django.contrib.admin.autodiscover()` when Django starts. .. class:: apps.SimpleAdminConfig This class works like :class:`~django.contrib.admin.apps.AdminConfig`, except it doesn't call :func:`~django.contrib.admin.autodiscover()`. .. function:: autodiscover This function attempts to import an ``admin`` module in each installed application. Such modules are expected to register models with the admin. Typically you won't need to call this function directly as :class:`~django.contrib.admin.apps.AdminConfig` calls it when Django starts. If you are using a custom ``AdminSite``, it is common to import all of the ``ModelAdmin`` subclasses into your code and register them to the custom ``AdminSite``. In that case, in order to disable auto-discovery, you should put ``'django.contrib.admin.apps.SimpleAdminConfig'`` instead of ``'django.contrib.admin'`` in your :setting:`INSTALLED_APPS` setting. ``ModelAdmin`` options ---------------------- The ``ModelAdmin`` is very flexible. It has several options for dealing with customizing the interface. All options are defined on the ``ModelAdmin`` subclass:: from django.contrib import admin class AuthorAdmin(admin.ModelAdmin): date_hierarchy = 'pub_date' .. attribute:: ModelAdmin.actions A list of actions to make available on the change list page. See :doc:`/ref/contrib/admin/actions` for details. .. attribute:: ModelAdmin.actions_on_top .. attribute:: ModelAdmin.actions_on_bottom Controls where on the page the actions bar appears. By default, the admin changelist displays actions at the top of the page (``actions_on_top = True; actions_on_bottom = False``). .. attribute:: ModelAdmin.actions_selection_counter Controls whether a selection counter is displayed next to the action dropdown. By default, the admin changelist will display it (``actions_selection_counter = True``). .. attribute:: ModelAdmin.date_hierarchy Set ``date_hierarchy`` to the name of a ``DateField`` or ``DateTimeField`` in your model, and the change list page will include a date-based drilldown navigation by that field. Example:: date_hierarchy = 'pub_date' You can also specify a field on a related model using the ``__`` lookup, for example:: date_hierarchy = 'author__pub_date' This will intelligently populate itself based on available data, e.g. if all the dates are in one month, it'll show the day-level drill-down only. .. note:: ``date_hierarchy`` uses :meth:`QuerySet.datetimes() ` internally. Please refer to its documentation for some caveats when time zone support is enabled (:setting:`USE_TZ = True `). .. attribute:: ModelAdmin.empty_value_display This attribute overrides the default display value for record's fields that are empty (``None``, empty string, etc.). The default value is ``-`` (a dash). For example:: from django.contrib import admin class AuthorAdmin(admin.ModelAdmin): empty_value_display = '-empty-' You can also override ``empty_value_display`` for all admin pages with :attr:`AdminSite.empty_value_display`, or for specific fields like this:: from django.contrib import admin class AuthorAdmin(admin.ModelAdmin): fields = ('name', 'title', 'view_birth_date') def view_birth_date(self, obj): return obj.birth_date view_birth_date.empty_value_display = '???' .. attribute:: ModelAdmin.exclude This attribute, if given, should be a list of field names to exclude from the form. For example, let's consider the following model:: from django.db import models class Author(models.Model): name = models.CharField(max_length=100) title = models.CharField(max_length=3) birth_date = models.DateField(blank=True, null=True) If you want a form for the ``Author`` model that includes only the ``name`` and ``title`` fields, you would specify ``fields`` or ``exclude`` like this:: from django.contrib import admin class AuthorAdmin(admin.ModelAdmin): fields = ('name', 'title') class AuthorAdmin(admin.ModelAdmin): exclude = ('birth_date',) Since the Author model only has three fields, ``name``, ``title``, and ``birth_date``, the forms resulting from the above declarations will contain exactly the same fields. .. attribute:: ModelAdmin.fields Use the ``fields`` option to make simple layout changes in the forms on the "add" and "change" pages such as showing only a subset of available fields, modifying their order, or grouping them into rows. For example, you could define a simpler version of the admin form for the :class:`django.contrib.flatpages.models.FlatPage` model as follows:: class FlatPageAdmin(admin.ModelAdmin): fields = ('url', 'title', 'content') In the above example, only the fields ``url``, ``title`` and ``content`` will be displayed, sequentially, in the form. ``fields`` can contain values defined in :attr:`ModelAdmin.readonly_fields` to be displayed as read-only. For more complex layout needs, see the :attr:`~ModelAdmin.fieldsets` option. The ``fields`` option, unlike :attr:`~ModelAdmin.list_display`, may only contain names of fields on the model or the form specified by :attr:`~ModelAdmin.form`. It may contain callables only if they are listed in :attr:`~ModelAdmin.readonly_fields`. To display multiple fields on the same line, wrap those fields in their own tuple. In this example, the ``url`` and ``title`` fields will display on the same line and the ``content`` field will be displayed below them on its own line:: class FlatPageAdmin(admin.ModelAdmin): fields = (('url', 'title'), 'content') .. admonition:: Note This ``fields`` option should not be confused with the ``fields`` dictionary key that is within the :attr:`~ModelAdmin.fieldsets` option, as described in the next section. If neither ``fields`` nor :attr:`~ModelAdmin.fieldsets` options are present, Django will default to displaying each field that isn't an ``AutoField`` and has ``editable=True``, in a single fieldset, in the same order as the fields are defined in the model. .. attribute:: ModelAdmin.fieldsets Set ``fieldsets`` to control the layout of admin "add" and "change" pages. ``fieldsets`` is a list of two-tuples, in which each two-tuple represents a ``
`` on the admin form page. (A ``
`` is a "section" of the form.) The two-tuples are in the format ``(name, field_options)``, where ``name`` is a string representing the title of the fieldset and ``field_options`` is a dictionary of information about the fieldset, including a list of fields to be displayed in it. A full example, taken from the :class:`django.contrib.flatpages.models.FlatPage` model:: from django.contrib import admin class FlatPageAdmin(admin.ModelAdmin): fieldsets = ( (None, { 'fields': ('url', 'title', 'content', 'sites') }), ('Advanced options', { 'classes': ('collapse',), 'fields': ('registration_required', 'template_name'), }), ) This results in an admin page that looks like: .. image:: _images/fieldsets.png If neither ``fieldsets`` nor :attr:`~ModelAdmin.fields` options are present, Django will default to displaying each field that isn't an ``AutoField`` and has ``editable=True``, in a single fieldset, in the same order as the fields are defined in the model. The ``field_options`` dictionary can have the following keys: * ``fields`` A tuple of field names to display in this fieldset. This key is required. Example:: { 'fields': ('first_name', 'last_name', 'address', 'city', 'state'), } As with the :attr:`~ModelAdmin.fields` option, to display multiple fields on the same line, wrap those fields in their own tuple. In this example, the ``first_name`` and ``last_name`` fields will display on the same line:: { 'fields': (('first_name', 'last_name'), 'address', 'city', 'state'), } ``fields`` can contain values defined in :attr:`~ModelAdmin.readonly_fields` to be displayed as read-only. If you add the name of a callable to ``fields``, the same rule applies as with the :attr:`~ModelAdmin.fields` option: the callable must be listed in :attr:`~ModelAdmin.readonly_fields`. * ``classes`` A list or tuple containing extra CSS classes to apply to the fieldset. Example:: { 'classes': ('wide', 'extrapretty'), } Two useful classes defined by the default admin site stylesheet are ``collapse`` and ``wide``. Fieldsets with the ``collapse`` style will be initially collapsed in the admin and replaced with a small "click to expand" link. Fieldsets with the ``wide`` style will be given extra horizontal space. * ``description`` A string of optional extra text to be displayed at the top of each fieldset, under the heading of the fieldset. This string is not rendered for :class:`~django.contrib.admin.TabularInline` due to its layout. Note that this value is *not* HTML-escaped when it's displayed in the admin interface. This lets you include HTML if you so desire. Alternatively you can use plain text and ``django.utils.html.escape()`` to escape any HTML special characters. .. attribute:: ModelAdmin.filter_horizontal By default, a :class:`~django.db.models.ManyToManyField` is displayed in the admin site with a ``