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.

概况

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:

  1. 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.

  2. Configure a DjangoTemplates backend in your TEMPLATES setting with django.template.context_processors.request, django.contrib.auth.context_processors.auth, and django.contrib.messages.context_processors.messages in the 'context_processors' option of OPTIONS.

    Changed in Django 3.1:

    django.template.context_processors.request was added as a requirement in the 'context_processors' option to support the new AdminSite.enable_nav_sidebar.

  3. If you’ve customized the MIDDLEWARE setting, django.contrib.auth.middleware.AuthenticationMiddleware and django.contrib.messages.middleware.MessageMiddleware must be included.

  4. 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_superuser or 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

参见

For information about serving the static files (images, JavaScript, and CSS) associated with the admin in production, see 提供文件服务.

Having problems? Try FAQ:管理.

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 an example of the ModelAdmin:

  1. from django.contrib import admin
  2. from myproject.myapp.models import Author
  3. class AuthorAdmin(admin.ModelAdmin):
  4. pass
  5. 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:

  1. from django.contrib import admin
  2. from myproject.myapp.models import Author
  3. admin.site.register(Author)

The register decorator

register(\models, site=django.contrib.admin.sites.site*)

There is also a decorator for registering your ModelAdmin classes:

  1. from django.contrib import admin
  2. from .models import Author
  3. @admin.register(Author)
  4. class AuthorAdmin(admin.ModelAdmin):
  5. 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:

  1. from django.contrib import admin
  2. from .models import Author, Editor, Reader
  3. from myproject.admin_site import custom_admin_site
  4. @admin.register(Author, Reader, Editor, site=custom_admin_site)
  5. class PersonAdmin(admin.ModelAdmin):
  6. 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()

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:

  1. from django.contrib import admin
  2. class AuthorAdmin(admin.ModelAdmin):
  3. 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.

举例:

  1. date_hierarchy = 'pub_date'

You can also specify a field on a related model using the __ lookup, for example:

  1. 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.

注解

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:

  1. from django.contrib import admin
  2. class AuthorAdmin(admin.ModelAdmin):
  3. 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:

  1. from django.contrib import admin
  2. class AuthorAdmin(admin.ModelAdmin):
  3. fields = ('name', 'title', 'view_birth_date')
  4. def view_birth_date(self, obj):
  5. return obj.birth_date
  6. view_birth_date.empty_value_display = '???'

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:

  1. from django.db import models
  2. class Author(models.Model):
  3. name = models.CharField(max_length=100)
  4. title = models.CharField(max_length=3)
  5. 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:

  1. from django.contrib import admin
  2. class AuthorAdmin(admin.ModelAdmin):
  3. fields = ('name', 'title')
  4. class AuthorAdmin(admin.ModelAdmin):
  5. 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:

  1. class FlatPageAdmin(admin.ModelAdmin):
  2. 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 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:

  1. class FlatPageAdmin(admin.ModelAdmin):
  2. fields = (('url', 'title'), 'content')

