The Django admin site

One of the most powerful parts of Django is the automatic admin interface. Itreads metadata from your models to provide a quick, model-centric interfacewhere trusted users can manage content on your site. The admin's recommendeduse is limited to an organization's internal management tool. It's not intendedfor building your entire front end around.

The admin has many hooks for customization, but beware of trying to use thosehooks exclusively. If you need to provide a more process-centric interfacethat 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 admininterface.

Overview

The admin is enabled in the default project template used bystartproject.

For reference, here are the requirements:

Other topics

See also

For information about serving the static files (images, JavaScript, andCSS) associated with the admin in production, see Serving files.

Having problems? Try FAQ: 管理.

ModelAdmin objects

  • class ModelAdmin[source]
  • The ModelAdmin class is the representation of a model in the admininterface. Usually, these are stored in a file named admin.py in yourapplication. Let's take a look at a very simple example ofthe ModelAdmin:
  1. from django.contrib import admin
  2. from myproject.myapp.models import Author
  3.  
  4. class AuthorAdmin(admin.ModelAdmin):
  5. pass
  6. admin.site.register(Author, AuthorAdmin)

Do you need a ModelAdmin object at all?

In the preceding example, the ModelAdmin class doesn't define anycustom values (yet). As a result, the default admin interface will beprovided. If you are happy with the default admin interface, you don'tneed to define a ModelAdmin object at all — you can register themodel class without providing a ModelAdmin description. Thepreceding example could be simplified to:

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

The register decorator

  • register(*models, site=django.admin.sites.site)[source]
  • There is also a decorator for registering your ModelAdmin classes:
  1. from django.contrib import admin
  2. from .models import Author
  3.  
  4. @admin.register(Author)
  5. class AuthorAdmin(admin.ModelAdmin):
  6. 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 keywordargument:

  1. from django.contrib import admin
  2. from .models import Author, Editor, Reader
  3. from myproject.admin_site import custom_admin_site
  4.  
  5. @admin.register(Author, Reader, Editor, site=custom_admin_site)
  6. class PersonAdmin(admin.ModelAdmin):
  7. pass

You can't use this decorator if you have to reference your model adminclass in its init() method, e.g.super(PersonAdmin, self).init(args, **kwargs). You can usesuper().init(args, **kwargs).

Discovery of admin files

When you put 'django.contrib.admin' in your INSTALLED_APPSsetting, Django automatically looks for an admin module in eachapplication 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().

  • autodiscover()[source]

  • This function attempts to import an admin module in each installedapplication. Such modules are expected to register models with the admin.

Typically you won't need to call this function directly asAdminConfig calls it when Django starts.

If you are using a custom AdminSite, it is common to import all of theModelAdmin subclasses into your code and register them to the customAdminSite. In that case, in order to disable auto-discovery, you shouldput '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 withcustomizing the interface. All options are defined on the ModelAdminsubclass:

  1. from django.contrib import admin
  2.  
  3. class AuthorAdmin(admin.ModelAdmin):
  4. date_hierarchy = 'pub_date'
  • ModelAdmin.actions
  • A list of actions to make available on the change list page. SeeAdmin actions for details.

  • ModelAdmin.actions_on_top

  • ModelAdmin.actions_on_bottom
  • Controls where on the page the actions bar appears. By default, the adminchangelist 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 DateTimeFieldin your model, and the change list page will include a date-based drilldownnavigation by that field.

Example:

  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-leveldrill-down only.

Changed in Django 1.11:The ability to reference fields on related models was added.

Note

date_hierarchy uses QuerySet.datetimes() internally. Please referto its documentation for some caveats when time zone support isenabled (USE_TZ = True).

  • ModelAdmin.empty_value_display
  • This attribute overrides the default display value for record's fields thatare empty (None, empty string, etc.). The default value is - (adash). For example:
  1. from django.contrib import admin
  2.  
  3. class AuthorAdmin(admin.ModelAdmin):
  4. empty_value_display = '-empty-'

You can also override empty_value_display for all admin pages withAdminSite.empty_value_display, or for specific fields like this:

  1. from django.contrib import admin
  2.  
  3. class AuthorAdmin(admin.ModelAdmin):
  4. fields = ('name', 'title', 'view_birth_date')
  5.  
  6. def view_birth_date(self, obj):
  7. return obj.birth_date
  8.  
  9. view_birth_date.empty_value_display = '???'
  • ModelAdmin.exclude
  • This attribute, if given, should be a list of field names to exclude fromthe form.

For example, let's consider the following model:

  1. from django.db import models
  2.  
  3. class Author(models.Model):
  4. name = models.CharField(max_length=100)
  5. title = models.CharField(max_length=3)
  6. birth_date = models.DateField(blank=True, null=True)

If you want a form for the Author model that includes only the nameand title fields, you would specify fields or exclude likethis:

  1. from django.contrib import admin
  2.  
  3. class AuthorAdmin(admin.ModelAdmin):
  4. fields = ('name', 'title')
  5.  
  6. class AuthorAdmin(admin.ModelAdmin):
  7. exclude = ('birth_date',)

Since the Author model only has three fields, name, title, andbirth_date, the forms resulting from the above declarations willcontain exactly the same fields.

  • ModelAdmin.fields
  • Use the fields option to make simple layout changes in the forms onthe "add" and "change" pages such as showing only a subset of availablefields, modifying their order, or grouping them into rows. For example, youcould define a simpler version of the admin form for thedjango.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 contentwill be displayed, sequentially, in the form. fields can containvalues defined in ModelAdmin.readonly_fields to be displayed asread-only.

For more complex layout needs, see the fieldsets option.

The fields option, unlike list_display, may onlycontain names of fields on the model or the form specified byform. It may contain callables only if they are listedin readonly_fields.

To display multiple fields on the same line, wrap those fields in their owntuple. In this example, the url and title fields will display on thesame line and the content field will be displayed below them on itsown line:

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

Note

This fields option should not be confused with the fieldsdictionary 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 andhas editable=True, in a single fieldset, in the same order as the fieldsare 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" ofthe form.)

The two-tuples are in the format (name, field_options), where nameis a string representing the title of the fieldset and field_options isa dictionary of information about the fieldset, including a list of fieldsto be displayed in it.

A full example, taken from thedjango.contrib.flatpages.models.FlatPage model:

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

This results in an admin page that looks like:../../../_images/fieldsets.pngIf neither fieldsets nor fields options are present,Django will default to displaying each field that isn't an AutoField andhas editable=True, in a single fieldset, in the same order as the fieldsare 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 isrequired.

Example:

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

As with the fields option, to display multiplefields on the same line, wrap those fields in their own tuple. In thisexample, the first_name and last_name fields will display onthe same line:

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

fields can contain values defined inreadonly_fields to be displayed as read-only.

If you add the name of a callable to fields, the same rule appliesas with the fields option: the callable must belisted in readonly_fields.

    • classes
    • A list or tuple containing extra CSS classes to apply to the fieldset.

Example:

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

Two useful classes defined by the default admin site stylesheet arecollapse and wide. Fieldsets with the collapse stylewill be initially collapsed in the admin and replaced with a small"click to expand" link. Fieldsets with the wide style will begiven extra horizontal space.

    • description
    • A string of optional extra text to be displayed at the top of eachfieldset, under the heading of the fieldset. This string is notrendered for TabularInline due to itslayout.

Note that this value is not HTML-escaped when it's displayed inthe admin interface. This lets you include HTML if you so desire.Alternatively you can use plain text anddjango.utils.html.escape() to escape any HTML specialcharacters.

  • ModelAdmin.filter_horizontal
  • By default, a ManyToManyField is displayed inthe admin site with a <select multiple>. However, multiple-select boxescan be difficult to use when selecting many items. Adding aManyToManyField to this list will instead usea nifty unobtrusive JavaScript "filter" interface that allows searchingwithin the options. The unselected and selected options appear in two boxesside by side. See filter_vertical to use a verticalinterface.

  • ModelAdmin.filter_vertical

  • Same as filter_horizontal, but uses a vertical displayof the filter interface with the box of unselected options appearing abovethe box of selected options.

  • ModelAdmin.form

  • By default a ModelForm is dynamically created for your model. It isused to create the form presented on both the add/change pages. You caneasily provide your own ModelForm to override any default form behavioron the add/change pages. Alternatively, you can customize the defaultform rather than specifying an entirely new one by using theModelAdmin.get_form() method.

