The Django admin site
The Django 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 startproject.
If you’re not using the default project template, here are the requirements:
- Add
'django.contrib.admin'and its dependencies - django.contrib.auth, django.contrib.contenttypes, django.contrib.messages, and django.contrib.sessions - to your INSTALLED_APPS setting. - Configure a DjangoTemplates backend in your TEMPLATES setting with
django.template.context_processors.request,django.contrib.auth.context_processors.auth, anddjango.contrib.messages.context_processors.messagesin the'context_processors'option of OPTIONS. - If you’ve customized the MIDDLEWARE setting, django.contrib.sessions.middleware.SessionMiddleware, django.contrib.auth.middleware.AuthenticationMiddleware, and django.contrib.messages.middleware.MessageMiddleware must be included.
- Hook the admin’s URLs into your URLconf.
After you’ve taken these steps, you’ll be able to use the admin site by visiting the URL you hooked it into (/admin/, by default).
If you need to create a user to login with, use the createsuperuser command. By default, logging in to the admin requires that the user has the is_staff attribute set to True.
Finally, determine which of your application’s models should be editable in the admin interface. For each of those models, register them with the admin as described in ModelAdmin.
Other topics
- Admin actions
- ModelAdmin List Filters
- The Django admin documentation generator
- JavaScript customizations in the admin
See also
For information about serving the static files (images, JavaScript, and CSS) associated with the admin in production, see Serving files.
Having problems? Try FAQ: The admin.
ModelAdmin objects
class ModelAdmin[source]
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 an example of the ModelAdmin:
from django.contrib import admin
from myapp.models import Author
class AuthorAdmin(admin.ModelAdmin):
pass
admin.site.register(Author, AuthorAdmin)
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 myapp.models import Author
admin.site.register(Author)
The register decorator
register(*models , site=django.contrib.admin.sites.site)[source]
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 AdminSite, pass it using the site keyword argument:
from django.contrib import admin
from .models import Author, Editor, Reader
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 INSTALLED_APPS setting, Django automatically looks for an admin module in each application and imports it.
class apps.AdminConfig
This is the default AppConfig class for the admin. It calls autodiscover() when Django starts.
class apps.SimpleAdminConfig
This class works like AdminConfig, except it doesn’t call autodiscover().
default_site
A dotted import path to the default admin site’s class or to a callable that returns a site instance. Defaults to 'django.contrib.admin.sites.AdminSite'. See Overriding the default admin site for usage.
autodiscover()[source]
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 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 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"
ModelAdmin.actions
A list of actions to make available on the change list page. See Admin actions for details.
ModelAdmin.actions_on_top
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).
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).
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 QuerySet.datetimes() internally. Please refer to its documentation for some caveats when time zone support is enabled (USE_TZ = True).
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 AdminSite.empty_value_display, or for specific fields like this:
from django.contrib import admin
class AuthorAdmin(admin.ModelAdmin):
list_display = ["name", "title", "view_birth_date"]
@admin.display(empty_value="???")
def view_birth_date(self, obj):
return obj.birth_date
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.
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 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 ModelAdmin.readonly_fields to be displayed as read-only.
For more complex layout needs, see the fieldsets option.
The fields option accepts the same types of values as list_display, except that callables and __ lookups for related fields aren’t accepted. Names of model and model admin methods will only be used if they’re listed in 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"]
Possible confusion with the ModelAdmin.fieldsets option
This fields option should not be confused with the fields dictionary key that is within the fieldsets option, as described in the next section.
If neither fields nor 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.
ModelAdmin.fieldsets
Set fieldsets to control the layout of admin “add” and “change” pages.
fieldsets is a list of 2-tuples, in which each 2-tuple represents a <fieldset> on the admin form page. (A <fieldset> is a “section” of the form.)
The 2-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 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:
If neither fieldsets nor 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 list or 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 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 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 fields option: the callable must be listed in readonly_fields.
classes
A list or tuple containing extra CSS classes to apply to the fieldset. This can include any custom CSS class defined in the project, as well as any of the CSS classes provided by Django. Within the default admin site CSS stylesheet, two particularly useful classes are defined: collapse and wide.
Example:
{
"classes": ["wide", "collapse"],
}
Fieldsets with the wide style will be given extra horizontal space in the admin interface. Fieldsets with a name and the collapse style will be initially collapsed, using an expandable widget with a toggle for switching their visibility.
Changed in Django 5.1:
fieldsets using the collapse class now use <details> and <summary> elements, provided they define a name.
description
A string of optional extra text to be displayed at the top of each fieldset, under the heading of the fieldset.
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.
TabularInline has limited support for fieldsets
Using fieldsets with TabularInline has limited functionality. You can specify which fields will be displayed and their order within the TabularInline layout by defining fields in the field_options dictionary.
All other features are not supported. This includes the use of name to define a title for a group of fields.
ModelAdmin.filter_horizontal
By default, a ManyToManyField is displayed in the admin site with a <select multiple>. However, multiple-select boxes can be difficult to use when selecting many items. Adding a ManyToManyField to this list will instead use a nifty unobtrusive JavaScript “filter” interface that allows searching within the options. The unselected and selected options appear in two boxes side by side. See filter_vertical to use a vertical interface.
ModelAdmin.filter_vertical
Same as filter_horizontal, but uses a vertical display of the filter interface with the box of unselected options appearing above the box of selected options.
ModelAdmin.form
By default a ModelForm is dynamically created for your model. It is used to create the form presented on both the add/change pages. You can easily provide your own ModelForm to override any default form behavior on the add/change pages. Alternatively, you can customize the default form rather than specifying an entirely new one by using the ModelAdmin.get_form() method.
For an example see the section Adding custom validation to the admin.
Omit the Meta.model attribute
If you define the Meta.model attribute on a ModelForm, you must also define the Meta.fields attribute (or the Meta.exclude attribute). However, since the admin has its own way of defining fields, the Meta.fields attribute will be ignored.
If the ModelForm is only going to be used for the admin, the easiest solution is to omit the Meta.model attribute, since ModelAdmin will provide the correct model to use. Alternatively, you can set fields = [] in the Meta class to satisfy the validation on the ModelForm.
ModelAdmin.exclude takes precedence
If your ModelForm and ModelAdmin both define an exclude option then ModelAdmin takes precedence:
from django import forms
from django.contrib import admin
from myapp.models import Person
class PersonForm(forms.ModelForm):
class Meta:
model = Person
exclude = ["name"]
class PersonAdmin(admin.ModelAdmin):
exclude = ["age"]
form = PersonForm
In the above example, the “age” field will be excluded but the “name” field will be included in the generated form.
ModelAdmin.formfield_overrides
This provides a quick-and-dirty way to override some of the Field options for use in the admin. formfield_overrides is a dictionary mapping a field class to a dict of arguments to pass to the field at construction time.
Since that’s a bit abstract, let’s look at a concrete example. The most common use of formfield_overrides is to add a custom widget for a certain type of field. So, imagine we’ve written a RichTextEditorWidget that we’d like to use for large text fields instead of the default <textarea>. Here’s how we’d do that:
``` from django.contrib import admin from django.db import models
(本文超出站点单文档体积上限,已按小节截断)