注释

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 two-tuples, in which each two-tuple represents a <fieldset> on the admin form page. (A <fieldset> 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 django.contrib.flatpages.models.FlatPage model:

  1. from django.contrib import admin
  2. class FlatPageAdmin(admin.ModelAdmin):
  3. fieldsets = (
  4. (None, {
  5. 'fields': ('url', 'title', 'content', 'sites')
  6. }),
  7. ('Advanced options', {
  8. 'classes': ('collapse',),
  9. 'fields': ('registration_required', 'template_name'),
  10. }),
  11. )

This results in an admin page that looks like:

../../../_images/fieldsets.png

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 tuple of field names to display in this fieldset. This key is required.

    举例:

    1. {
    2. 'fields': ('first_name', 'last_name', 'address', 'city', 'state'),
    3. }

    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:

    1. {
    2. 'fields': (('first_name', 'last_name'), 'address', 'city', 'state'),
    3. }

    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.

    举例:

    1. {
    2. 'classes': ('wide', 'extrapretty'),
    3. }

    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 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.

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.

注释

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.

注释

If your ModelForm and ModelAdmin both define an exclude option then ModelAdmin takes precedence:

  1. from django import forms
  2. from django.contrib import admin
  3. from myapp.models import Person
  4. class PersonForm(forms.ModelForm):
  5. class Meta:
  6. model = Person
  7. exclude = ['name']
  8. class PersonAdmin(admin.ModelAdmin):
  9. exclude = ['age']
  10. 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:

  1. from django.contrib import admin
  2. from django.db import models
  3. # Import our custom widget and our model from where they're defined
  4. from myapp.models import MyModel
  5. from myapp.widgets import RichTextEditorWidget
  6. class MyModelAdmin(admin.ModelAdmin):
  7. formfield_overrides = {
  8. models.TextField: {'widget': RichTextEditorWidget},
  9. }

Note that the key in the dictionary is the actual field class, not a string. The value is another dictionary; these arguments will be passed to the form field’s __init__() method. See The Forms API for details.

警告

If you want to use a custom widget with a relation field (i.e. ForeignKey or ManyToManyField), make sure you haven’t included that field’s name in raw_id_fields, radio_fields, or autocomplete_fields.

formfield_overrides won’t let you change the widget on relation fields that have raw_id_fields, radio_fields, or autocomplete_fields set. That’s because raw_id_fields, radio_fields, and autocomplete_fields imply custom widgets of their own.

ModelAdmin.``inlines

See InlineModelAdmin objects below as well as ModelAdmin.get_formsets_with_inlines().

ModelAdmin.``list_display

Set list_display to control which fields are displayed on the change list page of the admin.

举例:

  1. list_display = ('first_name', 'last_name')

If you don’t set list_display, the admin site will display a single column that displays the __str__() representation of each object.

There are four types of values that can be used in list_display:

  • The name of a model field. For example:

    1. class PersonAdmin(admin.ModelAdmin):
    2. list_display = ('first_name', 'last_name')
  • A callable that accepts one argument, the model instance. For example:

    1. def upper_case_name(obj):
    2. return ("%s %s" % (obj.first_name, obj.last_name)).upper()
    3. upper_case_name.short_description = 'Name'
    4. class PersonAdmin(admin.ModelAdmin):
    5. list_display = (upper_case_name,)
  • A string representing a ModelAdmin method that accepts one argument, the model instance. For example:

    1. class PersonAdmin(admin.ModelAdmin):
    2. list_display = ('upper_case_name',)
    3. def upper_case_name(self, obj):
    4. return ("%s %s" % (obj.first_name, obj.last_name)).upper()
    5. upper_case_name.short_description = 'Name'
  • A string representing a model attribute or method (without any required arguments). For example:

    1. from django.contrib import admin
    2. from django.db import models
    3. class Person(models.Model):
    4. name = models.CharField(max_length=50)
    5. birthday = models.DateField()
    6. def decade_born_in(self):
    7. return self.birthday.strftime('%Y')[:3] + "0's"
    8. decade_born_in.short_description = 'Birth decade'
    9. class PersonAdmin(admin.ModelAdmin):
    10. list_display = ('name', 'decade_born_in')

A few special cases to note about list_display:

  • If the field is a ForeignKey, Django will display the __str__() of the related object.

  • ManyToManyField fields aren’t supported, because that would entail executing a separate SQL statement for each row in the table. If you want to do this nonetheless, give your model a custom method, and add that method’s name to list_display. (See below for more on custom methods in list_display.)

  • If the field is a BooleanField, Django will display a pretty “on” or “off” icon instead of True or False.

  • If the string given is a method of the model, ModelAdmin or a callable, Django will HTML-escape the output by default. To escape user input and allow your own unescaped tags, use format_html().

    Here’s a full example model:

    1. from django.contrib import admin
    2. from django.db import models
    3. from django.utils.html import format_html
    4. class Person(models.Model):
    5. first_name = models.CharField(max_length=50)
    6. last_name = models.CharField(max_length=50)
    7. color_code = models.CharField(max_length=6)
    8. def colored_name(self):
    9. return format_html(
    10. '<span style="color: #{};">{} {}</span>',
    11. self.color_code,
    12. self.first_name,
    13. self.last_name,
    14. )
    15. class PersonAdmin(admin.ModelAdmin):
    16. list_display = ('first_name', 'last_name', 'colored_name')
  • As some examples have already demonstrated, when using a callable, a model method, or a ModelAdmin method, you can customize the column’s title by adding a short_description attribute to the callable.

  • If the value of a field is None, an empty string, or an iterable without elements, Django will display - (a dash). You can override this with AdminSite.empty_value_display:

    1. from django.contrib import admin
    2. admin.site.empty_value_display = '(None)'

    You can also use ModelAdmin.empty_value_display:

    1. class PersonAdmin(admin.ModelAdmin):
    2. empty_value_display = 'unknown'

    Or on a field level:

    1. class PersonAdmin(admin.ModelAdmin):
    2. list_display = ('name', 'birth_date_view')
    3. def birth_date_view(self, obj):
    4. return obj.birth_date
    5. birth_date_view.empty_value_display = 'unknown'
  • If the string given is a method of the model, ModelAdmin or a callable that returns True or False Django will display a pretty “on” or “off” icon if you give the method a boolean attribute whose value is True.

    Here’s a full example model:

    1. from django.contrib import admin
    2. from django.db import models
    3. class Person(models.Model):
    4. first_name = models.CharField(max_length=50)
    5. birthday = models.DateField()
    6. def born_in_fifties(self):
    7. return self.birthday.strftime('%Y')[:3] == '195'
    8. born_in_fifties.boolean = True
    9. class PersonAdmin(admin.ModelAdmin):
    10. list_display = ('name', 'born_in_fifties')
  • The __str__() method is just as valid in list_display as any other model method, so it’s perfectly OK to do this:

    1. list_display = ('__str__', 'some_other_field')
  • Usually, elements of list_display that aren’t actual database fields can’t be used in sorting (because Django does all the sorting at the database level).

    However, if an element of list_display represents a certain database field, you can indicate this fact by setting the admin_order_field attribute of the item.

    例子:

    1. from django.contrib import admin
    2. from django.db import models
    3. from django.utils.html import format_html
    4. class Person(models.Model):
    5. first_name = models.CharField(max_length=50)
    6. color_code = models.CharField(max_length=6)
    7. def colored_first_name(self):
    8. return format_html(
    9. '<span style="color: #{};">{}</span>',
    10. self.color_code,
    11. self.first_name,
    12. )
    13. colored_first_name.admin_order_field = 'first_name'
    14. class PersonAdmin(admin.ModelAdmin):
    15. list_display = ('first_name', 'colored_first_name')

    The above will tell Django to order by the first_name field when trying to sort by colored_first_name in the admin.

    To indicate descending order with admin_order_field you can use a hyphen prefix on the field name. Using the above example, this would look like:

    1. colored_first_name.admin_order_field = '-first_name'

    admin_order_field supports query lookups to sort by values on related models. This example includes an “author first name” column in the list display and allows sorting it by first name:

    1. class Blog(models.Model):
    2. title = models.CharField(max_length=255)
    3. author = models.ForeignKey(Person, on_delete=models.CASCADE)
    4. class BlogAdmin(admin.ModelAdmin):
    5. list_display = ('title', 'author', 'author_first_name')
    6. def author_first_name(self, obj):
    7. return obj.author.first_name
    8. author_first_name.admin_order_field = 'author__first_name'

    Query expressions may be used in admin_order_field. For example:

    1. from django.db.models import Value
    2. from django.db.models.functions import Concat
    3. class Person(models.Model):
    4. first_name = models.CharField(max_length=50)
    5. last_name = models.CharField(max_length=50)
    6. def full_name(self):
    7. return self.first_name + ' ' + self.last_name
    8. full_name.admin_order_field = Concat('first_name', Value(' '), 'last_name')
  • Elements of list_display can also be properties. Please note however, that due to the way properties work in Python, setting short_description or admin_order_field on a property is only possible when using the property() function and not with the @property decorator.

    例子:

    1. class Person(models.Model):
    2. first_name = models.CharField(max_length=50)
    3. last_name = models.CharField(max_length=50)
    4. def my_property(self):
    5. return self.first_name + ' ' + self.last_name
    6. my_property.short_description = "Full name of the person"
    7. my_property.admin_order_field = 'last_name'
    8. full_name = property(my_property)
    9. class PersonAdmin(admin.ModelAdmin):
    10. list_display = ('full_name',)
  • The field names in list_display will also appear as CSS classes in the HTML output, in the form of column-<field_name> on each <th> element. This can be used to set column widths in a CSS file for example.

  • Django will try to interpret every element of list_display in this order:

    • A field of the model.
    • A callable.
    • A string representing a ModelAdmin attribute.
    • A string representing a model attribute.

    For example if you have first_name as a model field and as a ModelAdmin attribute, the model field will be used.

ModelAdmin.``list_display_links

Use list_display_links to control if and which fields in list_display should be linked to the “change” page for an object.

By default, the change list page will link the first column — the first field specified in list_display — to the change page for each item. But list_display_links lets you change this:

  • Set it to None to get no links at all.

  • Set it to a list or tuple of fields (in the same format as list_display) whose columns you want converted to links.

    You can specify one or many fields. As long as the fields appear in list_display, Django doesn’t care how many (or how few) fields are linked. The only requirement is that if you want to use list_display_links in this fashion, you must define list_display.

In this example, the first_name and last_name fields will be linked on the change list page:

  1. class PersonAdmin(admin.ModelAdmin):
  2. list_display = ('first_name', 'last_name', 'birthday')
  3. list_display_links = ('first_name', 'last_name')

In this example, the change list page grid will have no links:

  1. class AuditEntryAdmin(admin.ModelAdmin):
  2. list_display = ('timestamp', 'message')
  3. list_display_links = None

ModelAdmin.``list_editable

Set list_editable to a list of field names on the model which will allow editing on the change list page. That is, fields listed in list_editable will be displayed as form widgets on the change list page, allowing users to edit and save multiple rows at once.

注解

list_editable interacts with a couple of other options in particular ways; you should note the following rules:

  • Any field in list_editable must also be in list_display. You can’t edit a field that’s not displayed!
  • The same field can’t be listed in both list_editable and list_display_links — a field can’t be both a form and a link.

You’ll get a validation error if either of these rules are broken.

ModelAdmin.``list_filter

Set list_filter to activate filters in the right sidebar of the change list page of the admin, as illustrated in the following screenshot:

../../../_images/list_filter.png

list_filter should be a list or tuple of elements, where each element should be of one of the following types:

  • a field name, where the specified field should be either a BooleanField, CharField, DateField, DateTimeField, IntegerField, ForeignKey or ManyToManyField, for example:

    1. class PersonAdmin(admin.ModelAdmin):
    2. list_filter = ('is_staff', 'company')

    Field names in list_filter can also span relations using the __ lookup, for example:

    1. class PersonAdmin(admin.UserAdmin):
    2. list_filter = ('company__name',)
  • a class inheriting from django.contrib.admin.SimpleListFilter, which you need to provide the title and parameter_name attributes to and override the lookups and queryset methods, e.g.:

    1. from datetime import date
    2. from django.contrib import admin
    3. from django.utils.translation import gettext_lazy as _
    4. class DecadeBornListFilter(admin.SimpleListFilter):
    5. # Human-readable title which will be displayed in the
    6. # right admin sidebar just above the filter options.
    7. title = _('decade born')
    8. # Parameter for the filter that will be used in the URL query.
    9. parameter_name = 'decade'
    10. def lookups(self, request, model_admin):
    11. """
    12. Returns a list of tuples. The first element in each
    13. tuple is the coded value for the option that will
    14. appear in the URL query. The second element is the
    15. human-readable name for the option that will appear
    16. in the right sidebar.
    17. """
    18. return (
    19. ('80s', _('in the eighties')),
    20. ('90s', _('in the nineties')),
    21. )
    22. def queryset(self, request, queryset):
    23. """
    24. Returns the filtered queryset based on the value
    25. provided in the query string and retrievable via
    26. `self.value()`.
    27. """
    28. # Compare the requested value (either '80s' or '90s')
    29. # to decide how to filter the queryset.
    30. if self.value() == '80s':
    31. return queryset.filter(birthday__gte=date(1980, 1, 1),
    32. birthday__lte=date(1989, 12, 31))
    33. if self.value() == '90s':
    34. return queryset.filter(birthday__gte=date(1990, 1, 1),
    35. birthday__lte=date(1999, 12, 31))
    36. class PersonAdmin(admin.ModelAdmin):
    37. list_filter = (DecadeBornListFilter,)

    注解

    As a convenience, the HttpRequest object is passed to the lookups and queryset methods, for example:

    1. class AuthDecadeBornListFilter(DecadeBornListFilter):
    2. def lookups(self, request, model_admin):
    3. if request.user.is_superuser:
    4. return super().lookups(request, model_admin)
    5. def queryset(self, request, queryset):
    6. if request.user.is_superuser:
    7. return super().queryset(request, queryset)

    Also as a convenience, the ModelAdmin object is passed to the lookups method, for example if you want to base the lookups on the available data:

    1. class AdvancedDecadeBornListFilter(DecadeBornListFilter):
    2. def lookups(self, request, model_admin):
    3. """
    4. Only show the lookups if there actually is
    5. anyone born in the corresponding decades.
    6. """
    7. qs = model_admin.get_queryset(request)
    8. if qs.filter(birthday__gte=date(1980, 1, 1),
    9. birthday__lte=date(1989, 12, 31)).exists():
    10. yield ('80s', _('in the eighties'))
    11. if qs.filter(birthday__gte=date(1990, 1, 1),
    12. birthday__lte=date(1999, 12, 31)).exists():
    13. yield ('90s', _('in the nineties'))
  • a tuple, where the first element is a field name and the second element is a class inheriting from django.contrib.admin.FieldListFilter, for example:

    1. class PersonAdmin(admin.ModelAdmin):
    2. list_filter = (
    3. ('is_staff', admin.BooleanFieldListFilter),
    4. )

    You can limit the choices of a related model to the objects involved in that relation using RelatedOnlyFieldListFilter:

    1. class BookAdmin(admin.ModelAdmin):
    2. list_filter = (
    3. ('author', admin.RelatedOnlyFieldListFilter),
    4. )

    Assuming author is a ForeignKey to a User model, this will limit the list_filter choices to the users who have written a book instead of listing all users.

    You can filter empty values using EmptyFieldListFilter, which can filter on both empty strings and nulls, depending on what the field allows to store:

    1. class BookAdmin(admin.ModelAdmin):
    2. list_filter = (
    3. ('title', admin.EmptyFieldListFilter),
    4. )

    注解

    The FieldListFilter API is considered internal and might be changed.

    New in Django 3.1:

    The EmptyFieldListFilter class was added.

List filter’s typically appear only if the filter has more than one choice. A filter’s has_output() method controls whether or not it appears.

It is possible to specify a custom template for rendering a list filter:

  1. class FilterWithCustomTemplate(admin.SimpleListFilter):
  2. template = "custom_template.html"

See the default template provided by Django (admin/filter.html) for a concrete example.

ModelAdmin.``list_max_show_all

Set list_max_show_all to control how many items can appear on a “Show all” admin change list page. The admin will display a “Show all” link on the change list only if the total result count is less than or equal to this setting. By default, this is set to 200.

ModelAdmin.``list_per_page

Set list_per_page to control how many items appear on each paginated admin change list page. By default, this is set to 100.

ModelAdmin.``list_select_related

Set list_select_related to tell Django to use select_related() in retrieving the list of objects on the admin change list page. This can save you a bunch of database queries.

The value should be either a boolean, a list or a tuple. Default is False.

When value is True, select_related() will always be called. When value is set to False, Django will look at list_display and call select_related() if any ForeignKey is present.

If you need more fine-grained control, use a tuple (or list) as value for list_select_related. Empty tuple will prevent Django from calling select_related at all. Any other tuple will be passed directly to select_related as parameters. For example:

  1. class ArticleAdmin(admin.ModelAdmin):
  2. list_select_related = ('author', 'category')

will call select_related('author', 'category').

If you need to specify a dynamic value based on the request, you can implement a get_list_select_related() method.

注解

ModelAdmin ignores this attribute when select_related() was already called on the changelist’s QuerySet.

ModelAdmin.``ordering

Set ordering to specify how lists of objects should be ordered in the Django admin views. This should be a list or tuple in the same format as a model’s ordering parameter.

If this isn’t provided, the Django admin will use the model’s default ordering.

If you need to specify a dynamic order (for example depending on user or language) you can implement a get_ordering() method.

Performance considerations with ordering and sorting

To ensure a deterministic ordering of results, the changelist adds pk to the ordering if it can’t find a single or unique together set of fields that provide total ordering.

For example, if the default ordering is by a non-unique name field, then the changelist is sorted by name and pk. This could perform poorly if you have a lot of rows and don’t have an index on name and pk.

ModelAdmin.``paginator

The paginator class to be used for pagination. By default, django.core.paginator.Paginator is used. If the custom paginator class doesn’t have the same constructor interface as django.core.paginator.Paginator, you will also need to provide an implementation for ModelAdmin.get_paginator().

ModelAdmin.``prepopulated_fields

Set prepopulated_fields to a dictionary mapping field names to the fields it should prepopulate from:

  1. class ArticleAdmin(admin.ModelAdmin):
  2. prepopulated_fields = {"slug": ("title",)}

When set, the given fields will use a bit of JavaScript to populate from the fields assigned. The main use for this functionality is to automatically generate the value for SlugField fields from one or more other fields. The generated value is produced by concatenating the values of the source fields, and then by transforming that result into a valid slug (e.g. substituting dashes for spaces; lowercasing ASCII letters; and removing various English stop words such as ‘a’, ‘an’, ‘as’, and similar).

Prepopulated fields aren’t modified by JavaScript after a value has been saved. It’s usually undesired that slugs change (which would cause an object’s URL to change if the slug is used in it).

prepopulated_fields doesn’t accept DateTimeField, ForeignKey, OneToOneField, and ManyToManyField fields.

ModelAdmin.``preserve_filters

By default, applied filters are preserved on the list view after creating, editing, or deleting an object. You can have filters cleared by setting this attribute to False.

ModelAdmin.``radio_fields

By default, Django’s admin uses a select-box interface () for fields that are ForeignKey. Sometimes you don’t want to incur the overhead of having to select all the related instances to display in the drop-down.

raw_id_fields is a list of fields you would like to change into an Input widget for either a ForeignKey or ManyToManyField:

  1. class ArticleAdmin(admin.ModelAdmin):
  2. raw_id_fields = ("newspaper",)

The raw_id_fields Input widget should contain a primary key if the field is a ForeignKey or a comma separated list of values if the field is a ManyToManyField. The raw_id_fields widget shows a magnifying glass button next to the field which allows users to search for and select a value:

../../../_images/raw_id_fields.png

ModelAdmin.``readonly_fields

By default the admin shows all fields as editable. Any fields in this option (which should be a list or tuple) will display its data as-is and non-editable; they are also excluded from the ModelForm used for creating and editing. Note that when specifying ModelAdmin.fields or ModelAdmin.fieldsets the read-only fields must be present to be shown (they are ignored otherwise).

If readonly_fields is used without defining explicit ordering through ModelAdmin.fields or ModelAdmin.fieldsets they will be added last after all editable fields.

A read-only field can not only display data from a model’s field, it can also display the output of a model’s method or a method of the ModelAdmin class itself. This is very similar to the way ModelAdmin.list_display behaves. This provides a way to use the admin interface to provide feedback on the status of the objects being edited, for example:

  1. from django.contrib import admin
  2. from django.utils.html import format_html_join
  3. from django.utils.safestring import mark_safe
  4. class PersonAdmin(admin.ModelAdmin):
  5. readonly_fields = ('address_report',)
  6. def address_report(self, instance):
  7. # assuming get_full_address() returns a list of strings
  8. # for each line of the address and you want to separate each
  9. # line by a linebreak
  10. return format_html_join(
  11. mark_safe('<br>'),
  12. '{}',
  13. ((line,) for line in instance.get_full_address()),
  14. ) or mark_safe("<span class='errors'>I can't determine this address.</span>")
  15. # short_description functions like a model field's verbose_name
  16. address_report.short_description = "Address"

ModelAdmin.``save_as

Set save_as to enable a “save as new” feature on admin change forms.

Normally, objects have three save options: “Save”, “Save and continue editing”, and “Save and add another”. If save_as is True, “Save and add another” will be replaced by a “Save as new” button that creates a new object (with a new ID) rather than updating the existing object.

By default, save_as is set to False.

ModelAdmin.``save_as_continue

When save_as=True, the default redirect after saving the new object is to the change view for that object. If you set save_as_continue=False, the redirect will be to the changelist view.

By default, save_as_continue is set to True.

ModelAdmin.``save_on_top

Set save_on_top to add save buttons across the top of your admin change forms.

Normally, the save buttons appear only at the bottom of the forms. If you set save_on_top, the buttons will appear both on the top and the bottom.

By default, save_on_top is set to False.

ModelAdmin.``search_fields

Set search_fields to enable a search box on the admin change list page. This should be set to a list of field names that will be searched whenever somebody submits a search query in that text box.

These fields should be some kind of text field, such as CharField or TextField. You can also perform a related lookup on a ForeignKey or ManyToManyField with the lookup API “follow” notation:

  1. search_fields = ['foreign_key__related_fieldname']

For example, if you have a blog entry with an author, the following definition would enable searching blog entries by the email address of the author:

  1. search_fields = ['user__email']

When somebody does a search in the admin search box, Django splits the search query into words and returns all objects that contain each of the words, case-insensitive (using the icontains lookup), where each word must be in at least one of search_fields. For example, if search_fields is set to ['first_name', 'last_name'] and a user searches for john lennon, Django will do the equivalent of this SQL WHERE clause:

  1. WHERE (first_name ILIKE '%john%' OR last_name ILIKE '%john%')
  2. AND (first_name ILIKE '%lennon%' OR last_name ILIKE '%lennon%')

If you don’t want to use icontains as the lookup, you can use any lookup by appending it the field. For example, you could use exact by setting search_fields to ['first_name__exact'].

Beware that because query terms are split and ANDed as described earlier, searching with exact only works with a single search word since two or more words can’t all be an exact match unless all words are the same.

Some (older) shortcuts for specifying a field lookup are also available. You can prefix a field in search_fields with the following characters and it’s equivalent to adding __<lookup> to the field:

PrefixLookup
^startswith
=iexact
@search
icontains

If you need to customize search you can use ModelAdmin.get_search_results() to provide additional or alternate search behavior.

ModelAdmin.``show_full_result_count

Set show_full_result_count to control whether the full count of objects should be displayed on a filtered admin page (e.g. 99 results (103 total)). If this option is set to False, a text like 99 results (Show all) is displayed instead.

The default of show_full_result_count=True generates a query to perform a full count on the table which can be expensive if the table contains a large number of rows.

ModelAdmin.``sortable_by

By default, the change list page allows sorting by all model fields (and callables that have the admin_order_field property) specified in list_display.

If you want to disable sorting for some columns, set sortable_by to a collection (e.g. list, tuple, or set) of the subset of list_display that you want to be sortable. An empty collection disables sorting for all columns.

If you need to specify this list dynamically, implement a get_sortable_by() method instead.

ModelAdmin.``view_on_site

Set view_on_site to control whether or not to display the “View on site” link. This link should bring you to a URL where you can display the saved object.

This value can be either a boolean flag or a callable. If True (the default), the object’s get_absolute_url() method will be used to generate the url.

If your model has a get_absolute_url() method but you don’t want the “View on site” button to appear, you only need to set view_on_site to False:

  1. from django.contrib import admin
  2. class PersonAdmin(admin.ModelAdmin):
  3. view_on_site = False

In case it is a callable, it accepts the model instance as a parameter. For example:

  1. from django.contrib import admin
  2. from django.urls import reverse
  3. class PersonAdmin(admin.ModelAdmin):
  4. def view_on_site(self, obj):
  5. url = reverse('person-detail', kwargs={'slug': obj.slug})
  6. return 'https://example.com' + url

Custom template options

The Overriding admin templates section describes how to override or extend the default admin templates. Use the following options to override the default templates used by the ModelAdmin views:

ModelAdmin.``add_form_template

Path to a custom template, used by add_view().

ModelAdmin.``change_form_template

Path to a custom template, used by change_view().

ModelAdmin.``change_list_template

Path to a custom template, used by changelist_view().

ModelAdmin.``delete_confirmation_template

Path to a custom template, used by delete_view() for displaying a confirmation page when deleting one or more objects.

ModelAdmin.``delete_selected_confirmation_template

Path to a custom template, used by the delete_selected action method for displaying a confirmation page when deleting one or more objects. See the actions documentation.

ModelAdmin.``object_history_template

Path to a custom template, used by history_view().

ModelAdmin.``popup_response_template

Path to a custom template, used by response_add(), response_change(), and response_delete().

ModelAdmin methods

警告

When overriding ModelAdmin.save_model() and ModelAdmin.delete_model(), your code must save/delete the object. They aren’t meant for veto purposes, rather they allow you to perform extra operations.

ModelAdmin.``save_model(request, obj, form, change)

The save_model method is given the HttpRequest, a model instance, a ModelForm instance, and a boolean value based on whether it is adding or changing the object. Overriding this method allows doing pre- or post-save operations. Call super().save_model() to save the object using Model.save().

For example to attach request.user to the object prior to saving:

  1. from django.contrib import admin
  2. class ArticleAdmin(admin.ModelAdmin):
  3. def save_model(self, request, obj, form, change):
  4. obj.user = request.user
  5. super().save_model(request, obj, form, change)

ModelAdmin.``delete_model(request, obj)

The delete_model method is given the HttpRequest and a model instance. Overriding this method allows doing pre- or post-delete operations. Call super().delete_model() to delete the object using Model.delete().

ModelAdmin.``delete_queryset(request, queryset)

The delete_queryset() method is given the HttpRequest and a QuerySet of objects to be deleted. Override this method to customize the deletion process for the “delete selected objects” action.

ModelAdmin.``save_formset(request, form, formset, change)

The save_formset method is given the HttpRequest, the parent ModelForm instance and a boolean value based on whether it is adding or changing the parent object.

For example, to attach request.user to each changed formset model instance:

  1. class ArticleAdmin(admin.ModelAdmin):
  2. def save_formset(self, request, form, formset, change):
  3. instances = formset.save(commit=False)
  4. for obj in formset.deleted_objects:
  5. obj.delete()
  6. for instance in instances:
  7. instance.user = request.user
  8. instance.save()
  9. formset.save_m2m()

See also 在表单集中保存对象.

ModelAdmin.``get_ordering(request)

The get_ordering method takes a request as parameter and is expected to return a list or tuple for ordering similar to the ordering attribute. For example:

  1. class PersonAdmin(admin.ModelAdmin):
  2. def get_ordering(self, request):
  3. if request.user.is_superuser:
  4. return ['name', 'rank']
  5. else:
  6. return ['name']

ModelAdmin.``get_search_results(request, queryset, search_term)

The get_search_results method modifies the list of objects displayed into those that match the provided search term. It accepts the request, a queryset that applies the current filters, and the user-provided search term. It returns a tuple containing a queryset modified to implement the search, and a boolean indicating if the results may contain duplicates.

The default implementation searches the fields named in ModelAdmin.search_fields.

This method may be overridden with your own custom search method. For example, you might wish to search by an integer field, or use an external tool such as Solr or Haystack. You must establish if the queryset changes implemented by your search method may introduce duplicates into the results, and return True in the second element of the return value.

For example, to search by name and age, you could use:

  1. class PersonAdmin(admin.ModelAdmin):
  2. list_display = ('name', 'age')
  3. search_fields = ('name',)
  4. def get_search_results(self, request, queryset, search_term):
  5. queryset, use_distinct = super().get_search_results(request, queryset, search_term)
  6. try:
  7. search_term_as_int = int(search_term)
  8. except ValueError:
  9. pass
  10. else:
  11. queryset |= self.model.objects.filter(age=search_term_as_int)
  12. return queryset, use_distinct

This implementation is more efficient than search_fields = ('name', '=age') which results in a string comparison for the numeric field, for example ... OR UPPER("polls_choice"."votes"::text) = UPPER('4') on PostgreSQL.

ModelAdmin.``save_related(request, form, formsets, change)

The save_related method is given the HttpRequest, the parent ModelForm instance, the list of inline formsets and a boolean value based on whether the parent is being added or changed. Here you can do any pre- or post-save operations for objects related to the parent. Note that at this point the parent object and its form have already been saved.

ModelAdmin.``get_autocomplete_fields(request)

The get_autocomplete_fields() method is given the HttpRequest and is expected to return a list or tuple of field names that will be displayed with an autocomplete widget as described above in the ModelAdmin.autocomplete_fields section.

ModelAdmin.``get_readonly_fields(request, obj=None)

The get_readonly_fields method is given the HttpRequest and the obj being edited (or None on an add form) and is expected to return a list or tuple of field names that will be displayed as read-only, as described above in the ModelAdmin.readonly_fields section.

ModelAdmin.``get_prepopulated_fields(request, obj=None)

The get_prepopulated_fields method is given the HttpRequest and the obj being edited (or None on an add form) and is expected to return a dictionary, as described above in the ModelAdmin.prepopulated_fields section.

ModelAdmin.``get_list_display(request)

The get_list_display method is given the HttpRequest and is expected to return a list or tuple of field names that will be displayed on the changelist view as described above in the ModelAdmin.list_display section.

ModelAdmin.``get_list_display_links(request, list_display)

The get_list_display_links method is given the HttpRequest and the list or tuple returned by ModelAdmin.get_list_display(). It is expected to return either None or a list or tuple of field names on the changelist that will be linked to the change view, as described in the ModelAdmin.list_display_links section.

ModelAdmin.``get_exclude(request, obj=None)

The get_exclude method is given the HttpRequest and the obj being edited (or None on an add form) and is expected to return a list of fields, as described in ModelAdmin.exclude.

ModelAdmin.``get_fields(request, obj=None)

The get_fields method is given the HttpRequest and the obj being edited (or None on an add form) and is expected to return a list of fields, as described above in the ModelAdmin.fields section.

ModelAdmin.``get_fieldsets(request, obj=None)

The get_fieldsets method is given the HttpRequest and the obj being edited (or None on an add form) and is expected to return a list of two-tuples, in which each two-tuple represents a <fieldset> on the admin form page, as described above in the ModelAdmin.fieldsets section.

ModelAdmin.``get_list_filter(request)

The get_list_filter method is given the HttpRequest and is expected to return the same kind of sequence type as for the list_filter attribute.

ModelAdmin.``get_list_select_related(request)

The get_list_select_related method is given the HttpRequest and should return a boolean or list as ModelAdmin.list_select_related does.

ModelAdmin.``get_search_fields(request)

The get_search_fields method is given the HttpRequest and is expected to return the same kind of sequence type as for the search_fields attribute.

ModelAdmin.``get_sortable_by(request)

The get_sortable_by() method is passed the HttpRequest and is expected to return a collection (e.g. list, tuple, or set) of field names that will be sortable in the change list page.

Its default implementation returns sortable_by if it’s set, otherwise it defers to get_list_display().

For example, to prevent one or more columns from being sortable:

  1. class PersonAdmin(admin.ModelAdmin):
  2. def get_sortable_by(self, request):
  3. return {*self.get_list_display(request)} - {'rank'}

ModelAdmin.``get_inline_instances(request, obj=None)

The get_inline_instances method is given the HttpRequest and the obj being edited (or None on an add form) and is expected to return a list or tuple of InlineModelAdmin objects, as described below in the InlineModelAdmin section. For example, the following would return inlines without the default filtering based on add, change, delete, and view permissions:

  1. class MyModelAdmin(admin.ModelAdmin):
  2. inlines = (MyInline,)
  3. def get_inline_instances(self, request, obj=None):
  4. return [inline(self.model, self.admin_site) for inline in self.inlines]

If you override this method, make sure that the returned inlines are instances of the classes defined in inlines or you might encounter a “Bad Request” error when adding related objects.

ModelAdmin.``get_inlines(request, obj)

New in Django 3.0.

The get_inlines method is given the HttpRequest and the obj being edited (or None on an add form) and is expected to return an iterable of inlines. You can override this method to dynamically add inlines based on the request or model instance instead of specifying them in ModelAdmin.inlines.

ModelAdmin.``get_urls()

The get_urls method on a ModelAdmin returns the URLs to be used for that ModelAdmin in the same way as a URLconf. Therefore you can extend them as documented in URL调度器:

  1. from django.contrib import admin
  2. from django.template.response import TemplateResponse
  3. from django.urls import path
  4. class MyModelAdmin(admin.ModelAdmin):
  5. def get_urls(self):
  6. urls = super().get_urls()
  7. my_urls = [
  8. path('my_view/', self.my_view),
  9. ]
  10. return my_urls + urls
  11. def my_view(self, request):
  12. # ...
  13. context = dict(
  14. # Include common variables for rendering the admin template.
  15. self.admin_site.each_context(request),
  16. # Anything else you want in the context...
  17. key=value,
  18. )
  19. return TemplateResponse(request, "sometemplate.html", context)

If you want to use the admin layout, extend from admin/base_site.html:

  1. {% extends "admin/base_site.html" %}
  2. {% block content %}
  3. ...
  4. {% endblock %}

注解

Notice that the custom patterns are included before the regular admin URLs: the admin URL patterns are very permissive and will match nearly anything, so you’ll usually want to prepend your custom URLs to the built-in ones.

In this example, my_view will be accessed at /admin/myapp/mymodel/my_view/ (assuming the admin URLs are included at /admin/.)

However, the self.my_view function registered above suffers from two problems:

  • It will not perform any permission checks, so it will be accessible to the general public.
  • It will not provide any header details to prevent caching. This means if the page retrieves data from the database, and caching middleware is active, the page could show outdated information.

Since this is usually not what you want, Django provides a convenience wrapper to check permissions and mark the view as non-cacheable. This wrapper is AdminSite.admin_view() (i.e. self.admin_site.admin_view inside a ModelAdmin instance); use it like so:

  1. class MyModelAdmin(admin.ModelAdmin):
  2. def get_urls(self):
  3. urls = super().get_urls()
  4. my_urls = [
  5. path('my_view/', self.admin_site.admin_view(self.my_view))
  6. ]
  7. return my_urls + urls

Notice the wrapped view in the fifth line above:

  1. path('my_view/', self.admin_site.admin_view(self.my_view))

This wrapping will protect self.my_view from unauthorized access and will apply the django.views.decorators.cache.never_cache() decorator to make sure it is not cached if the cache middleware is active.

If the page is cacheable, but you still want the permission check to be performed, you can pass a cacheable=True argument to AdminSite.admin_view():

  1. path('my_view/', self.admin_site.admin_view(self.my_view, cacheable=True))

ModelAdmin views have model_admin attributes. Other AdminSite views have admin_site attributes.

ModelAdmin.``get_form(request, obj=None, \*kwargs*)

Returns a ModelForm class for use in the admin add and change views, see add_view() and change_view().

The base implementation uses modelform_factory() to subclass form, modified by attributes such as fields and exclude. So, for example, if you wanted to offer additional fields to superusers, you could swap in a different base form like so:

  1. class MyModelAdmin(admin.ModelAdmin):
  2. def get_form(self, request, obj=None, **kwargs):
  3. if request.user.is_superuser:
  4. kwargs['form'] = MySuperuserForm
  5. return super().get_form(request, obj, **kwargs)

You may also return a custom ModelForm class directly.

ModelAdmin.``get_formsets_with_inlines(request, obj=None)

Yields (FormSet, InlineModelAdmin) pairs for use in admin add and change views.

For example if you wanted to display a particular inline only in the change view, you could override get_formsets_with_inlines as follows:

  1. class MyModelAdmin(admin.ModelAdmin):
  2. inlines = [MyInline, SomeOtherInline]
  3. def get_formsets_with_inlines(self, request, obj=None):
  4. for inline in self.get_inline_instances(request, obj):
  5. # hide MyInline in the add view
  6. if not isinstance(inline, MyInline) or obj is not None:
  7. yield inline.get_formset(request, obj), inline

ModelAdmin.``formfield_for_foreignkey(db_field, request, \*kwargs*)

The formfield_for_foreignkey method on a ModelAdmin allows you to override the default formfield for a foreign keys field. For example, to return a subset of objects for this foreign key field based on the user:

  1. class MyModelAdmin(admin.ModelAdmin):
  2. def formfield_for_foreignkey(self, db_field, request, **kwargs):
  3. if db_field.name == "car":
  4. kwargs["queryset"] = Car.objects.filter(owner=request.user)
  5. return super().formfield_for_foreignkey(db_field, request, **kwargs)

This uses the HttpRequest instance to filter the Car foreign key field to only display the cars owned by the User instance.

For more complex filters, you can use ModelForm.__init__() method to filter based on an instance of your model (see Fields which handle relationships). For example:

  1. class CountryAdminForm(forms.ModelForm):
  2. def __init__(self, *args, **kwargs):
  3. super().__init__(*args, **kwargs)
  4. self.fields['capital'].queryset = self.instance.cities.all()
  5. class CountryAdmin(admin.ModelAdmin):
  6. form = CountryAdminForm

ModelAdmin.``formfield_for_manytomany(db_field, request, \*kwargs*)

Like the formfield_for_foreignkey method, the formfield_for_manytomany method can be overridden to change the default formfield for a many to many field. For example, if an owner can own multiple cars and cars can belong to multiple owners — a many to many relationship — you could filter the Car foreign key field to only display the cars owned by the User:

  1. class MyModelAdmin(admin.ModelAdmin):
  2. def formfield_for_manytomany(self, db_field, request, **kwargs):
  3. if db_field.name == "cars":
  4. kwargs["queryset"] = Car.objects.filter(owner=request.user)
  5. return super().formfield_for_manytomany(db_field, request, **kwargs)

ModelAdmin.``formfield_for_choice_field(db_field, request, \*kwargs*)

Like the formfield_for_foreignkey and formfield_for_manytomany methods, the formfield_for_choice_field method can be overridden to change the default formfield for a field that has declared choices. For example, if the choices available to a superuser should be different than those available to regular staff, you could proceed as follows:

  1. class MyModelAdmin(admin.ModelAdmin):
  2. def formfield_for_choice_field(self, db_field, request, **kwargs):
  3. if db_field.name == "status":
  4. kwargs['choices'] = (
  5. ('accepted', 'Accepted'),
  6. ('denied', 'Denied'),
  7. )
  8. if request.user.is_superuser:
  9. kwargs['choices'] += (('ready', 'Ready for deployment'),)
  10. return super().formfield_for_choice_field(db_field, request, **kwargs)

注释

Any choices attribute set on the formfield will be limited to the form field only. If the corresponding field on the model has choices set, the choices provided to the form must be a valid subset of those choices, otherwise the form submission will fail with a ValidationError when the model itself is validated before saving.

ModelAdmin.``get_changelist(request, \*kwargs*)

Returns the Changelist class to be used for listing. By default, django.contrib.admin.views.main.ChangeList is used. By inheriting this class you can change the behavior of the listing.

ModelAdmin.``get_changelist_form(request, \*kwargs*)

Returns a ModelForm class for use in the Formset on the changelist page. To use a custom form, for example:

  1. from django import forms
  2. class MyForm(forms.ModelForm):
  3. pass
  4. class MyModelAdmin(admin.ModelAdmin):
  5. def get_changelist_form(self, request, **kwargs):
  6. return MyForm

注释

If you define the Meta.model attribute on a ModelForm, you must also define the Meta.fields attribute (or the Meta.exclude attribute). However, ModelAdmin ignores this value, overriding it with the ModelAdmin.list_editable attribute. The easiest solution is to omit the Meta.model attribute, since ModelAdmin will provide the correct model to use.

ModelAdmin.``get_changelist_formset(request, \*kwargs*)

Returns a ModelFormSet class for use on the changelist page if list_editable is used. To use a custom formset, for example:

  1. from django.forms import BaseModelFormSet
  2. class MyAdminFormSet(BaseModelFormSet):
  3. pass
  4. class MyModelAdmin(admin.ModelAdmin):
  5. def get_changelist_formset(self, request, **kwargs):
  6. kwargs['formset'] = MyAdminFormSet
  7. return super().get_changelist_formset(request, **kwargs)

ModelAdmin.``lookup_allowed(lookup, value)

The objects in the changelist page can be filtered with lookups from the URL’s query string. This is how list_filter works, for example. The lookups are similar to what’s used in QuerySet.filter() (e.g. user__email=user@example.com). Since the lookups in the query string can be manipulated by the user, they must be sanitized to prevent unauthorized data exposure.

The lookup_allowed() method is given a lookup path from the query string (e.g. 'user__email') and the corresponding value (e.g. 'user@example.com'), and returns a boolean indicating whether filtering the changelist’s QuerySet using the parameters is permitted. If lookup_allowed() returns False, DisallowedModelAdminLookup (subclass of SuspiciousOperation) is raised.

By default, lookup_allowed() allows access to a model’s local fields, field paths used in list_filter (but not paths from get_list_filter()), and lookups required for limit_choices_to to function correctly in raw_id_fields.

Override this method to customize the lookups permitted for your ModelAdmin subclass.

ModelAdmin.``has_view_permission(request, obj=None)

Should return True if viewing obj is permitted, False otherwise. If obj is None, should return True or False to indicate whether viewing of objects of this type is permitted in general (e.g., False will be interpreted as meaning that the current user is not permitted to view any object of this type).

The default implementation returns True if the user has either the “change” or “view” permission.

ModelAdmin.``has_add_permission(request)

Should return True if adding an object is permitted, False otherwise.

ModelAdmin.``has_change_permission(request, obj=None)

Should return True if editing obj is permitted, False otherwise. If obj is None, should return True or False to indicate whether editing of objects of this type is permitted in general (e.g., False will be interpreted as meaning that the current user is not permitted to edit any object of this type).

ModelAdmin.``has_delete_permission(request, obj=None)

Should return True if deleting obj is permitted, False otherwise. If obj is None, should return True or False to indicate whether deleting objects of this type is permitted in general (e.g., False will be interpreted as meaning that the current user is not permitted to delete any object of this type).

ModelAdmin.``has_module_permission(request)

Should return True if displaying the module on the admin index page and accessing the module’s index page is permitted, False otherwise. Uses User.has_module_perms() by default. Overriding it does not restrict access to the view, add, change, or delete views, has_view_permission(), has_add_permission(), has_change_permission(), and has_delete_permission() should be used for that.

ModelAdmin.``get_queryset(request)

The get_queryset method on a ModelAdmin returns a QuerySet of all model instances that can be edited by the admin site. One use case for overriding this method is to show objects owned by the logged-in user:

  1. class MyModelAdmin(admin.ModelAdmin):
  2. def get_queryset(self, request):
  3. qs = super().get_queryset(request)
  4. if request.user.is_superuser:
  5. return qs
  6. return qs.filter(author=request.user)

ModelAdmin.``message_user(request, message, level=messages.INFO, extra_tags=’’, fail_silently=False)

Sends a message to the user using the django.contrib.messages backend. See the custom ModelAdmin example.

Keyword arguments allow you to change the message level, add extra CSS tags, or fail silently if the contrib.messages framework is not installed. These keyword arguments match those for django.contrib.messages.add_message(), see that function’s documentation for more details. One difference is that the level may be passed as a string label in addition to integer/constant.

ModelAdmin.``get_paginator(request, queryset, per_page, orphans=0, allow_empty_first_page=True)

Returns an instance of the paginator to use for this view. By default, instantiates an instance of paginator.

ModelAdmin.``response_add(request, obj, post_url_continue=None)

Determines the HttpResponse for the add_view() stage.

response_add is called after the admin form is submitted and just after the object and all the related instances have been created and saved. You can override it to change the default behavior after the object has been created.

ModelAdmin.``response_change(request, obj)

Determines the HttpResponse for the change_view() stage.

response_change is called after the admin form is submitted and just after the object and all the related instances have been saved. You can override it to change the default behavior after the object has been changed.

ModelAdmin.``response_delete(request, obj_display, obj_id)

Determines the HttpResponse for the delete_view() stage.

response_delete is called after the object has been deleted. You can override it to change the default behavior after the object has been deleted.

obj_display is a string with the name of the deleted object.

obj_id is the serialized identifier used to retrieve the object to be deleted.

ModelAdmin.``get_changeform_initial_data(request)

A hook for the initial data on admin change forms. By default, fields are given initial values from GET parameters. For instance, ?name=initial_value will set the name field’s initial value to be initial_value.

This method should return a dictionary in the form {'fieldname': 'fieldval'}:

  1. def get_changeform_initial_data(self, request):
  2. return {'name': 'custom_initial_value'}

ModelAdmin.``get_deleted_objects(objs, request)

A hook for customizing the deletion process of the delete_view() and the “delete selected” action.

The objs argument is a homogeneous iterable of objects (a QuerySet or a list of model instances) to be deleted, and request is the HttpRequest.

This method must return a 4-tuple of (deleted_objects, model_count, perms_needed, protected).

deleted_objects is a list of strings representing all the objects that will be deleted. If there are any related objects to be deleted, the list is nested and includes those related objects. The list is formatted in the template using the unordered_list filter.

model_count is a dictionary mapping each model’s verbose_name_plural to the number of objects that will be deleted.

perms_needed is a set of verbose_names of the models that the user doesn’t have permission to delete.

protected is a list of strings representing of all the protected related objects that can’t be deleted. The list is displayed in the template.

Other methods

ModelAdmin.``add_view(request, form_url=’’, extra_context=None)

Django view for the model instance addition page. See note below.

ModelAdmin.``change_view(request, object_id, form_url=’’, extra_context=None)

Django view for the model instance editing page. See note below.

ModelAdmin.``changelist_view(request, extra_context=None)

Django view for the model instances change list/actions page. See note below.

ModelAdmin.``delete_view(request, object_id, extra_context=None)

Django view for the model instance(s) deletion confirmation page. See note below.

ModelAdmin.``history_view(request, object_id, extra_context=None)

Django view for the page that shows the modification history for a given model instance.

Unlike the hook-type ModelAdmin methods detailed in the previous section, these five methods are in reality designed to be invoked as Django views from the admin application URL dispatching handler to render the pages that deal with model instances CRUD operations. As a result, completely overriding these methods will significantly change the behavior of the admin application.

One common reason for overriding these methods is to augment the context data that is provided to the template that renders the view. In the following example, the change view is overridden so that the rendered template is provided some extra mapping data that would not otherwise be available:

  1. class MyModelAdmin(admin.ModelAdmin):
  2. # A template for a very customized change view:
  3. change_form_template = 'admin/myapp/extras/openstreetmap_change_form.html'
  4. def get_osm_info(self):
  5. # ...
  6. pass
  7. def change_view(self, request, object_id, form_url='', extra_context=None):
  8. extra_context = extra_context or {}
  9. extra_context['osm_data'] = self.get_osm_info()
  10. return super().change_view(
  11. request, object_id, form_url, extra_context=extra_context,
  12. )

These views return TemplateResponse instances which allow you to easily customize the response data before rendering. For more details, see the TemplateResponse documentation.

ModelAdmin asset definitions

There are times where you would like add a bit of CSS and/or JavaScript to the add/change views. This can be accomplished by using a Media inner class on your ModelAdmin:

  1. class ArticleAdmin(admin.ModelAdmin):
  2. class Media:
  3. css = {
  4. "all": ("my_styles.css",)
  5. }
  6. js = ("my_code.js",)

The staticfiles app prepends STATIC_URL (or MEDIA_URL if STATIC_URL is None) to any asset paths. The same rules apply as regular asset definitions on forms.

jQuery

Django admin JavaScript makes use of the jQuery library.

To avoid conflicts with user-supplied scripts or libraries, Django’s jQuery (version 3.5.1) is namespaced as django.jQuery. If you want to use jQuery in your own admin JavaScript without including a second copy, you can use the django.jQuery object on changelist and add/edit views.

Changed in Django 3.0:

jQuery was upgraded from 3.3.1 to 3.4.1.

Changed in Django 3.1:

jQuery was upgraded from 3.4.1 to 3.5.1.

The ModelAdmin class requires jQuery by default, so there is no need to add jQuery to your ModelAdmin’s list of media resources unless you have a specific need. For example, if you require the jQuery library to be in the global namespace (for example when using third-party jQuery plugins) or if you need a newer version of jQuery, you will have to include your own copy.

Django provides both uncompressed and ‘minified’ versions of jQuery, as jquery.js and jquery.min.js respectively.

ModelAdmin and InlineModelAdmin have a media property that returns a list of Media objects which store paths to the JavaScript files for the forms and/or formsets. If DEBUG is True it will return the uncompressed versions of the various JavaScript files, including jquery.js; if not, it will return the ‘minified’ versions.

Adding custom validation to the admin

You can also add custom validation of data in the admin. The automatic admin interface reuses django.forms, and the ModelAdmin class gives you the ability define your own form:

  1. class ArticleAdmin(admin.ModelAdmin):
  2. form = MyArticleAdminForm

MyArticleAdminForm can be defined anywhere as long as you import where needed. Now within your form you can add your own custom validation for any field:

  1. class MyArticleAdminForm(forms.ModelForm):
  2. def clean_name(self):
  3. # do something that validates your data
  4. return self.cleaned_data["name"]

It is important you use a ModelForm here otherwise things can break. See the forms documentation on custom validation and, more specifically, the model form validation notes for more information.

InlineModelAdmin objects

class InlineModelAdmin

class TabularInline

class StackedInline

The admin interface has the ability to edit models on the same page as a parent model. These are called inlines. Suppose you have these two models:

  1. from django.db import models
  2. class Author(models.Model):
  3. name = models.CharField(max_length=100)
  4. class Book(models.Model):
  5. author = models.ForeignKey(Author, on_delete=models.CASCADE)
  6. title = models.CharField(max_length=100)

You can edit the books authored by an author on the author page. You add inlines to a model by specifying them in a ModelAdmin.inlines:

  1. from django.contrib import admin
  2. class BookInline(admin.TabularInline):
  3. model = Book
  4. class AuthorAdmin(admin.ModelAdmin):
  5. inlines = [
  6. BookInline,
  7. ]

Django provides two subclasses of InlineModelAdmin and they are:

The difference between these two is merely the template used to render them.

InlineModelAdmin options

InlineModelAdmin shares many of the same features as ModelAdmin, and adds some of its own (the shared features are actually defined in the BaseModelAdmin superclass). The shared features are:

The InlineModelAdmin class adds or customizes:

InlineModelAdmin.``model

The model which the inline is using. This is required.

InlineModelAdmin.``fk_name

The name of the foreign key on the model. In most cases this will be dealt with automatically, but fk_name must be specified explicitly if there are more than one foreign key to the same parent model.

InlineModelAdmin.``formset

This defaults to BaseInlineFormSet. Using your own formset can give you many possibilities of customization. Inlines are built around model formsets.

InlineModelAdmin.``form

The value for form defaults to ModelForm. This is what is passed through to inlineformset_factory() when creating the formset for this inline.

警告

When writing custom validation for InlineModelAdmin forms, be cautious of writing validation that relies on features of the parent model. If the parent model fails to validate, it may be left in an inconsistent state as described in the warning in 验证 ModelForm.

InlineModelAdmin.``classes

A list or tuple containing extra CSS classes to apply to the fieldset that is rendered for the inlines. Defaults to None. As with classes configured in fieldsets, inlines with a collapse class will be initially collapsed and their header will have a small “show” link.

InlineModelAdmin.``extra

This controls the number of extra forms the formset will display in addition to the initial forms. Defaults to 3. See the formsets documentation for more information.

For users with JavaScript-enabled browsers, an “Add another” link is provided to enable any number of additional inlines to be added in addition to those provided as a result of the extra argument.

The dynamic link will not appear if the number of currently displayed forms exceeds max_num, or if the user does not have JavaScript enabled.

InlineModelAdmin.get_extra() also allows you to customize the number of extra forms.

InlineModelAdmin.``max_num

This controls the maximum number of forms to show in the inline. This doesn’t directly correlate to the number of objects, but can if the value is small enough. See 限制可编辑对象的数量 for more information.

InlineModelAdmin.get_max_num() also allows you to customize the maximum number of extra forms.

InlineModelAdmin.``min_num

This controls the minimum number of forms to show in the inline. See modelformset_factory() for more information.

InlineModelAdmin.get_min_num() also allows you to customize the minimum number of displayed forms.

InlineModelAdmin.``raw_id_fields

By default, Django’s admin uses a select-box interface (