For an example see the section Adding custom validation to the admin.

Note

If you define the Meta.model attribute on aModelForm, you must also define theMeta.fields attribute (or the Meta.exclude attribute). However,since the admin has its own way of defining fields, the Meta.fieldsattribute will be ignored.

If the ModelForm is only going to be used for the admin, the easiestsolution is to omit the Meta.model attribute, since ModelAdminwill provide the correct model to use. Alternatively, you can setfields = [] in the Meta class to satisfy the validation on theModelForm.

Note

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

  1. from django import forms
  2. from django.contrib import admin
  3. from myapp.models import Person
  4.  
  5. class PersonForm(forms.ModelForm):
  6.  
  7. class Meta:
  8. model = Person
  9. exclude = ['name']
  10.  
  11. class PersonAdmin(admin.ModelAdmin):
  12. exclude = ['age']
  13. 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 theField options for use in the admin.formfield_overrides is a dictionary mapping a field class to a dict ofarguments to pass to the field at construction time.

Since that's a bit abstract, let's look at a concrete example. The mostcommon use of formfield_overrides is to add a custom widget for acertain type of field. So, imagine we've written a RichTextEditorWidgetthat 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.  
  4. # Import our custom widget and our model from where they're defined
  5. from myapp.models import MyModel
  6. from myapp.widgets import RichTextEditorWidget
  7.  
  8. class MyModelAdmin(admin.ModelAdmin):
  9. formfield_overrides = {
  10. models.TextField: {'widget': RichTextEditorWidget},
  11. }

Note that the key in the dictionary is the actual field class, not astring. The value is another dictionary; these arguments will be passed tothe form field's init() method. See The Forms API fordetails.

Warning

If you want to use a custom widget with a relation field (i.e.ForeignKey orManyToManyField), make sure you haven'tincluded that field's name in raw_id_fields, radio_fields, orautocomplete_fields.

formfield_overrides won't let you change the widget on relationfields that have raw_id_fields, radio_fields, orautocomplete_fields set. That's because raw_id_fields,radio_fields, and autocomplete_fields imply custom widgets oftheir own.

Example:

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

If you don't set listdisplay, the admin site will display a singlecolumn that displays the _str() representation of each object.

You have four possible values that can be used in list_display:

  • A field of the model. For example:
  1. class PersonAdmin(admin.ModelAdmin):
  2. list_display = ('first_name', 'last_name')
  • A callable that accepts one parameter for the model instance. Forexample:
  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.  
  5. class PersonAdmin(admin.ModelAdmin):
  6. list_display = (upper_case_name,)
  • A string representing an attribute on the ModelAdmin. Thisbehaves same as the callable. For example:
  1. class PersonAdmin(admin.ModelAdmin):
  2. list_display = ('upper_case_name',)
  3.  
  4. def upper_case_name(self, obj):
  5. return ("%s %s" % (obj.first_name, obj.last_name)).upper()
  6. upper_case_name.short_description = 'Name'
  • A string representing an attribute on the model. This behaves almostthe same as the callable, but self in this context is the modelinstance. Here's a full model example:
  1. from django.contrib import admin
  2. from django.db import models
  3.  
  4. class Person(models.Model):
  5. name = models.CharField(max_length=50)
  6. birthday = models.DateField()
  7.  
  8. def decade_born_in(self):
  9. return self.birthday.strftime('%Y')[:3] + "0's"
  10. decade_born_in.short_description = 'Birth decade'
  11.  
  12. class PersonAdmin(admin.ModelAdmin):
  13. list_display = ('name', 'decade_born_in')

A few special cases to note about list_display:

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

  • ManyToManyField fields aren't supported, because that wouldentail 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 moreon custom methods in list_display.)

  • If the field is a BooleanField or NullBooleanField, Djangowill display a pretty "on" or "off" icon instead of True orFalse.

  • If the string given is a method of the model, ModelAdmin or acallable, Django will HTML-escape the output by default. To escapeuser input and allow your own unescaped tags, useformat_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.  
  5. class Person(models.Model):
  6. first_name = models.CharField(max_length=50)
  7. last_name = models.CharField(max_length=50)
  8. color_code = models.CharField(max_length=6)
  9.  
  10. def colored_name(self):
  11. return format_html(
  12. '<span style="color: #{};">{} {}</span>',
  13. self.color_code,
  14. self.first_name,
  15. self.last_name,
  16. )
  17.  
  18. class PersonAdmin(admin.ModelAdmin):
  19. list_display = ('first_name', 'last_name', 'colored_name')
  • As some examples have already demonstrated, when using a callable, amodel method, or a ModelAdmin method, you can customize the column'stitle by adding a short_description attribute to the callable.

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

  1. from django.contrib import admin
  2.  
  3. 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.  
  4. def birth_date_view(self, obj):
  5. return obj.birth_date
  6.  
  7. birth_date_view.empty_value_display = 'unknown'
  • If the string given is a method of the model, ModelAdmin or acallable that returns True or False Django will display a pretty"on" or "off" icon if you give the method a boolean attributewhose value is True.

Here's a full example model:

  1. from django.contrib import admin
  2. from django.db import models
  3.  
  4. class Person(models.Model):
  5. first_name = models.CharField(max_length=50)
  6. birthday = models.DateField()
  7.  
  8. def born_in_fifties(self):
  9. return self.birthday.strftime('%Y')[:3] == '195'
  10. born_in_fifties.boolean = True
  11.  
  12. class PersonAdmin(admin.ModelAdmin):
  13. list_display = ('name', 'born_in_fifties')
  • The str() method is just as valid in list_display as anyother 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 databasefields can't be used in sorting (because Django does all the sortingat the database level).

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

For example:

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

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

To indicate descending order with admin_order_field you can use ahyphen prefix on the field name. Using the above example, this wouldlook like:

  1. colored_first_name.admin_order_field = '-first_name'

admin_order_field supports query lookups to sort by values on relatedmodels. This example includes an "author first name" column in the listdisplay 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.  
  5. class BlogAdmin(admin.ModelAdmin):
  6. list_display = ('title', 'author', 'author_first_name')
  7.  
  8. def author_first_name(self, obj):
  9. return obj.author.first_name
  10.  
  11. author_first_name.admin_order_field = 'author__first_name'
  • Elements of list_display can also be properties. Please note however,that due to the way properties work in Python, settingshort_description on a property is only possible when using theproperty() function and not with the @property decorator.

For example:

  1. class Person(models.Model):
  2. first_name = models.CharField(max_length=50)
  3. last_name = models.CharField(max_length=50)
  4.  
  5. def my_property(self):
  6. return self.first_name + ' ' + self.last_name
  7. my_property.short_description = "Full name of the person"
  8.  
  9. full_name = property(my_property)
  10.  
  11. class PersonAdmin(admin.ModelAdmin):
  12. list_display = ('full_name',)
  • The field names in list_display will also appear as CSS classes inthe 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 thisorder:

    • 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 andas a ModelAdmin attribute, the model field will be used.
  • ModelAdmin.list_display_links
  • Use list_display_links to control if and which fields inlist_display should be linked to the "change" page for an object.

By default, the change list page will link the first column — the firstfield 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 aslist_display) whose columns you want converted to links.

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

In this example, the first_name and last_name fields will belinked 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 willallow editing on the change list page. That is, fields listed inlist_editable will be displayed as form widgets on the change listpage, allowing users to edit and save multiple rows at once.

Note

list_editable interacts with a couple of other options inparticular 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 andlist_display_links — a field can't be both a form anda 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 changelist page of the admin, as illustrated in the following screenshot:../../../_images/list_filter.pnglist_filter should be a list or tuple of elements, where each elementshould be of one of the following types:

    • a field name, where the specified field should be either aBooleanField, CharField, DateField, DateTimeField,IntegerField, ForeignKey or ManyToManyField, for example:
  1. class PersonAdmin(admin.ModelAdmin):
  2. list_filter = ('is_staff', 'company')

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

