The Django admin site¶
One of the most powerful parts of Django is the automatic admin interface. It reads metadata from your models to provide a quick, model-centric interface where trusted users can manage content on your site. The admin’s recommended use is limited to an organization’s internal management tool. It’s not intended for building your entire front end around.
The admin has many hooks for customization, but beware of trying to use those hooks exclusively. If you need to provide a more process-centric interface that abstracts away the implementation details of database tables and fields, then it’s probably time to write your own views.
In this document we discuss how to activate, use, and customize Django’s admin interface.
Overview¶
The admin is enabled in the default project template used by
startproject.
If you’re not using the default project template, here are the requirements:
Add
'django.contrib.admin'and its dependencies -django.contrib.auth,django.contrib.contenttypes,django.contrib.messages, anddjango.contrib.sessions- to yourINSTALLED_APPSsetting.Configure a
DjangoTemplatesbackend in yourTEMPLATESsetting withdjango.template.context_processors.request,django.contrib.auth.context_processors.auth, anddjango.contrib.messages.context_processors.messagesin the'context_processors'option ofOPTIONS.If you’ve customized the
MIDDLEWAREsetting,django.contrib.sessions.middleware.SessionMiddleware,django.contrib.auth.middleware.AuthenticationMiddleware, anddjango.contrib.messages.middleware.MessageMiddlewaremust be included.
After you’ve taken these steps, you’ll be able to use the admin site by
visiting the URL you hooked it into (/admin/, by default).
If you need to create a user to login with, use the createsuperuser
command. By default, logging in to the admin requires that the user has the
is_staff attribute set to True.
Finally, determine which of your application’s models should be editable in the
admin interface. For each of those models, register them with the admin as
described in ModelAdmin.
Other topics¶
Δείτε επίσης
For information about serving the static files (images, JavaScript, and CSS) associated with the admin in production, see Εξυπηρετώντας αρχεία.
Having problems? Try Συχνές Ερωτήσεις: Το admin site.
ModelAdmin objects¶
- class ModelAdmin[πηγή]¶
The
ModelAdminclass is the representation of a model in the admin interface. Usually, these are stored in a file namedadmin.pyin your application. Let’s take a look at an example of theModelAdmin:from django.contrib import admin from myapp.models import Author class AuthorAdmin(admin.ModelAdmin): pass admin.site.register(Author, AuthorAdmin)
Do you need a
ModelAdminobject at all?In the preceding example, the
ModelAdminclass doesn’t define any custom values (yet). As a result, the default admin interface will be provided. If you are happy with the default admin interface, you don’t need to define aModelAdminobject at all – you can register the model class without providing aModelAdmindescription. The preceding example could be simplified to:from django.contrib import admin from myapp.models import Author admin.site.register(Author)
The register decorator¶
- register(*models, site=django.contrib.admin.sites.site)[πηγή]¶
There is also a decorator for registering your
ModelAdminclasses:from django.contrib import admin from .models import Author @admin.register(Author) class AuthorAdmin(admin.ModelAdmin): pass
It’s given one or more model classes to register with the
ModelAdmin. If you’re using a customAdminSite, pass it using thesitekeyword argument:from django.contrib import admin from .models import Author, Editor, Reader from myproject.admin_site import custom_admin_site @admin.register(Author, Reader, Editor, site=custom_admin_site) class PersonAdmin(admin.ModelAdmin): pass
You can’t use this decorator if you have to reference your model admin class in its
__init__()method, e.g.super(PersonAdmin, self).__init__(*args, **kwargs). You can usesuper().__init__(*args, **kwargs).
Discovery of admin files¶
When you put 'django.contrib.admin' in your INSTALLED_APPS
setting, Django automatically looks for an admin module in each
application and imports it.
- class apps.AdminConfig¶
This is the default
AppConfigclass for the admin. It callsautodiscover()when Django starts.
- class apps.SimpleAdminConfig¶
This class works like
AdminConfig, except it doesn’t callautodiscover().- default_site¶
A dotted import path to the default admin site’s class or to a callable that returns a site instance. Defaults to
'django.contrib.admin.sites.AdminSite'. See Overriding the default admin site for usage.
- autodiscover()[πηγή]¶
This function attempts to import an
adminmodule in each installed application. Such modules are expected to register models with the admin.Typically you won’t need to call this function directly as
AdminConfigcalls it when Django starts.
If you are using a custom AdminSite, it is common to import all of the
ModelAdmin subclasses into your code and register them to the custom
AdminSite. In that case, in order to disable auto-discovery, you should
put 'django.contrib.admin.apps.SimpleAdminConfig' instead of
'django.contrib.admin' in your INSTALLED_APPS setting.
ModelAdmin options¶
The ModelAdmin is very flexible. It has several options for dealing with
customizing the interface. All options are defined on the ModelAdmin
subclass:
from django.contrib import admin
class AuthorAdmin(admin.ModelAdmin):
date_hierarchy = "pub_date"
- ModelAdmin.actions¶
A list of actions to make available on the change list page. See Admin actions for details.
- ModelAdmin.actions_on_top¶
- ModelAdmin.actions_on_bottom¶
Controls where on the page the actions bar appears. By default, the admin changelist displays actions at the top of the page (
actions_on_top = True; actions_on_bottom = False).
- ModelAdmin.actions_selection_counter¶
Controls whether a selection counter is displayed next to the action dropdown. By default, the admin changelist will display it (
actions_selection_counter = True).
- ModelAdmin.date_hierarchy¶
Set
date_hierarchyto the name of aDateFieldorDateTimeFieldin your model, and the change list page will include a date-based drilldown navigation by that field.Example:
date_hierarchy = "pub_date"
You can also specify a field on a related model using the
__lookup, for example:date_hierarchy = "author__pub_date"
This will intelligently populate itself based on available data, e.g. if all the dates are in one month, it’ll show the day-level drill-down only.
Σημείωση
date_hierarchyusesQuerySet.datetimes()internally. Please refer to its documentation for some caveats when time zone support is enabled (USE_TZ = True).
- ModelAdmin.empty_value_display¶
This attribute overrides the default display value for record’s fields that are empty (
None, empty string, etc.). The default value is-(a dash). For example:from django.contrib import admin class AuthorAdmin(admin.ModelAdmin): empty_value_display = "-empty-"
You can also override
empty_value_displayfor all admin pages withAdminSite.empty_value_display, or for specific fields like this:from django.contrib import admin class AuthorAdmin(admin.ModelAdmin): list_display = ["name", "title", "view_birth_date"] @admin.display(empty_value="???") def view_birth_date(self, obj): return obj.birth_date
- ModelAdmin.exclude¶
This attribute, if given, should be a list of field names to exclude from the form.
For example, let’s consider the following model:
from django.db import models class Author(models.Model): name = models.CharField(max_length=100) title = models.CharField(max_length=3) birth_date = models.DateField(blank=True, null=True)
If you want a form for the
Authormodel that includes only thenameandtitlefields, you would specifyfieldsorexcludelike this:from django.contrib import admin class AuthorAdmin(admin.ModelAdmin): fields = ["name", "title"] class AuthorAdmin(admin.ModelAdmin): exclude = ["birth_date"]
Since the Author model only has three fields,
name,title, andbirth_date, the forms resulting from the above declarations will contain exactly the same fields.
- ModelAdmin.fields¶
Use the
fieldsoption to make simple layout changes in the forms on the «add» and «change» pages such as showing only a subset of available fields, modifying their order, or grouping them into rows. For example, you could define a simpler version of the admin form for thedjango.contrib.flatpages.models.FlatPagemodel as follows:class FlatPageAdmin(admin.ModelAdmin): fields = ["url", "title", "content"]
In the above example, only the fields
url,titleandcontentwill be displayed, sequentially, in the form.fieldscan contain values defined inModelAdmin.readonly_fieldsto be displayed as read-only.For more complex layout needs, see the
fieldsetsoption.The
fieldsoption accepts the same types of values aslist_display, except that callables and__lookups for related fields aren’t accepted. Names of model and model admin methods will only be used if they’re listed inreadonly_fields.To display multiple fields on the same line, wrap those fields in their own tuple. In this example, the
urlandtitlefields will display on the same line and thecontentfield will be displayed below them on its own line:class FlatPageAdmin(admin.ModelAdmin): fields = [("url", "title"), "content"]
Possible confusion with the
ModelAdmin.fieldsetsoptionThis
fieldsoption should not be confused with thefieldsdictionary key that is within thefieldsetsoption, as described in the next section.If neither
fieldsnorfieldsetsoptions are present, Django will default to displaying each field that isn’t anAutoFieldand haseditable=True, in a single fieldset, in the same order as the fields are defined in the model, followed by any fields defined inreadonly_fields.
- ModelAdmin.fieldsets¶
Set
fieldsetsto control the layout of admin «add» and «change» pages.fieldsetsis a list of 2-tuples, in which each 2-tuple represents a<fieldset>on the admin form page. (A<fieldset>is a «section» of the form.)The 2-tuples are in the format
(name, field_options), wherenameis a string representing the title of the fieldset andfield_optionsis a dictionary of information about the fieldset, including a list of fields to be displayed in it.A full example, taken from the
django.contrib.flatpages.models.FlatPagemodel:from django.contrib import admin class FlatPageAdmin(admin.ModelAdmin): fieldsets = [ ( None, { "fields": ["url", "title", "content", "sites"], }, ), ( "Advanced options", { "classes": ["collapse"], "fields": ["registration_required", "template_name"], }, ), ]
This results in an admin page that looks like:
If neither
fieldsetsnorfieldsoptions are present, Django will default to displaying each field that isn’t anAutoFieldand haseditable=True, in a single fieldset, in the same order as the fields are defined in the model.The
field_optionsdictionary can have the following keys:fieldsA list or tuple of field names to display in this fieldset. This key is required.
Example:
{ "fields": ["first_name", "last_name", "address", "city", "state"], }
As with the
fieldsoption, to display multiple fields on the same line, wrap those fields in their own tuple. In this example, thefirst_nameandlast_namefields will display on the same line:{ "fields": [("first_name", "last_name"), "address", "city", "state"], }
fieldscan contain values defined inreadonly_fieldsto be displayed as read-only.If you add the name of a callable to
fields, the same rule applies as with thefieldsoption: the callable must be listed inreadonly_fields.
classesA list or tuple containing extra CSS classes to apply to the fieldset. This can include any custom CSS class defined in the project, as well as any of the CSS classes provided by Django. Within the default admin site CSS stylesheet, two particularly useful classes are defined:
collapseandwide.Example:
{ "classes": ["wide", "collapse"], }
Fieldsets with the
widestyle will be given extra horizontal space in the admin interface. Fieldsets with a name and thecollapsestyle will be initially collapsed, using an expandable widget with a toggle for switching their visibility.Changed in Django 5.1:fieldsetsusing thecollapseclass now use<details>and<summary>elements, provided they define aname.
descriptionA string of optional extra text to be displayed at the top of each fieldset, under the heading of the fieldset.
Note that this value is not HTML-escaped when it’s displayed in the admin interface. This lets you include HTML if you so desire. Alternatively you can use plain text and
django.utils.html.escape()to escape any HTML special characters.
TabularInlinehas limited support forfieldsetsUsing
fieldsetswithTabularInlinehas limited functionality. You can specify which fields will be displayed and their order within theTabularInlinelayout by definingfieldsin thefield_optionsdictionary.All other features are not supported. This includes the use of
nameto define a title for a group of fields.
- ModelAdmin.filter_horizontal¶
By default, a
ManyToManyFieldis displayed in the admin site with a<select multiple>. However, multiple-select boxes can be difficult to use when selecting many items. Adding aManyToManyFieldto this list will instead use a nifty unobtrusive JavaScript «filter» interface that allows searching within the options. The unselected and selected options appear in two boxes side by side. Seefilter_verticalto use a vertical interface.
- ModelAdmin.filter_vertical¶
Same as
filter_horizontal, but uses a vertical display of the filter interface with the box of unselected options appearing above the box of selected options.
- ModelAdmin.form¶
By default a
ModelFormis dynamically created for your model. It is used to create the form presented on both the add/change pages. You can easily provide your ownModelFormto override any default form behavior on the add/change pages. Alternatively, you can customize the default form rather than specifying an entirely new one by using theModelAdmin.get_form()method.For an example see the section Adding custom validation to the admin.
ModelAdmin.excludetakes precedenceIf your
ModelFormandModelAdminboth define anexcludeoption thenModelAdmintakes precedence:from django import forms from django.contrib import admin from myapp.models import Person class PersonForm(forms.ModelForm): class Meta: model = Person exclude = ["name"] class PersonAdmin(admin.ModelAdmin): exclude = ["age"] form = PersonForm
In the above example, the «age» field will be excluded but the «name» field will be included in the generated form.
- ModelAdmin.formfield_overrides¶
This provides a quick-and-dirty way to override some of the
Fieldoptions for use in the admin.formfield_overridesis a dictionary mapping a field class to a dict of arguments to pass to the field at construction time.Since that’s a bit abstract, let’s look at a concrete example. The most common use of
formfield_overridesis to add a custom widget for a certain type of field. So, imagine we’ve written aRichTextEditorWidgetthat we’d like to use for large text fields instead of the default<textarea>. Here’s how we’d do that:from django.contrib import admin from django.db import models # Import our custom widget and our model from where they're defined from myapp.models import MyModel from myapp.widgets import RichTextEditorWidget class MyModelAdmin(admin.ModelAdmin): formfield_overrides = { models.TextField: {"widget": RichTextEditorWidget}, }
Note that the key in the dictionary is the actual field class, not a string. The value is another dictionary; these arguments will be passed to the form field’s
__init__()method. See The Forms API for details.Προειδοποίηση
If you want to use a custom widget with a relation field (i.e.
ForeignKeyorManyToManyField), make sure you haven’t included that field’s name inraw_id_fields,radio_fields, orautocomplete_fields.formfield_overrideswon’t let you change the widget on relation fields that haveraw_id_fields,radio_fields, orautocomplete_fieldsset. That’s becauseraw_id_fields,radio_fields, andautocomplete_fieldsimply custom widgets of their own.
- ModelAdmin.inlines¶
See
InlineModelAdminobjects below as well asModelAdmin.get_formsets_with_inlines().
- ModelAdmin.list_display¶
Set
list_displayto control which fields are displayed on the change list page of the admin.Example:
list_display = ["first_name", "last_name"]
If you don’t set
list_display, the admin site will display a single column that displays the__str__()representation of each object.There are five types of values that can be used in
list_display. All but the simplest may use thedisplay()decorator, which is used to customize how the field is presented:The name of a model field. For example:
class PersonAdmin(admin.ModelAdmin): list_display = ["first_name", "last_name"]
The name of a related field, using the
__notation. For example:class PersonAdmin(admin.ModelAdmin): list_display = ["city__name"]
A callable that accepts one argument, the model instance. For example:
@admin.display(description="Name") def upper_case_name(obj): return f"{obj.first_name} {obj.last_name}".upper() class PersonAdmin(admin.ModelAdmin): list_display = [upper_case_name]
A string representing a
ModelAdminmethod that accepts one argument, the model instance. For example:class PersonAdmin(admin.ModelAdmin): list_display = ["upper_case_name"] @admin.display(description="Name") def upper_case_name(self, obj): return f"{obj.first_name} {obj.last_name}".upper()
A string representing a model attribute or method (without any required arguments). For example:
from django.contrib import admin from django.db import models class Person(models.Model): name = models.CharField(max_length=50) birthday = models.DateField() @admin.display(description="Birth decade") def decade_born_in(self): decade = self.birthday.year // 10 * 10 return f"{decade}’s" class PersonAdmin(admin.ModelAdmin): list_display = ["name", "decade_born_in"]
Changed in Django 5.1:Support for using
__lookups was added, when targeting related fields.A few special cases to note about
list_display:If the field is a
ForeignKey, Django will display the__str__()of the related object.ManyToManyFieldfields aren’t supported, because that would entail executing a separate SQL statement for each row in the table. If you want to do this nonetheless, give your model a custom method, and add that method’s name tolist_display. (See below for more on custom methods inlist_display.)If the field is a
BooleanField, Django will display a pretty «yes», «no», or «unknown» icon instead ofTrue,False, orNone.If the string given is a method of the model,
ModelAdminor a callable, Django will HTML-escape the output by default. To escape user input and allow your own unescaped tags, useformat_html().Here’s a full example model:
from django.contrib import admin from django.db import models from django.utils.html import format_html class Person(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) color_code = models.CharField(max_length=6) @admin.display def colored_name(self): return format_html( '<span style="color: #{};">{} {}</span>', self.color_code, self.first_name, self.last_name, ) class PersonAdmin(admin.ModelAdmin): list_display = ["first_name", "last_name", "colored_name"]
As some examples have already demonstrated, when using a callable, a model method, or a
ModelAdminmethod, you can customize the column’s title by wrapping the callable with thedisplay()decorator and passing thedescriptionargument.If the value of a field is
None, an empty string, or an iterable without elements, Django will display-(a dash). You can override this withAdminSite.empty_value_display:from django.contrib import admin admin.site.empty_value_display = "(None)"
You can also use
ModelAdmin.empty_value_display:class PersonAdmin(admin.ModelAdmin): empty_value_display = "unknown"
Or on a field level:
class PersonAdmin(admin.ModelAdmin): list_display = ["name", "birth_date_view"] @admin.display(empty_value="unknown") def birth_date_view(self, obj): return obj.birth_date
If the string given is a method of the model,
ModelAdminor a callable that returnsTrue,False, orNone, Django will display a pretty «yes», «no», or «unknown» icon if you wrap the method with thedisplay()decorator passing thebooleanargument with the value set toTrue:from django.contrib import admin from django.db import models class Person(models.Model): first_name = models.CharField(max_length=50) birthday = models.DateField() @admin.display(boolean=True) def born_in_fifties(self): return 1950 <= self.birthday.year < 1960 class PersonAdmin(admin.ModelAdmin): list_display = ["name", "born_in_fifties"]
The
__str__()method is just as valid inlist_displayas any other model method, so it’s perfectly OK to do this:list_display = ["__str__", "some_other_field"]
Usually, elements of
list_displaythat aren’t actual database fields can’t be used in sorting (because Django does all the sorting at the database level).However, if an element of
list_displayrepresents a certain database field, you can indicate this fact by using thedisplay()decorator on the method, passing theorderingargument:from django.contrib import admin from django.db import models from django.utils.html import format_html class Person(models.Model): first_name = models.CharField(max_length=50) color_code = models.CharField(max_length=6) @admin.display(ordering="first_name") def colored_first_name(self): return format_html( '<span style="color: #{};">{}</span>', self.color_code, self.first_name, ) class PersonAdmin(admin.ModelAdmin): list_display = ["first_name", "colored_first_name"]
The above will tell Django to order by the
first_namefield when trying to sort bycolored_first_namein the admin.To indicate descending order with the
orderingargument you can use a hyphen prefix on the field name. Using the above example, this would look like:@admin.display(ordering="-first_name") def colored_first_name(self): ...
The
orderingargument supports query lookups to sort by values on related models. This example includes an «author first name» column in the list display and allows sorting it by first name:class Blog(models.Model): title = models.CharField(max_length=255) author = models.ForeignKey(Person, on_delete=models.CASCADE) class BlogAdmin(admin.ModelAdmin): list_display = ["title", "author", "author_first_name"] @admin.display(ordering="author__first_name") def author_first_name(self, obj): return obj.author.first_name
Query expressions may be used with the
orderingargument:from django.db.models import Value from django.db.models.functions import Concat class Person(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) @admin.display(ordering=Concat("first_name", Value(" "), "last_name")) def full_name(self): return self.first_name + " " + self.last_name
Elements of
list_displaycan also be propertiesclass Person(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) @property @admin.display( ordering="last_name", description="Full name of the person", boolean=False, ) def full_name(self): return self.first_name + " " + self.last_name class PersonAdmin(admin.ModelAdmin): list_display = ["full_name"]
Note that
@propertymust be above@display. If you’re using the old way – setting the display-related attributes directly rather than using thedisplay()decorator – be aware that theproperty()function and not the@propertydecorator must be used:def my_property(self): return self.first_name + " " + self.last_name my_property.short_description = "Full name of the person" my_property.admin_order_field = "last_name" my_property.boolean = False full_name = property(my_property)
The field names in
list_displaywill also appear as CSS classes in the HTML output, in the form ofcolumn-<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_displayin this order:A field of the model or from a related field.
A callable.
A string representing a
ModelAdminattribute.A string representing a model attribute.
For example if you have
first_nameas a model field and as aModelAdminattribute, the model field will be used.
- ModelAdmin.list_display_links¶
Use
list_display_linksto control if and which fields inlist_displayshould be linked to the «change» page for an object.By default, the change list page will link the first column – the first field specified in
list_display– to the change page for each item. Butlist_display_linkslets you change this:Set it to
Noneto get no links at all.Set it to a list or tuple of fields (in the same format as
list_display) whose columns you want converted to links.You can specify one or many fields. As long as the fields appear in
list_display, Django doesn’t care how many (or how few) fields are linked. The only requirement is that if you want to uselist_display_linksin this fashion, you must definelist_display.
In this example, the
first_nameandlast_namefields will be linked on the change list page:class PersonAdmin(admin.ModelAdmin): list_display = ["first_name", "last_name", "birthday"] list_display_links = ["first_name", "last_name"]
In this example, the change list page grid will have no links:
class AuditEntryAdmin(admin.ModelAdmin): list_display = ["timestamp", "message"] list_display_links = None
- ModelAdmin.list_editable¶
Set
list_editableto a list of field names on the model which will allow editing on the change list page. That is, fields listed inlist_editablewill be displayed as form widgets on the change list page, allowing users to edit and save multiple rows at once.Σημείωση
list_editableinteracts with a couple of other options in particular ways; you should note the following rules:Any field in
list_editablemust also be inlist_display. You can’t edit a field that’s not displayed!The same field can’t be listed in both
list_editableandlist_display_links– a field can’t be both a form and a link.
You’ll get a validation error if either of these rules are broken.
- ModelAdmin.list_filter¶
Set
list_filterto activate filters in the right sidebar of the change list page of the admin.At it’s simplest
list_filtertakes a list or tuple of field names to activate filtering upon, but several more advanced options as available. See ModelAdmin List Filters for the details.
- ModelAdmin.list_max_show_all¶
Set
list_max_show_allto control how many items can appear on a «Show all» admin change list page. The admin will display a «Show all» link on the change list only if the total result count is less than or equal to this setting. By default, this is set to200.
- ModelAdmin.list_per_page¶
Set
list_per_pageto control how many items appear on each paginated admin change list page. By default, this is set to100.
Set
list_select_relatedto tell Django to useselect_related()in retrieving the list of objects on the admin change list page. This can save you a bunch of database queries.The value should be either a boolean, a list or a tuple. Default is
False.When value is
True,select_related()will always be called. When value is set toFalse, Django will look atlist_displayand callselect_related()if anyForeignKeyis present.If you need more fine-grained control, use a tuple (or list) as value for
list_select_related. Empty tuple will prevent Django from callingselect_relatedat all. Any other tuple will be passed directly toselect_relatedas parameters. For example:class ArticleAdmin(admin.ModelAdmin): list_select_related = ["author", "category"]
will call
select_related('author', 'category').If you need to specify a dynamic value based on the request, you can implement a
get_list_select_related()method.Σημείωση
ModelAdminignores this attribute whenselect_related()was already called on the changelist’sQuerySet.
- ModelAdmin.ordering¶
Set
orderingto specify how lists of objects should be ordered in the Django admin views. This should be a list or tuple in the same format as a model’sorderingparameter.If this isn’t provided, the Django admin will use the model’s default ordering.
If you need to specify a dynamic order (for example depending on user or language) you can implement a
get_ordering()method.Performance considerations with ordering and sorting
To ensure a deterministic ordering of results, the changelist adds
pkto the ordering if it can’t find a single or unique together set of fields that provide total ordering.For example, if the default ordering is by a non-unique
namefield, then the changelist is sorted bynameandpk. This could perform poorly if you have a lot of rows and don’t have an index onnameandpk.
- ModelAdmin.paginator¶
The paginator class to be used for pagination. By default,
django.core.paginator.Paginatoris used. If the custom paginator class doesn’t have the same constructor interface asdjango.core.paginator.Paginator, you will also need to provide an implementation forModelAdmin.get_paginator().
- ModelAdmin.prepopulated_fields¶
Set
prepopulated_fieldsto a dictionary mapping field names to the fields it should prepopulate from:class ArticleAdmin(admin.ModelAdmin): prepopulated_fields = {"slug": ["title"]}
When set, the given fields will use a bit of JavaScript to populate from the fields assigned. The main use for this functionality is to automatically generate the value for
SlugFieldfields from one or more other fields. The generated value is produced by concatenating the values of the source fields, and then by transforming that result into a valid slug (e.g. substituting dashes for spaces and lowercasing ASCII letters).Prepopulated fields aren’t modified by JavaScript after a value has been saved. It’s usually undesired that slugs change (which would cause an object’s URL to change if the slug is used in it).
prepopulated_fieldsdoesn’t acceptDateTimeField,ForeignKey,OneToOneField, andManyToManyFieldfields.
- ModelAdmin.preserve_filters¶
By default, applied filters are preserved on the list view after creating, editing, or deleting an object. You can have filters cleared by setting this attribute to
False.
- ModelAdmin.show_facets¶
Controls whether facet counts are displayed for filters in the admin changelist. Defaults to
ShowFacets.ALLOW.When displayed, facet counts update in line with currently applied filters.
- class ShowFacets¶
Enum of allowed values for
ModelAdmin.show_facets.- ALWAYS¶
Always show facet counts.
- ALLOW¶
Show facet counts when the
_facetsquery string parameter is provided.
- NEVER¶
Never show facet counts.
Set
show_facetsto the desiredShowFacetsvalue. For example, to always show facet counts without needing to provide the query parameter:from django.contrib import admin class MyModelAdmin(admin.ModelAdmin): ... # Have facets always shown for this model admin. show_facets = admin.ShowFacets.ALWAYS
Performance considerations with facets
Enabling facet filters will increase the number of queries on the admin changelist page in line with the number of filters. These queries may cause performance problems, especially for large datasets. In these cases it may be appropriate to set
show_facetstoShowFacets.NEVERto disable faceting entirely.
- ModelAdmin.radio_fields¶
By default, Django’s admin uses a select-box interface (<select>) for fields that are
ForeignKeyor havechoicesset. If a field is present inradio_fields, Django will use a radio-button interface instead. Assuminggroupis aForeignKeyon thePersonmodel:class PersonAdmin(admin.ModelAdmin): radio_fields = {"group": admin.VERTICAL}
You have the choice of using
HORIZONTALorVERTICALfrom thedjango.contrib.adminmodule.Don’t include a field in
radio_fieldsunless it’s aForeignKeyor haschoicesset.
- ModelAdmin.autocomplete_fields¶
autocomplete_fieldsis a list ofForeignKeyand/orManyToManyFieldfields you would like to change to Select2 autocomplete inputs.By default, the admin uses a select-box interface (
<select>) for those fields. Sometimes you don’t want to incur the overhead of selecting all the related instances to display in the dropdown.The Select2 input looks similar to the default input but comes with a search feature that loads the options asynchronously. This is faster and more user-friendly if the related model has many instances.
You must define
search_fieldson the related object’sModelAdminbecause the autocomplete search uses it.To avoid unauthorized data disclosure, users must have the
vieworchangepermission to the related object in order to use autocomplete.Ordering and pagination of the results are controlled by the related
ModelAdmin’sget_ordering()andget_paginator()methods.In the following example,
ChoiceAdminhas an autocomplete field for theForeignKeyto theQuestion. The results are filtered by thequestion_textfield and ordered by thedate_createdfield:class QuestionAdmin(admin.ModelAdmin): ordering = ["date_created"] search_fields = ["question_text"] class ChoiceAdmin(admin.ModelAdmin): autocomplete_fields = ["question"]
Performance considerations for large datasets
Ordering using
ModelAdmin.orderingmay cause performance problems as sorting on a large queryset will be slow.Also, if your search fields include fields that aren’t indexed by the database, you might encounter poor performance on extremely large tables.
For those cases, it’s a good idea to write your own
ModelAdmin.get_search_results()implementation using a full-text indexed search.You may also want to change the
Paginatoron very large tables as the default paginator always performs acount()query. For example, you could override the default implementation of thePaginator.countproperty.
- ModelAdmin.raw_id_fields¶
By default, Django’s admin uses a select-box interface (<select>) for fields that are
ForeignKey. Sometimes you don’t want to incur the overhead of having to select all the related instances to display in the drop-down.raw_id_fieldsis a list of fields you would like to change into anInputwidget for either aForeignKeyorManyToManyField:class ArticleAdmin(admin.ModelAdmin): raw_id_fields = ["newspaper"]
The
raw_id_fieldsInputwidget should contain a primary key if the field is aForeignKeyor a comma separated list of values if the field is aManyToManyField. Theraw_id_fieldswidget shows a magnifying glass button next to the field which allows users to search for and select a value:
- ModelAdmin.readonly_fields¶
By default the admin shows all fields as editable. Any fields in this option (which should be a
listortuple) will display its data as-is and non-editable; they are also excluded from theModelFormused for creating and editing. Note that when specifyingModelAdmin.fieldsorModelAdmin.fieldsetsthe read-only fields must be present to be shown (they are ignored otherwise).If
readonly_fieldsis used without defining explicit ordering throughModelAdmin.fieldsorModelAdmin.fieldsetsthey will be added last after all editable fields.A read-only field can not only display data from a model’s field, it can also display the output of a model’s method or a method of the
ModelAdminclass itself. This is very similar to the wayModelAdmin.list_displaybehaves. This provides a way to use the admin interface to provide feedback on the status of the objects being edited, for example:from django.contrib import admin from django.utils.html import format_html_join from django.utils.safestring import mark_safe class PersonAdmin(admin.ModelAdmin): readonly_fields = ["address_report"] # description functions like a model field's verbose_name @admin.display(description="Address") def address_report(self, instance): # assuming get_full_address() returns a list of strings # for each line of the address and you want to separate each # line by a linebreak return format_html_join( mark_safe("<br>"), "{}", ((line,) for line in instance.get_full_address()), ) or mark_safe("<span class='errors'>I can't determine this address.</span>")
- ModelAdmin.save_as¶
Set
save_asto enable a «save as new» feature on admin change forms.Normally, objects have three save options: «Save», «Save and continue editing», and «Save and add another». If
save_asisTrue, «Save and add another» will be replaced by a «Save as new» button that creates a new object (with a new ID) rather than updating the existing object.By default,
save_asis set toFalse.
- ModelAdmin.save_as_continue¶
When
save_as=True, the default redirect after saving the new object is to the change view for that object. If you setsave_as_continue=False, the redirect will be to the changelist view.By default,
save_as_continueis set toTrue.
- ModelAdmin.save_on_top¶
Set
save_on_topto add save buttons across the top of your admin change forms.Normally, the save buttons appear only at the bottom of the forms. If you set
save_on_top, the buttons will appear both on the top and the bottom.By default,
save_on_topis set toFalse.
- ModelAdmin.search_fields¶
Set
search_fieldsto enable a search box on the admin change list page. This should be set to a list of field names that will be searched whenever somebody submits a search query in that text box.These fields should be some kind of text field, such as
CharFieldorTextField. You can also perform a related lookup on aForeignKeyorManyToManyFieldwith the lookup API «follow» notation:search_fields = ["foreign_key__related_fieldname"]
For example, if you have a blog entry with an author, the following definition would enable searching blog entries by the email address of the author:
search_fields = ["user__email"]
When somebody does a search in the admin search box, Django splits the search query into words and returns all objects that contain each of the words, case-insensitive (using the
icontainslookup), where each word must be in at least one ofsearch_fields. For example, ifsearch_fieldsis set to['first_name', 'last_name']and a user searches forjohn lennon, Django will do the equivalent of this SQLWHEREclause:WHERE (first_name ILIKE '%john%' OR last_name ILIKE '%john%') AND (first_name ILIKE '%lennon%' OR last_name ILIKE '%lennon%')
The search query can contain quoted phrases with spaces. For example, if a user searches for
"john winston"or'john winston', Django will do the equivalent of this SQLWHEREclause:WHERE (first_name ILIKE '%john winston%' OR last_name ILIKE '%john winston%')
If you don’t want to use
icontainsas the lookup, you can use any lookup by appending it the field. For example, you could useexactby settingsearch_fieldsto['first_name__exact'].Some (older) shortcuts for specifying a field lookup are also available. You can prefix a field in
search_fieldswith the following characters and it’s equivalent to adding__<lookup>to the field:Prefix
Lookup
^
=
@
None
If you need to customize search you can use
ModelAdmin.get_search_results()to provide additional or alternate search behavior.
- ModelAdmin.search_help_text¶
Set
search_help_textto specify a descriptive text for the search box which will be displayed below it.
- ModelAdmin.show_full_result_count¶
Set
show_full_result_countto control whether the full count of objects should be displayed on a filtered admin page (e.g.99 results (103 total)). If this option is set toFalse, a text like99 results (Show all)is displayed instead.The default of
show_full_result_count=Truegenerates a query to perform a full count on the table which can be expensive if the table contains a large number of rows.
- ModelAdmin.sortable_by¶
By default, the change list page allows sorting by all model fields (and callables that use the
orderingargument to thedisplay()decorator or have theadmin_order_fieldattribute) specified inlist_display.If you want to disable sorting for some columns, set
sortable_byto a collection (e.g.list,tuple, orset) of the subset oflist_displaythat you want to be sortable. An empty collection disables sorting for all columns.If you need to specify this list dynamically, implement a
get_sortable_by()method instead.
- ModelAdmin.view_on_site¶
Set
view_on_siteto control whether or not to display the «View on site» link. This link should bring you to a URL where you can display the saved object.This value can be either a boolean flag or a callable. If
True(the default), the object’sget_absolute_url()method will be used to generate the url.If your model has a
get_absolute_url()method but you don’t want the «View on site» button to appear, you only need to setview_on_sitetoFalse:from django.contrib import admin class PersonAdmin(admin.ModelAdmin): view_on_site = False
In case it is a callable, it accepts the model instance as a parameter. For example:
from django.contrib import admin from django.urls import reverse class PersonAdmin(admin.ModelAdmin): def view_on_site(self, obj): url = reverse("person-detail", kwargs={"slug": obj.slug}) return "https://example.com" + url
Custom template options¶
The Overriding admin templates section describes how to override or extend
the default admin templates. Use the following options to override the default
templates used by the ModelAdmin views:
- ModelAdmin.add_form_template¶
Path to a custom template, used by
add_view().
- ModelAdmin.change_form_template¶
Path to a custom template, used by
change_view().
- ModelAdmin.change_list_template¶
Path to a custom template, used by
changelist_view().
- ModelAdmin.delete_confirmation_template¶
Path to a custom template, used by
delete_view()for displaying a confirmation page when deleting one or more objects.
- ModelAdmin.delete_selected_confirmation_template¶
Path to a custom template, used by the
delete_selectedaction method for displaying a confirmation page when deleting one or more objects. See the actions documentation.
- ModelAdmin.object_history_template¶
Path to a custom template, used by
history_view().
- ModelAdmin.popup_response_template¶
Path to a custom template, used by
response_add(),response_change(), andresponse_delete().
ModelAdmin methods¶
Προειδοποίηση
When overriding ModelAdmin.save_model() and
ModelAdmin.delete_model(), your code must save/delete the
object. They aren’t meant for veto purposes, rather they allow you to
perform extra operations.
- ModelAdmin.save_model(request, obj, form, change)[πηγή]¶
The
save_modelmethod is given theHttpRequest, a model instance, aModelForminstance, and a boolean value based on whether it is adding or changing the object. Overriding this method allows doing pre- or post-save operations. Callsuper().save_model()to save the object usingModel.save().For example to attach
request.userto the object prior to saving:from django.contrib import admin class ArticleAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): obj.user = request.user super().save_model(request, obj, form, change)
- ModelAdmin.delete_model(request, obj)[πηγή]¶
The
delete_modelmethod is given theHttpRequestand a model instance. Overriding this method allows doing pre- or post-delete operations. Callsuper().delete_model()to delete the object usingModel.delete().
- ModelAdmin.delete_queryset(request, queryset)[πηγή]¶
The
delete_queryset()method is given theHttpRequestand aQuerySetof objects to be deleted. Override this method to customize the deletion process for the «delete selected objects» action.
- ModelAdmin.save_formset(request, form, formset, change)[πηγή]¶
The
save_formsetmethod is given theHttpRequest, the parentModelForminstance and a boolean value based on whether it is adding or changing the parent object.For example, to attach
request.userto each changed formset model instance:class ArticleAdmin(admin.ModelAdmin): def save_formset(self, request, form, formset, change): instances = formset.save(commit=False) for obj in formset.deleted_objects: obj.delete() for instance in instances: instance.user = request.user instance.save() formset.save_m2m()
See also Saving objects in the formset.
Προειδοποίηση
All hooks that return a ModelAdmin property return the property itself
rather than a copy of its value. Dynamically modifying the value can lead
to surprising results.
Let’s take ModelAdmin.get_readonly_fields() as an example:
class PersonAdmin(admin.ModelAdmin):
readonly_fields = ["name"]
def get_readonly_fields(self, request, obj=None):
readonly = super().get_readonly_fields(request, obj)
if not request.user.is_superuser:
readonly.append("age") # Edits the class attribute.
return readonly
This results in readonly_fields becoming
["name", "age", "age", ...], even for a superuser, as "age" is added
each time non-superuser visits the page.
- ModelAdmin.get_ordering(request)¶
The
get_orderingmethod takes arequestas parameter and is expected to return alistortuplefor ordering similar to theorderingattribute. For example:class PersonAdmin(admin.ModelAdmin): def get_ordering(self, request): if request.user.is_superuser: return ["name", "rank"] else: return ["name"]
- ModelAdmin.get_search_results(request, queryset, search_term)[πηγή]¶
The
get_search_resultsmethod modifies the list of objects displayed into those that match the provided search term. It accepts the request, a queryset that applies the current filters, and the user-provided search term. It returns a tuple containing a queryset modified to implement the search, and a boolean indicating if the results may contain duplicates.The default implementation searches the fields named in
ModelAdmin.search_fields.This method may be overridden with your own custom search method. For example, you might wish to search by an integer field, or use an external tool such as Solr or Haystack. You must establish if the queryset changes implemented by your search method may introduce duplicates into the results, and return
Truein the second element of the return value.For example, to search by
nameandage, you could use:class PersonAdmin(admin.ModelAdmin): list_display = ["name", "age"] search_fields = ["name"] def get_search_results(self, request, queryset, search_term): queryset, may_have_duplicates = super().get_search_results( request, queryset, search_term, ) try: search_term_as_int = int(search_term) except ValueError: pass else: queryset |= self.model.objects.filter(age=search_term_as_int) return queryset, may_have_duplicates
This implementation is more efficient than
search_fields = ('name', '=age')which results in a string comparison for the numeric field, for example... OR UPPER("polls_choice"."votes"::text) = UPPER('4')on PostgreSQL.
The
save_relatedmethod is given theHttpRequest, the parentModelForminstance, the list of inline formsets and a boolean value based on whether the parent is being added or changed. Here you can do any pre- or post-save operations for objects related to the parent. Note that at this point the parent object and its form have already been saved.
- ModelAdmin.get_autocomplete_fields(request)¶
The
get_autocomplete_fields()method is given theHttpRequestand is expected to return alistortupleof field names that will be displayed with an autocomplete widget as described above in theModelAdmin.autocomplete_fieldssection.
- ModelAdmin.get_readonly_fields(request, obj=None)¶
The
get_readonly_fieldsmethod is given theHttpRequestand theobjbeing edited (orNoneon an add form) and is expected to return alistortupleof field names that will be displayed as read-only, as described above in theModelAdmin.readonly_fieldssection.
- ModelAdmin.get_prepopulated_fields(request, obj=None)¶
The
get_prepopulated_fieldsmethod is given theHttpRequestand theobjbeing edited (orNoneon an add form) and is expected to return adictionary, as described above in theModelAdmin.prepopulated_fieldssection.
- ModelAdmin.get_list_display(request)[πηγή]¶
The
get_list_displaymethod is given theHttpRequestand is expected to return alistortupleof field names that will be displayed on the changelist view as described above in theModelAdmin.list_displaysection.
- ModelAdmin.get_list_display_links(request, list_display)[πηγή]¶
The
get_list_display_linksmethod is given theHttpRequestand thelistortuplereturned byModelAdmin.get_list_display(). It is expected to return eitherNoneor alistortupleof field names on the changelist that will be linked to the change view, as described in theModelAdmin.list_display_linkssection.
- ModelAdmin.get_exclude(request, obj=None)¶
The
get_excludemethod is given theHttpRequestand theobjbeing edited (orNoneon an add form) and is expected to return a list of fields, as described inModelAdmin.exclude.
- ModelAdmin.get_fields(request, obj=None)¶
The
get_fieldsmethod is given theHttpRequestand theobjbeing edited (orNoneon an add form) and is expected to return a list of fields, as described above in theModelAdmin.fieldssection.
- ModelAdmin.get_fieldsets(request, obj=None)¶
The
get_fieldsetsmethod is given theHttpRequestand theobjbeing edited (orNoneon an add form) and is expected to return a list of 2-tuples, in which each 2-tuple represents a<fieldset>on the admin form page, as described above in theModelAdmin.fieldsetssection.
- ModelAdmin.get_list_filter(request)[πηγή]¶
The
get_list_filtermethod is given theHttpRequestand is expected to return the same kind of sequence type as for thelist_filterattribute.
The
get_list_select_relatedmethod is given theHttpRequestand should return a boolean or list asModelAdmin.list_select_relateddoes.
- ModelAdmin.get_search_fields(request)[πηγή]¶
The
get_search_fieldsmethod is given theHttpRequestand is expected to return the same kind of sequence type as for thesearch_fieldsattribute.
- ModelAdmin.get_sortable_by(request)¶
The
get_sortable_by()method is passed theHttpRequestand is expected to return a collection (e.g.list,tuple, orset) of field names that will be sortable in the change list page.Its default implementation returns
sortable_byif it’s set, otherwise it defers toget_list_display().For example, to prevent one or more columns from being sortable:
class PersonAdmin(admin.ModelAdmin): def get_sortable_by(self, request): return {*self.get_list_display(request)} - {"rank"}
- ModelAdmin.get_inline_instances(request, obj=None)[πηγή]¶
The
get_inline_instancesmethod is given theHttpRequestand theobjbeing edited (orNoneon an add form) and is expected to return alistortupleofInlineModelAdminobjects, as described below in theInlineModelAdminsection. For example, the following would return inlines without the default filtering based on add, change, delete, and view permissions:class MyModelAdmin(admin.ModelAdmin): inlines = [MyInline] def get_inline_instances(self, request, obj=None): return [inline(self.model, self.admin_site) for inline in self.inlines]
If you override this method, make sure that the returned inlines are instances of the classes defined in