Note

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

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

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

  1. class AdvancedDecadeBornListFilter(DecadeBornListFilter):
  2.  
  3. def lookups(self, request, model_admin):
  4. """
  5. Only show the lookups if there actually is
  6. anyone born in the corresponding decades.
  7. """
  8. qs = model_admin.get_queryset(request)
  9. if qs.filter(birthday__gte=date(1980, 1, 1),
  10. birthday__lte=date(1989, 12, 31)).exists():
  11. yield ('80s', _('in the eighties'))
  12. if qs.filter(birthday__gte=date(1990, 1, 1),
  13. birthday__lte=date(1999, 12, 31)).exists():
  14. yield ('90s', _('in the nineties'))
  • a tuple, where the first element is a field name and the secondelement is a class inheriting fromdjango.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 inthat 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 willlimit the list_filter choices to the users who have written a bookinstead of listing all users.

Note

The FieldListFilter API is considered internal and might bechanged.

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) fora concrete example.

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

  • ModelAdmin.list_per_page

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

  • ModelAdmin.list_select_related

  • Set list_select_related to tell Django to useselect_related() in retrievingthe list of objects on the admin change list page. This can save you abunch of database queries.

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

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

If you need more fine-grained control, use a tuple (or list) as value forlist_select_related. Empty tuple will prevent Django from callingselect_related at all. Any other tuple will be passed directly toselect_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 canimplement a get_list_select_related() method.

  • ModelAdmin.ordering
  • Set ordering to specify how lists of objects should be ordered in theDjango admin views. This should be a list or tuple in the same format as amodel's ordering parameter.

If this isn't provided, the Django admin will use the model's defaultordering.

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

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

When set, the given fields will use a bit of JavaScript to populate fromthe fields assigned. The main use for this functionality is toautomatically generate the value for SlugField fields from one or moreother fields. The generated value is produced by concatenating the valuesof the source fields, and then by transforming that result into a validslug (e.g. substituting dashes for spaces; lowercasing ASCII letters; andremoving various English stop words such as 'a', 'an', 'as', and similar).

Fields are prepopulated on add forms but not on change forms. It's usuallyundesired that slugs change after an object is created (which would causean 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
  • The admin now preserves filters on the list view after creating, editingor deleting an object. You can restore the previous behavior of clearingfilters by setting this attribute to False.

  • ModelAdmin.radio_fields

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

    • ModelAdmin.autocomplete_fields
    • New in Django 2.0.

    autocomplete_fields is a list of ForeignKey and/orManyToManyField fields you would like to change to Select2 autocomplete inputs.

    By default, the admin uses a select-box interface (<select>) forthose fields. Sometimes you don't want to incur the overhead of selectingall the related instances to display in the dropdown.

    The Select2 input looks similar to the default input but comes with asearch feature that loads the options asynchronously. This is faster andmore user-friendly if the related model has many instances.

    You must define search_fields on the related object'sModelAdmin because the autocomplete search uses it.

    Ordering and pagination of the results are controlled by the relatedModelAdmin's get_ordering() andget_paginator() methods.

    In the following example, ChoiceAdmin has an autocomplete field for theForeignKey to the Question. The results are filtered by thequestion_text field and ordered by the date_created field:

    1. class QuestionAdmin(admin.ModelAdmin):
    2. ordering = ['date_created']
    3. search_fields = ['question_text']
    4.  
    5. class ChoiceAdmin(admin.ModelAdmin):
    6. autocomplete_fields = ['question']

    Performance considerations for large datasets

    Ordering using ModelAdmin.ordering may cause performanceproblems as sorting on a large queryset will be slow.

    Also, if your search fields include fields that aren't indexed by thedatabase, you might encounter poor performance on extremely largetables.

    For those cases, it's a good idea to write your ownModelAdmin.get_search_results() implementation using afull-text indexed search.

    You may also want to change the Paginator on very large tablesas the default paginator always performs a count() query.For example, you could override the default implementation of thePaginator.count property.

    • ModelAdmin.raw_id_fields
    • By default, Django's admin uses a select-box interface (

      • ModelAdmin.readonly_fields
      • By default the admin shows all fields as editable. Any fields in thisoption (which should be a list or tuple) will display its dataas-is and non-editable; they are also excluded from theModelForm used for creating and editing. Note thatwhen specifying ModelAdmin.fields or ModelAdmin.fieldsetsthe read-only fields must be present to be shown (they are ignoredotherwise).

      If readonly_fields is used without defining explicit ordering throughModelAdmin.fields or ModelAdmin.fieldsets they will beadded last after all editable fields.

      A read-only field can not only display data from a model's field, it canalso display the output of a model's method or a method of theModelAdmin class itself. This is very similar to the wayModelAdmin.list_display behaves. This provides an easy way to usethe admin interface to provide feedback on the status of the objects beingedited, 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.  
      5. class PersonAdmin(admin.ModelAdmin):
      6. readonly_fields = ('address_report',)
      7.  
      8. def address_report(self, instance):
      9. # assuming get_full_address() returns a list of strings
      10. # for each line of the address and you want to separate each
      11. # line by a linebreak
      12. return format_html_join(
      13. mark_safe('<br/>'),
      14. '{}',
      15. ((line,) for line in instance.get_full_address()),
      16. ) or mark_safe("<span class='errors'>I can't determine this address.</span>")
      17.  
      18. # short_description functions like a model field's verbose_name
      19. 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 continueediting", and "Save and add another". If save_as is True, "Saveand add another" will be replaced by a "Save as new" button that creates anew 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 thenew object is to the change view for that object. If you setsave_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 changeforms.

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

      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 wheneversomebody submits a search query in that text box.

      These fields should be some kind of text field, such as CharField orTextField. You can also perform a related lookup on a ForeignKey orManyToManyField 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 followingdefinition would enable searching blog entries by the email address of theauthor:

      1. search_fields = ['user__email']

      When somebody does a search in the admin search box, Django splits thesearch query into words and returns all objects that contain each of thewords, case insensitive, where each word must be in at least one ofsearch_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%')

      For faster and/or more restrictive searches, prefix the field namewith an operator:

      • ^
      • Use the '^' operator to match starting at the beginning of thefield. For example, if search_fields is set to['^first_name', '^last_name'] and a user searches forjohn lennon, Django will do the equivalent of this SQL WHEREclause:
      1. WHERE (first_name ILIKE 'john%' OR last_name ILIKE 'john%')
      2. AND (first_name ILIKE 'lennon%' OR last_name ILIKE 'lennon%')

      This query is more efficient than the normal '%john%' query,because the database only needs to check the beginning of a column'sdata, rather than seeking through the entire column's data. Plus, ifthe column has an index on it, some databases may be able to use theindex for this query, even though it's a LIKE query.

      • =
      • Use the '=' operator for case-insensitive exact matching. Forexample, if search_fields is set to['=first_name', '=last_name'] and a user searches forjohn lennon, Django will do the equivalent of this SQLWHERE clause:
      1. WHERE (first_name ILIKE 'john' OR last_name ILIKE 'john')
      2. AND (first_name ILIKE 'lennon' OR last_name ILIKE 'lennon')

      Note that the query input is split by spaces, so, following thisexample, it's currently not possible to search for all records in whichfirst_name is exactly 'john winston' (containing a space).

      • @
      • Using the '@' operator to perform a full text match. This is like thedefault search method but uses an index. Currently this is onlyavailable for MySQL.If you need to customize search you can useModelAdmin.get_search_results() to provide additional or alternatesearch behavior.
      • ModelAdmin.show_full_result_count
      • Set show_full_result_count to control whether the full count of objectsshould 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 performa full count on the table which can be expensive if the table contains alarge number of rows.

      • 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 (thedefault), the object's get_absolute_url()method will be used to generate the url.

      If your model has a get_absolute_url() methodbut you don't want the "View on site" button to appear, you only need to setview_on_site to False:

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

      Custom template options

      The Overriding admin templates section describes how to override or extendthe default admin templates. Use the following options to override the defaulttemplates 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 aconfirmation page when deleting one or more objects.

      • ModelAdmin.delete_selected_confirmation_template

      • Path to a custom template, used by the delete_selected action methodfor displaying a confirmation page when deleting one or more objects. Seethe actions documentation.

      • ModelAdmin.object_history_template

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

      • ModelAdmin.popup_response_template

      • New in Django 1.11.

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

      ModelAdmin methods

      Warning

      When overriding ModelAdmin.save_model() andModelAdmin.delete_model(), your code must save/delete theobject. They aren't meant for veto purposes, rather they allow you toperform extra operations.

      • ModelAdmin.savemodel(_request, obj, form, change)[source]
      • The save_model method is given the HttpRequest, a model instance,a ModelForm instance, and a boolean value based on whether it is addingor changing the object. Overriding this method allows doing pre- orpost-save operations. Call super().save_model() to save the objectusing Model.save().

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

      1. from django.contrib import admin
      2.  
      3. class ArticleAdmin(admin.ModelAdmin):
      4. def save_model(self, request, obj, form, change):
      5. obj.user = request.user
      6. super().save_model(request, obj, form, change)
      • ModelAdmin.deletemodel(_request, obj)[source]
      • The delete_model method is given the HttpRequest and a modelinstance. Overriding this method allows doing pre- or post-deleteoperations. Call super().delete_model() to delete the object usingModel.delete().

      • ModelAdmin.saveformset(_request, form, formset, change)[source]

      • The save_formset method is given the HttpRequest, the parentModelForm instance and a boolean value based on whether it is adding orchanging the parent object.

      For example, to attach request.user to each changed formsetmodel 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 Saving objects in the formset.

      • ModelAdmin.getordering(_request)
      • The get_ordering method takes a request as parameter andis expected to return a list or tuple for ordering similarto the ordering attribute. For example:
      1. class PersonAdmin(admin.ModelAdmin):
      2.  
      3. def get_ordering(self, request):
      4. if request.user.is_superuser:
      5. return ['name', 'rank']
      6. else:
      7. return ['name']
      • ModelAdmin.getsearch_results(_request, queryset, search_term)[source]
      • The get_search_results method modifies the list of objects displayedinto those that match the provided search term. It accepts the request, aqueryset that applies the current filters, and the user-provided search term.It returns a tuple containing a queryset modified to implement the search, anda 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. Forexample, you might wish to search by an integer field, or use an externaltool such as Solr or Haystack. You must establish if the queryset changesimplemented 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.  
      5. def get_search_results(self, request, queryset, search_term):
      6. queryset, use_distinct = super().get_search_results(request, queryset, search_term)
      7. try:
      8. search_term_as_int = int(search_term)
      9. except ValueError:
      10. pass
      11. else:
      12. queryset |= self.model.objects.filter(age=search_term_as_int)
      13. return queryset, use_distinct

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

      • ModelAdmin.saverelated(_request, form, formsets, change)[source]
      • The save_related method is given the HttpRequest, the parentModelForm instance, the list of inline formsets and a boolean valuebased on whether the parent is being added or changed. Here you can do anypre- or post-save operations for objects related to the parent. Notethat at this point the parent object and its form have already been saved.

      • ModelAdmin.getautocomplete_fields(_request)

      • New in Django 2.0.

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

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

      • ModelAdmin.getprepopulated_fields(_request, obj=None)

      • The get_prepopulated_fields method is given the HttpRequest and theobj being edited (or None on an add form) and is expected to returna dictionary, as described above in the ModelAdmin.prepopulated_fieldssection.

      • ModelAdmin.getlist_display(_request)[source]

      • The get_list_display method is given the HttpRequest and isexpected to return a list or tuple of field names that will bedisplayed on the changelist view as described above in theModelAdmin.list_display section.

      • ModelAdmin.getlist_display_links(_request, list_display)[source]

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

      • ModelAdmin.getexclude(_request, obj=None)

      • New in Django 1.11.

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

      • ModelAdmin.getfields(_request, obj=None)
      • The get_fields method is given the HttpRequest and the objbeing edited (or None on an add form) and is expected to return a listof fields, as described above in the ModelAdmin.fields section.

      • ModelAdmin.getfieldsets(_request, obj=None)

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

      • ModelAdmin.getlist_filter(_request)[source]

      • The get_list_filter method is given the HttpRequest and is expectedto return the same kind of sequence type as for thelist_filter attribute.

      • ModelAdmin.getlist_select_related(_request)[source]

      • The get_list_select_related method is given the HttpRequest andshould return a boolean or list as ModelAdmin.list_select_relateddoes.

      • ModelAdmin.getsearch_fields(_request)[source]

      • The get_search_fields method is given the HttpRequest and is expectedto return the same kind of sequence type as for thesearch_fields attribute.

      • ModelAdmin.getinline_instances(_request, obj=None)[source]

      • The get_inline_instances method is given the HttpRequest and theobj being edited (or None on an add form) and is expected to returna list or tuple of InlineModelAdminobjects, as described below in the InlineModelAdminsection. For example, the following would return inlines without the defaultfiltering based on add, change, and delete permissions:
      1. class MyModelAdmin(admin.ModelAdmin):
      2. inlines = (MyInline,)
      3.  
      4. def get_inline_instances(self, request, obj=None):
      5. return [inline(self.model, self.admin_site) for inline in self.inlines]

      If you override this method, make sure that the returned inlines areinstances of the classes defined in inlines or you might encountera "Bad Request" error when adding related objects.

      • ModelAdmin.get_urls()[source]
      • The get_urls method on a ModelAdmin returns the URLs to be used forthat ModelAdmin in the same way as a URLconf. Therefore you can extendthem as documented in URL调度器:
      1. from django.contrib import admin
      2. from django.template.response import TemplateResponse
      3. from django.urls import path
      4.  
      5. class MyModelAdmin(admin.ModelAdmin):
      6. def get_urls(self):
      7. urls = super().get_urls()
      8. my_urls = [
      9. path('my_view/', self.my_view),
      10. ]
      11. return my_urls + urls
      12.  
      13. def my_view(self, request):
      14. # ...
      15. context = dict(
      16. # Include common variables for rendering the admin template.
      17. self.admin_site.each_context(request),
      18. # Anything else you want in the context...
      19. key=value,
      20. )
      21. 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 %}

      Note

      Notice that the custom patterns are included before the regular adminURLs: the admin URL patterns are very permissive and will match nearlyanything, so you'll usually want to prepend your custom URLs to thebuilt-in ones.

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

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

      • It will not perform any permission checks, so it will be accessibleto the general public.
      • It will not provide any header details to prevent caching. This meansif the page retrieves data from the database, and caching middleware isactive, the page could show outdated information.Since this is usually not what you want, Django provides a conveniencewrapper to check permissions and mark the view as non-cacheable. Thiswrapper is AdminSite.admin_view() (i.e. self.admin_site.admin_viewinside 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 andwill apply the django.views.decorators.cache.never_cache() decorator tomake sure it is not cached if the cache middleware is active.

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

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

      ModelAdmin views have model_admin attributes. OtherAdminSite views have admin_site attributes.

      The base implementation uses modelform_factory()to subclass form, modified by attributes such as fieldsand exclude. So, for example, if you wanted to offer additionalfields 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 simply return a custom ModelForm classdirectly.

      • ModelAdmin.getformsets_with_inlines(_request, obj=None)[source]
      • Yields (FormSet, InlineModelAdmin) pairs for use in admin addand change views.

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

      1. class MyModelAdmin(admin.ModelAdmin):
      2. inlines = [MyInline, SomeOtherInline]
      3.  
      4. def get_formsets_with_inlines(self, request, obj=None):
      5. for inline in self.get_inline_instances(request, obj):
      6. # hide MyInline in the add view
      7. if isinstance(inline, MyInline) and obj is None:
      8. continue
      9. yield inline.get_formset(request, obj), inline
      • ModelAdmin.formfieldfor_foreignkey(_db_field, request, **kwargs)
      • The formfield_for_foreignkey method on a ModelAdmin allows you tooverride the default formfield for a foreign keys field. For example, toreturn 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 keyfield to only display the cars owned by the User instance.

      • ModelAdmin.formfieldfor_manytomany(_db_field, request, **kwargs)
      • Like the formfield_for_foreignkey method, theformfield_for_manytomany method can be overridden to change thedefault formfield for a many to many field. For example, if an owner canown multiple cars and cars can belong to multiple owners — a many tomany relationship — you could filter the Car foreign key field toonly 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.formfieldfor_choice_field(_db_field, request, **kwargs)
      • Like the formfield_for_foreignkey and formfield_for_manytomanymethods, the formfield_for_choice_field method can be overridden tochange the default formfield for a field that has declared choices. Forexample, if the choices available to a superuser should be different thanthose 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)

      Note

      Any choices attribute set on the formfield will be limited to theform field only. If the corresponding field on the model has choicesset, the choices provided to the form must be a valid subset of thosechoices, otherwise the form submission will fail witha ValidationError when the model itselfis validated before saving.

      • ModelAdmin.getchangelist(_request, **kwargs)[source]
      • Returns the Changelist class to be used for listing. By default,django.contrib.admin.views.main.ChangeList is used. By inheriting thisclass you can change the behavior of the listing.

      • ModelAdmin.getchangelist_form(_request, **kwargs)[source]

      • Returns a ModelForm class for use in the Formseton the changelist page. To use a custom form, for example:
      1. from django import forms
      2.  
      3. class MyForm(forms.ModelForm):
      4. pass
      5.  
      6. class MyModelAdmin(admin.ModelAdmin):
      7. def get_changelist_form(self, request, **kwargs):
      8. return MyForm

      Note

      If you define the Meta.model attribute on aModelForm, you must also define theMeta.fields attribute (or the Meta.exclude attribute). However,ModelAdmin ignores this value, overriding it with theModelAdmin.list_editable attribute. The easiest solution is toomit the Meta.model attribute, since ModelAdmin will provide thecorrect model to use.

      • ModelAdmin.getchangelist_formset(_request, **kwargs)[source]
      • Returns a ModelFormSet class for use on thechangelist page if list_editable is used. To use acustom formset, for example:
      1. from django.forms import BaseModelFormSet
      2.  
      3. class MyAdminFormSet(BaseModelFormSet):
      4. pass
      5.  
      6. class MyModelAdmin(admin.ModelAdmin):
      7. def get_changelist_formset(self, request, **kwargs):
      8. kwargs['formset'] = MyAdminFormSet
      9. return super().get_changelist_formset(request, **kwargs)
      • ModelAdmin.lookupallowed(_lookup, value)
      • The objects in the changelist page can be filtered with lookups from theURL's query string. This is how list_filter works, for example. Thelookups are similar to what's used in QuerySet.filter() (e.g.user__email=user@example.com). Since the lookups in the query stringcan be manipulated by the user, they must be sanitized to preventunauthorized 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 whetherfiltering 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 fromget_list_filter()), and lookups required forlimit_choices_to to functioncorrectly in raw_id_fields.

      Override this method to customize the lookups permitted for yourModelAdmin subclass.

      • ModelAdmin.hasadd_permission(_request)
      • Should return True if adding an object is permitted, Falseotherwise.

      • ModelAdmin.haschange_permission(_request, obj=None)

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

      • ModelAdmin.hasdelete_permission(_request, obj=None)

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

      • ModelAdmin.hasmodule_permission(_request)

      • Should return True if displaying the module on the admin index page andaccessing the module's index page is permitted, False otherwise.Uses User.has_module_perms() by default. Overridingit does not restrict access to the add, change or delete views,has_add_permission(),has_change_permission(), andhas_delete_permission() should be used for that.

      • ModelAdmin.getqueryset(_request)

      • The get_queryset method on a ModelAdmin returns aQuerySet of all model instances thatcan be edited by the admin site. One use case for overriding this methodis 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)

      Keyword arguments allow you to change the message level, add extra CSStags, or fail silently if the contrib.messages framework is notinstalled. These keyword arguments match those fordjango.contrib.messages.add_message(), see that function'sdocumentation for more details. One difference is that the level may bepassed as a string label in addition to integer/constant.

      • ModelAdmin.getpaginator(_request, queryset, per_page, orphans=0, allow_empty_first_page=True)[source]
      • Returns an instance of the paginator to use for this view. By default,instantiates an instance of paginator.

      • ModelAdmin.responseadd(_request, obj, post_url_continue=None)[source]

      • Determines the HttpResponse for theadd_view() stage.

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

      response_change is called after the admin form is submitted andjust after the object and all the related instances havebeen saved. You can override it to change the defaultbehavior after the object has been changed.

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

      obj_display is a string with the name of the deletedobject.

      obj_id is the serialized identifier used to retrieve the object to bedeleted.

      • ModelAdmin.getchangeform_initial_data(_request)[source]
      • A hook for the initial data on admin change forms. By default, fields aregiven initial values from GET parameters. For instance,?name=initial_value will set the name field's initial value to beinitial_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'}

      Other methods

      • ModelAdmin.addview(_request, form_url='', extra_context=None)[source]
      • Django view for the model instance addition page. See note below.

      • ModelAdmin.changeview(_request, object_id, form_url='', extra_context=None)[source]

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

      • ModelAdmin.changelistview(_request, extra_context=None)[source]

      • Django view for the model instances change list/actions page. See notebelow.

      • ModelAdmin.deleteview(_request, object_id, extra_context=None)[source]

      • Django view for the model instance(s) deletion confirmation page. See notebelow.

      • ModelAdmin.historyview(_request, object_id, extra_context=None)[source]

      • Django view for the page that shows the modification history for a givenmodel 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 fromthe admin application URL dispatching handler to render the pages that dealwith model instances CRUD operations. As a result, completely overriding thesemethods will significantly change the behavior of the admin application.

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

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

      These views return TemplateResponseinstances which allow you to easily customize the response data beforerendering. 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 tothe add/change views. This can be accomplished by using a Media inner classon 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 prependsSTATIC_URL (or MEDIA_URL if STATIC_URL isNone) to any asset paths. The same rules apply as regular assetdefinitions 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 2.2.3) is namespaced as django.jQuery. If you want to use jQueryin your own admin JavaScript without including a second copy, you can use thedjango.jQuery object on changelist and add/edit views.

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

      Django provides both uncompressed and 'minified' versions of jQuery, asjquery.js and jquery.min.js respectively.

      ModelAdmin and InlineModelAdmin have a media propertythat returns a list of Media objects which store paths to the JavaScriptfiles for the forms and/or formsets. If DEBUG is True it willreturn the uncompressed versions of the various JavaScript files, includingjquery.js; if not, it will return the 'minified' versions.

      Adding custom validation to the admin

      Adding custom validation of data in the admin is quite easy. The automaticadmin interface reuses django.forms, and the ModelAdmin class givesyou the ability define your own form:

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

      MyArticleAdminForm can be defined anywhere as long as you import whereneeded. Now within your form you can add your own custom validation forany 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. Seethe forms documentation on custom validation and, more specifically, themodel form validation notes for moreinformation.

      InlineModelAdmin objects

      • class InlineModelAdmin
      • class TabularInline[source]
      • class StackedInline[source]
      • The admin interface has the ability to edit models on the same page as aparent model. These are called inlines. Suppose you have these two models:
      1. from django.db import models
      2.  
      3. class Author(models.Model):
      4. name = models.CharField(max_length=100)
      5.  
      6. class Book(models.Model):
      7. author = models.ForeignKey(Author, on_delete=models.CASCADE)
      8. title = models.CharField(max_length=100)

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

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

      Django provides two subclasses of InlineModelAdmin and they are:

      InlineModelAdmin options

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

      Warning

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

      • InlineModelAdmin.classes
      • A list or tuple containing extra CSS classes to apply to the fieldset thatis rendered for the inlines. Defaults to None. As with classesconfigured in fieldsets, inlines with a collapseclass 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 inaddition to the initial forms. See theformsets documentation for moreinformation.

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

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

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

      • InlineModelAdmin.max_num
      • This controls the maximum number of forms to show in the inline. Thisdoesn't directly correlate to the number of objects, but can if the valueis small enough. See Limiting the number of editable objects for more information.

      InlineModelAdmin.get_max_num() also allows you to customize themaximum 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 theminimum number of displayed forms.

      • InlineModelAdmin.raw_id_fields
      • By default, Django's admin uses a select-box interface (

        • InlineModelAdmin.template
        • The template used to render the inline on the page.

        • InlineModelAdmin.verbose_name

        • An override to the verbose_name found in the model's inner Metaclass.

        • InlineModelAdmin.verbose_name_plural

        • An override to the verbose_name_plural found in the model's innerMeta class.

        • InlineModelAdmin.can_delete

        • Specifies whether or not inline objects can be deleted in the inline.Defaults to True.

        • InlineModelAdmin.show_change_link

        • Specifies whether or not inline objects that can be changed in theadmin have a link to the change form. Defaults to False.

        • InlineModelAdmin.getformset(_request, obj=None, **kwargs)

        • Returns a BaseInlineFormSet class for use inadmin add/change views. See the example forModelAdmin.get_formsets_with_inlines.

        • InlineModelAdmin.getextra(_request, obj=None, **kwargs)

        • Returns the number of extra inline forms to use. By default, returns theInlineModelAdmin.extra attribute.

        Override this method to programmatically determine the number of extrainline forms. For example, this may be based on the model instance(passed as the keyword argument obj):

        1. class BinaryTreeAdmin(admin.TabularInline):
        2. model = BinaryTree
        3.  
        4. def get_extra(self, request, obj=None, **kwargs):
        5. extra = 2
        6. if obj:
        7. return extra - obj.binarytree_set.count()
        8. return extra
        • InlineModelAdmin.getmax_num(_request, obj=None, **kwargs)
        • Returns the maximum number of extra inline forms to use. By default,returns the InlineModelAdmin.max_num attribute.

        Override this method to programmatically determine the maximum number ofinline forms. For example, this may be based on the model instance(passed as the keyword argument obj):

        1. class BinaryTreeAdmin(admin.TabularInline):
        2. model = BinaryTree
        3.  
        4. def get_max_num(self, request, obj=None, **kwargs):
        5. max_num = 10
        6. if obj and obj.parent:
        7. return max_num - 5
        8. return max_num
        • InlineModelAdmin.getmin_num(_request, obj=None, **kwargs)
        • Returns the minimum number of inline forms to use. By default,returns the InlineModelAdmin.min_num attribute.

        Override this method to programmatically determine the minimum number ofinline forms. For example, this may be based on the model instance(passed as the keyword argument obj).

        Working with a model with two or more foreign keys to the same parent model

        It is sometimes possible to have more than one foreign key to the same model.Take this model for instance:

        1. from django.db import models
        2.  
        3. class Friendship(models.Model):
        4. to_person = models.ForeignKey(Person, on_delete=models.CASCADE, related_name="friends")
        5. from_person = models.ForeignKey(Person, on_delete=models.CASCADE, related_name="from_friends")

        If you wanted to display an inline on the Person admin add/change pagesyou need to explicitly define the foreign key since it is unable to do soautomatically:

        1. from django.contrib import admin
        2. from myapp.models import Friendship
        3.  
        4. class FriendshipInline(admin.TabularInline):
        5. model = Friendship
        6. fk_name = "to_person"
        7.  
        8. class PersonAdmin(admin.ModelAdmin):
        9. inlines = [
        10. FriendshipInline,
        11. ]

        Working with many-to-many models

        By default, admin widgets for many-to-many relations will be displayedon whichever model contains the actual reference to theManyToManyField. Depending on your ModelAdmindefinition, each many-to-many field in your model will be represented by astandard HTML <select multiple>, a horizontal or vertical filter, or araw_id_admin widget. However, it is also possible to replace thesewidgets with inlines.

        Suppose we have the following models:

        1. from django.db import models
        2.  
        3. class Person(models.Model):
        4. name = models.CharField(max_length=128)
        5.  
        6. class Group(models.Model):
        7. name = models.CharField(max_length=128)
        8. members = models.ManyToManyField(Person, related_name='groups')

        If you want to display many-to-many relations using an inline, you can doso by defining an InlineModelAdmin object for the relationship:

        1. from django.contrib import admin
        2.  
        3. class MembershipInline(admin.TabularInline):
        4. model = Group.members.through
        5.  
        6. class PersonAdmin(admin.ModelAdmin):
        7. inlines = [
        8. MembershipInline,
        9. ]
        10.  
        11. class GroupAdmin(admin.ModelAdmin):
        12. inlines = [
        13. MembershipInline,
        14. ]
        15. exclude = ('members',)

        There are two features worth noting in this example.

        Firstly - the MembershipInline class references Group.members.through.The through attribute is a reference to the model that manages themany-to-many relation. This model is automatically created by Django when youdefine a many-to-many field.

        Secondly, the GroupAdmin must manually exclude the members field.Django displays an admin widget for a many-to-many field on the model thatdefines the relation (in this case, Group). If you want to use an inlinemodel to represent the many-to-many relationship, you must tell Django's adminto not display this widget - otherwise you will end up with two widgets onyour admin page for managing the relation.

        Note that when using this technique them2m_changed signals aren't triggered. Thisis because as far as the admin is concerned, through is just a model withtwo foreign key fields rather than a many-to-many relation.

        In all other respects, the InlineModelAdmin is exactly the same as anyother. You can customize the appearance using any of the normalModelAdmin properties.

        Working with many-to-many intermediary models

        When you specify an intermediary model using the through argument to aManyToManyField, the admin will not display awidget by default. This is because each instance of that intermediary modelrequires more information than could be displayed in a single widget, and thelayout required for multiple widgets will vary depending on the intermediatemodel.

        However, we still want to be able to edit that information inline. Fortunately,this is easy to do with inline admin models. Suppose we have the followingmodels:

        1. from django.db import models
        2.  
        3. class Person(models.Model):
        4. name = models.CharField(max_length=128)
        5.  
        6. class Group(models.Model):
        7. name = models.CharField(max_length=128)
        8. members = models.ManyToManyField(Person, through='Membership')
        9.  
        10. class Membership(models.Model):
        11. person = models.ForeignKey(Person, on_delete=models.CASCADE)
        12. group = models.ForeignKey(Group, on_delete=models.CASCADE)
        13. date_joined = models.DateField()
        14. invite_reason = models.CharField(max_length=64)

        The first step in displaying this intermediate model in the admin is todefine an inline class for the Membership model:

        1. class MembershipInline(admin.TabularInline):
        2. model = Membership
        3. extra = 1

        This simple example uses the default InlineModelAdmin values for theMembership model, and limits the extra add forms to one. This could becustomized using any of the options available to InlineModelAdmin classes.

        Now create admin views for the Person and Group models:

        1. class PersonAdmin(admin.ModelAdmin):
        2. inlines = (MembershipInline,)
        3.  
        4. class GroupAdmin(admin.ModelAdmin):
        5. inlines = (MembershipInline,)

        Finally, register your Person and Group models with the admin site:

        1. admin.site.register(Person, PersonAdmin)
        2. admin.site.register(Group, GroupAdmin)

        Now your admin site is set up to edit Membership objects inline fromeither the Person or the Group detail pages.

        Using generic relations as an inline

        It is possible to use an inline with generically related objects. Let's sayyou have the following models:

        1. from django.contrib.contenttypes.fields import GenericForeignKey
        2. from django.db import models
        3.  
        4. class Image(models.Model):
        5. image = models.ImageField(upload_to="images")
        6. content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
        7. object_id = models.PositiveIntegerField()
        8. content_object = GenericForeignKey("content_type", "object_id")
        9.  
        10. class Product(models.Model):
        11. name = models.CharField(max_length=100)

        If you want to allow editing and creating an Image instance on theProduct, add/change views you can useGenericTabularInlineor GenericStackedInline (bothsubclasses of GenericInlineModelAdmin)provided by admin. They implement tabularand stacked visual layouts for the forms representing the inline objects,respectively, just like their non-generic counterparts. They behave just likeany other inline. In your admin.py for this example app:

        1. from django.contrib import admin
        2. from django.contrib.contenttypes.admin import GenericTabularInline
        3.  
        4. from myproject.myapp.models import Image, Product
        5.  
        6. class ImageInline(GenericTabularInline):
        7. model = Image
        8.  
        9. class ProductAdmin(admin.ModelAdmin):
        10. inlines = [
        11. ImageInline,
        12. ]
        13.  
        14. admin.site.register(Product, ProductAdmin)

        See the contenttypes documentation for morespecific information.

        Overriding admin templates

        It is relatively easy to override many of the templates which the admin moduleuses to generate the various pages of an admin site. You can even override afew of these templates for a specific app, or a specific model.

        Set up your projects admin template directories

        The admin template files are located in the contrib/admin/templates/admindirectory.

        In order to override one or more of them, first create an admin directoryin your project's templates directory. This can be any of the directoriesyou specified in the DIRS option of theDjangoTemplates backend in the TEMPLATES setting. If you havecustomized the 'loaders' option, be sure'django.template.loaders.filesystem.Loader' appears before'django.template.loaders.app_directories.Loader' so that your customtemplates will be found by the template loading system before those that areincluded with django.contrib.admin.

        Within this admin directory, create sub-directories named after your app.Within these app subdirectories create sub-directories named after your models.Note, that the admin app will lowercase the model name when looking for thedirectory, so make sure you name the directory in all lowercase if you aregoing to run your app on a case-sensitive filesystem.

        To override an admin template for a specific app, copy and edit the templatefrom the django/contrib/admin/templates/admin directory, and save it to oneof the directories you just created.

        For example, if we wanted to add a tool to the change list view for all themodels in an app named my_app, we would copycontrib/admin/templates/admin/change_list.html to thetemplates/admin/my_app/ directory of our project, and make any necessarychanges.

        If we wanted to add a tool to the change list view for only a specific modelnamed 'Page', we would copy that same file to thetemplates/admin/my_app/page directory of our project.

        Overriding vs. replacing an admin template

        Because of the modular design of the admin templates, it is usually neithernecessary nor advisable to replace an entire template. It is almost alwaysbetter to override only the section of the template which you need to change.

        To continue the example above, we want to add a new link next to theHistory tool for the Page model. After looking at change_form.htmlwe determine that we only need to override the object-tools-items block.Therefore here is our new change_form.html :

        1. {% extends "admin/change_form.html" %}
        2. {% load i18n admin_urls %}
        3. {% block object-tools-items %}
        4. <li>
        5. <a href="{% url opts|admin_urlname:'history' original.pk|admin_urlquote %}" class="historylink">{% trans "History" %}</a>
        6. </li>
        7. <li>
        8. <a href="mylink/" class="historylink">My Link</a>
        9. </li>
        10. {% if has_absolute_url %}
        11. <li>
        12. <a href="{% url 'admin:view_on_site' content_type_id original.pk %}" class="viewsitelink">{% trans "View on site" %}</a>
        13. </li>
        14. {% endif %}
        15. {% endblock %}

        And that's it! If we placed this file in the templates/admin/my_appdirectory, our link would appear on the change form for all models withinmy_app.

        Templates which may be overridden per app or model

        Not every template in contrib/admin/templates/admin may be overridden perapp or per model. The following can:

        • app_index.html
        • change_form.html
        • change_list.html
        • delete_confirmation.html
        • object_history.html
        • popup_response.htmlChanged in Django 1.11:The ability to override the popup_response.html template was added.

        For those templates that cannot be overridden in this way, you may stilloverride them for your entire project. Just place the new version in yourtemplates/admin directory. This is particularly useful to create custom 404and 500 pages.

        Note

        Some of the admin templates, such as change_list_results.html are usedto render custom inclusion tags. These may be overridden, but in such casesyou are probably better off creating your own version of the tag inquestion and giving it a different name. That way you can use itselectively.

        Root and login templates

        If you wish to change the index, login or logout templates, you are better offcreating your own AdminSite instance (see below), and changing theAdminSite.index_template , AdminSite.login_template orAdminSite.logout_template properties.

        AdminSite objects

        • class AdminSite(name='admin')[source]
        • A Django administrative site is represented by an instance ofdjango.contrib.admin.sites.AdminSite; by default, an instance ofthis class is created as django.contrib.admin.site and you canregister your models and ModelAdmin instances with it.

        When constructing an instance of an AdminSite, you can providea unique instance name using the name argument to the constructor. Thisinstance name is used to identify the instance, especially whenreversing admin URLs. If no instance name isprovided, a default instance name of admin will be used.See Customizing the AdminSite class for an example of customizing theAdminSite class.

        AdminSite attributes

        Templates can override or extend base admin templates as described inOverriding admin templates.

        • AdminSite.site_header
        • The text to put at the top of each admin page, as an <h1> (a string).By default, this is "Django administration".

        • AdminSite.site_title

        • The text to put at the end of each admin page's <title> (a string). Bydefault, this is "Django site admin".

        • AdminSite.site_url

        • The URL for the "View site" link at the top of each admin page. By default,site_url is /. Set it to None to remove the link.

        For sites running on a subpath, the each_context() method checks ifthe current request has request.META['SCRIPT_NAME'] set and uses thatvalue if site_url isn't set to something other than /.

        • AdminSite.index_title
        • The text to put at the top of the admin index page (a string). By default,this is "Site administration".

        • AdminSite.index_template

        • Path to a custom template that will be used by the admin site main indexview.

        • AdminSite.app_index_template

        • Path to a custom template that will be used by the admin site app index view.

        • AdminSite.empty_value_display

        • The string to use for displaying empty values in the admin site's changelist. Defaults to a dash. The value can also be overridden on a perModelAdmin basis and on a custom field within a ModelAdmin bysetting an empty_value_display attribute on the field. SeeModelAdmin.empty_value_display for examples.

        • AdminSite.login_template

        • Path to a custom template that will be used by the admin site login view.

        • AdminSite.login_form

        • Subclass of AuthenticationForm thatwill be used by the admin site login view.

        • AdminSite.logout_template

        • Path to a custom template that will be used by the admin site logout view.

        • AdminSite.password_change_template

        • Path to a custom template that will be used by the admin site passwordchange view.

        • AdminSite.password_change_done_template

        • Path to a custom template that will be used by the admin site passwordchange done view.

        AdminSite methods

        • AdminSite.eachcontext(_request)[source]
        • Returns a dictionary of variables to put in the template context forevery page in the admin site.

        Includes the following variables and values by default:

        • site_header: AdminSite.site_header

        • site_title: AdminSite.site_title

        • site_url: AdminSite.site_url

        • has_permission: AdminSite.has_permission()

        • available_apps: a list of applications from the application registry available for the current user. Each entry in thelist is a dict representing an application with the following keys:

          • app_label: the application label
          • app_url: the URL of the application index in the admin
          • has_module_perms: a boolean indicating if displaying and accessing ofthe module's index page is permitted for the current user
          • models: a list of the models available in the applicationEach model is a dict with the following keys:

          • object_name: class name of the model

          • name: plural name of the model
          • perms: a dict tracking add, change, and delete permissions
          • admin_url: admin changelist URL for the model
          • add_url: admin URL to add a new model instance
          • AdminSite.haspermission(_request)[source]
          • Returns True if the user for the given HttpRequest has permissionto view at least one page in the admin site. Defaults to requiring bothUser.is_active andUser.is_staff to beTrue.
        • AdminSite.register(model_or_iterable, admin_class=None, **options)[source]
        • Registers the given model class (or iterable of classes) with the givenadmin_class. admin_class defaults toModelAdmin (the default admin options). Ifkeyword arguments are given — e.g. list_display — they'll be appliedas options to the admin class.

        Raises ImproperlyConfigured if a model isabstract. and django.contrib.admin.sites.AlreadyRegistered if a modelis already registered.

        Hooking AdminSite instances into your URLconf

        The last step in setting up the Django admin is to hook your AdminSiteinstance into your URLconf. Do this by pointing a given URL at theAdminSite.urls method. It is not necessary to useinclude().

        In this example, we register the default AdminSite instancedjango.contrib.admin.site at the URL /admin/

        1. # urls.py
        2. from django.contrib import admin
        3. from django.urls import path
        4.  
        5. urlpatterns = [
        6. path('admin/', admin.site.urls),
        7. ]

        Customizing the AdminSite class

        If you'd like to set up your own admin site with custom behavior, you're freeto subclass AdminSite and override or add anything you like. Then, simplycreate an instance of your AdminSite subclass (the same way you'dinstantiate any other Python class) and register your models andModelAdmin subclasses with it instead of with the default site. Finally,update myproject/urls.py to reference your AdminSite subclass.

        myapp/admin.py

        1. from django.contrib.admin import AdminSite
        2.  
        3. from .models import MyModel
        4.  
        5. class MyAdminSite(AdminSite):
        6. site_header = 'Monty Python administration'
        7.  
        8. admin_site = MyAdminSite(name='myadmin')
        9. admin_site.register(MyModel)

        myproject/urls.py

        1. from django.urls import path
        2.  
        3. from myapp.admin import admin_site
        4.  
        5. urlpatterns = [
        6. path('myadmin/', admin_site.urls),
        7. ]

        Note that you may not want autodiscovery of admin modules when using yourown AdminSite instance since you will likely be importing all the per-appadmin modules in your myproject.admin module. This means you need toput 'django.contrib.admin.apps.SimpleAdminConfig' instead of'django.contrib.admin' in your INSTALLED_APPS setting.

        Multiple admin sites in the same URLconf

        It's easy to create multiple instances of the admin site on the sameDjango-powered website. Just create multiple instances of AdminSite androot each one at a different URL.

        In this example, the URLs /basic-admin/ and /advanced-admin/ featureseparate versions of the admin site — using the AdminSite instancesmyproject.admin.basic_site and myproject.admin.advanced_site,respectively:

        1. # urls.py
        2. from django.urls import path
        3. from myproject.admin import advanced_site, basic_site
        4.  
        5. urlpatterns = [
        6. path('basic-admin/', basic_site.urls),
        7. path('advanced-admin/', advanced_site.urls),
        8. ]

        AdminSite instances take a single argument to their constructor, theirname, which can be anything you like. This argument becomes the prefix to theURL names for the purposes of reversing them. Thisis only necessary if you are using more than one AdminSite.

        Adding views to admin sites

        Just like ModelAdmin, AdminSite provides aget_urls() methodthat can be overridden to define additional views for the site. To adda new view to your admin site, extend the baseget_urls() method to includea pattern for your new view.

        Note

        Any view you render that uses the admin templates, or extends the baseadmin template, should set request.current_app before rendering thetemplate. It should be set to either self.name if your view is on anAdminSite or self.admin_site.name if your view is on aModelAdmin.

        Adding a password reset feature

        You can add a password reset feature to the admin site by adding a few lines toyour URLconf. Specifically, add these four patterns:

        1. from django.contrib.auth import views as auth_views
        2.  
        3. path(
        4. 'admin/password_reset/',
        5. auth_views.PasswordResetView.as_view(),
        6. name='admin_password_reset',
        7. ),
        8. path(
        9. 'admin/password_reset/done/',
        10. auth_views.PasswordResetDoneView.as_view(),
        11. name='password_reset_done',
        12. ),
        13. path(
        14. 'reset/<uidb64>/<token>/',
        15. auth_views.PasswordResetConfirmView.as_view(),
        16. name='password_reset_confirm',
        17. ),
        18. path(
        19. 'reset/done/',
        20. auth_views.PasswordResetCompleteView.as_view(),
        21. name='password_reset_complete',
        22. ),

        (This assumes you've added the admin at admin/ and requires that you putthe URLs starting with ^admin/ before the line that includes the admin appitself).

        The presence of the admin_password_reset named URL will cause a "forgottenyour password?" link to appear on the default admin log-in page under thepassword box.

        LogEntry objects

        • class models.LogEntry
        • The LogEntry class tracks additions, changes, and deletions of objectsdone through the admin interface.

        LogEntry attributes

        • LogEntry.action_time
        • The date and time of the action.

        • LogEntry.user

        • The user (an AUTH_USER_MODEL instance) who performed theaction.

        • LogEntry.content_type

        • The ContentType of themodified object.

        • LogEntry.object_id

        • The textual representation of the modified object's primary key.

        • LogEntry.object_repr

        • The object`s repr() after the modification.

        • LogEntry.action_flag

        • The type of action logged: ADDITION, CHANGE, DELETION.

        For example, to get a list of all additions done through the admin:

        1. from django.contrib.admin.models import ADDITION, LogEntry
        2.  
        3. LogEntry.objects.filter(action_flag=ADDITION)
        • LogEntry.change_message
        • The detailed description of the modification. In the case of an edit, forexample, the message contains a list of the edited fields. The Django adminsite formats this content as a JSON structure, so thatget_change_message() can recompose a message translated in the currentuser language. Custom code might set this as a plain string though. You areadvised to use the get_change_message() method to retrieve this valueinstead of accessing it directly.

        LogEntry methods

        • LogEntry.get_edited_object()
        • A shortcut that returns the referenced object.

        • LogEntry.get_change_message()

        • Formats and translates change_message into the current userlanguage. Messages created before Django 1.10 will always be displayed inthe language in which they were logged.

        Reversing admin URLs

        When an AdminSite is deployed, the views provided by that site areaccessible using Django's URL reversing system.

        The AdminSite provides the following named URL patterns:

        PageURL nameParameters
        Indexindex
        Loginlogin
        Logoutlogout
        Password changepassword_change
        Password change donepassword_change_done
        i18n JavaScriptjsi18n
        Application index pageapp_listapp_label
        Redirect to object's pageview_on_sitecontent_type_id, object_id

        Each ModelAdmin instance provides an additional set of named URLs:

        PageURL nameParameters
        Changelist{{ applabel }}{{ modelname }}_changelist
        Add{{ app_label }}{{ modelname }}_add
        History{{ app_label }}{{ modelname }}_historyobject_id
        Delete{{ app_label }}{{ modelname }}_deleteobject_id
        Change{{ app_label }}{{ model_name }}_changeobject_id

        The UserAdmin provides a named URL:

        PageURL nameParameters
        Password changeauth_user_password_changeuser_id

        These named URLs are registered with the application namespace admin, andwith an instance namespace corresponding to the name of the Site instance.

        So - if you wanted to get a reference to the Change view for a particularChoice object (from the polls application) in the default admin, you wouldcall:

        1. >>> from django.urls import reverse
        2. >>> c = Choice.objects.get(...)
        3. >>> change_url = reverse('admin:polls_choice_change', args=(c.id,))

        This will find the first registered instance of the admin application(whatever the instance name), and resolve to the view for changingpoll.Choice instances in that instance.

        If you want to find a URL in a specific admin instance, provide the name ofthat instance as a current_app hint to the reverse call. For example,if you specifically wanted the admin view from the admin instance namedcustom, you would need to call:

        1. >>> change_url = reverse('admin:polls_choice_change', args=(c.id,), current_app='custom')

        For more details, see the documentation on reversing namespaced URLs.

        To allow easier reversing of the admin urls in templates, Django provides anadmin_urlname filter which takes an action as argument:

        1. {% load admin_urls %}
        2. <a href="{% url opts|admin_urlname:'add' %}">Add user</a>
        3. <a href="{% url opts|admin_urlname:'delete' user.pk %}">Delete this user</a>

        The action in the examples above match the last part of the URL names forModelAdmin instances described above. The opts variable can be anyobject which has an app_label and model_name attributes and is usuallysupplied by the admin views for the current model.

        The staff_member_required decorator

        • staffmember_required(_redirect_field_name='next', login_url='admin:login')[source]
        • This decorator is used on the admin views that require authorization. Aview decorated with this function will having the following behavior:

          • If the user is logged in, is a staff member (User.is_staff=True), andis active (User.is_active=True), execute the view normally.
          • Otherwise, the request will be redirected to the URL specified by thelogin_url parameter, with the originally requested path in a querystring variable specified by redirect_field_name. For example:/admin/login/?next=/admin/polls/question/3/.Example usage:
        1. from django.contrib.admin.views.decorators import staff_member_required
        2.  
        3. @staff_member_required
        4. def my_view(request):
        5. ...