default_tags = [<class 'flask.json.tag.TagDict'>, <class 'flask.json.tag.PassDict'>, <class 'flask.json.tag.TagTuple'>, <class 'flask.json.tag.PassList'>, <class 'flask.json.tag.TagBytes'>, <class 'flask.json.tag.TagMarkup'>, <class 'flask.json.tag.TagUUID'>, <class 'flask.json.tag.TagDateTime'>]
Tag classes to bind when creating the serializer. Other tags can be added later using register().


dumps(value)
Tag the value and dump it to a compact JSON string.  Parameters
value (Any) –   Return type
str


loads(value)
Load data from a JSON string and deserialized any tagged objects.  Parameters
value (str) –   Return type
Any


register(tag_class, force=False, index=None)
Register a new tag with this serializer.  Parameters

tag_class (Type[flask.json.tag.JSONTag]) – tag class to register. Will be instantiated with this serializer instance.
force (bool) – overwrite an existing tag. If false (default), a KeyError is raised.
index (Optional[int]) – index to insert the new tag in the tag order. Useful when the new tag is a special case of an existing tag. If None (default), the tag is appended to the end of the order.   Raises
KeyError – if the tag key is already registered and force is not true.  Return type
None


tag(value)
Convert a value to a tagged representation if necessary.  Parameters
value (Any) –   Return type
Dict[str, Any]


untag(value)
Convert a tagged representation back to the original type.  Parameters
value (Dict[str, Any]) –   Return type
Any


Templates Flask leverages Jinja2 as its template engine. You are obviously free to use a different template engine, but you still have to install Jinja2 to run Flask itself. This requirement is necessary to enable rich extensions. An extension can depend on Jinja2 being present. This section only gives a very quick introduction into how Jinja2 is integrated into Flask. If you want information on the template engine’s syntax itself, head over to the official Jinja2 Template Documentation for more information. Jinja Setup Unless customized, Jinja2 is configured by Flask as follows:  autoescaping is enabled for all templates ending in .html, .htm, .xml as well as .xhtml when using render_template(). autoescaping is enabled for all strings when using render_template_string(). a template has the ability to opt in/out autoescaping with the {% autoescape %} tag. Flask inserts a couple of global functions and helpers into the Jinja2 context, additionally to the values that are present by default.  Standard Context The following global variables are available within Jinja2 templates by default:   config

The current configuration object (flask.config)  Changelog Changed in version 0.10: This is now always available, even in imported templates.   New in version 0.6.

   request

The current request object (flask.request). This variable is unavailable if the template was rendered without an active request context.
   session

The current session object (flask.session). This variable is unavailable if the template was rendered without an active request context.
   g

The request-bound object for global variables (flask.g). This variable is unavailable if the template was rendered without an active request context.
   url_for()

The flask.url_for() function.
   get_flashed_messages()

The flask.get_flashed_messages() function.
  The Jinja Context Behavior These variables are added to the context of variables, they are not global variables. The difference is that by default these will not show up in the context of imported templates. This is partially caused by performance considerations, partially to keep things explicit. What does this mean for you? If you have a macro you want to import, that needs to access the request object you have two possibilities:  you explicitly pass the request to the macro as parameter, or the attribute of the request object you are interested in. you import the macro “with context”.  Importing with context looks like this: {% from '_helpers.html' import my_macro with context %}
  Controlling Autoescaping Autoescaping is the concept of automatically escaping special characters for you. Special characters in the sense of HTML (or XML, and thus XHTML) are &, >, <, " as well as '. Because these characters carry specific meanings in documents on their own you have to replace them by so called “entities” if you want to use them for text. Not doing so would not only cause user frustration by the inability to use these characters in text, but can also lead to security problems. (see Cross-Site Scripting (XSS)) Sometimes however you will need to disable autoescaping in templates. This can be the case if you want to explicitly inject HTML into pages, for example if they come from a system that generates secure HTML like a markdown to HTML converter. There are three ways to accomplish that:  In the Python code, wrap the HTML string in a Markup object before passing it to the template. This is in general the recommended way. Inside the template, use the |safe filter to explicitly mark a string as safe HTML ({{ myvariable|safe }}) Temporarily disable the autoescape system altogether.  To disable the autoescape system in templates, you can use the {%
autoescape %} block: {% autoescape false %}
    <p>autoescaping is disabled here
    <p>{{ will_not_be_escaped }}
{% endautoescape %}
 Whenever you do this, please be very cautious about the variables you are using in this block. Registering Filters If you want to register your own filters in Jinja2 you have two ways to do that. You can either put them by hand into the jinja_env of the application or use the template_filter() decorator. The two following examples work the same and both reverse an object: @app.template_filter('reverse')
def reverse_filter(s):
    return s[::-1]

def reverse_filter(s):
    return s[::-1]
app.jinja_env.filters['reverse'] = reverse_filter
 In case of the decorator the argument is optional if you want to use the function name as name of the filter. Once registered, you can use the filter in your templates in the same way as Jinja2’s builtin filters, for example if you have a Python list in context called mylist: {% for x in mylist | reverse %}
{% endfor %}
 Context Processors To inject new variables automatically into the context of a template, context processors exist in Flask. Context processors run before the template is rendered and have the ability to inject new values into the template context. A context processor is a function that returns a dictionary. The keys and values of this dictionary are then merged with the template context, for all templates in the app: @app.context_processor
def inject_user():
    return dict(user=g.user)
 The context processor above makes a variable called user available in the template with the value of g.user. This example is not very interesting because g is available in templates anyways, but it gives an idea how this works. Variables are not limited to values; a context processor can also make functions available to templates (since Python allows passing around functions): @app.context_processor
def utility_processor():
    def format_price(amount, currency="€"):
        return f"{amount:.2f}{currency}"
    return dict(format_price=format_price)
 The context processor above makes the format_price function available to all templates: {{ format_price(0.33) }}
 You could also build format_price as a template filter (see Registering Filters), but this demonstrates how to pass functions in a context processor.


TEMPLATES_AUTO_RELOAD
Reload templates when they are changed. If not set, it will be enabled in debug mode. Default: None


TESTING
Enable testing mode. Exceptions are propagated rather than handled by the the app’s error handlers. Extensions may also change their behavior to facilitate easier testing. You should enable this in your own tests. Default: False


TRAP_BAD_REQUEST_ERRORS
Trying to access a key that doesn’t exist from request dicts like args and form will return a 400 Bad Request error page. Enable this to treat the error as an unhandled exception instead so that you get the interactive debugger. This is a more specific version of TRAP_HTTP_EXCEPTIONS. If unset, it is enabled in debug mode. Default: None


TRAP_HTTP_EXCEPTIONS
If there is no handler for an HTTPException-type exception, re-raise it to be handled by the interactive debugger instead of returning it as a simple error response. Default: False


flask.url_for(endpoint, **values)
Generates a URL to the given endpoint with the method provided. Variable arguments that are unknown to the target endpoint are appended to the generated URL as query arguments. If the value of a query argument is None, the whole pair is skipped. In case blueprints are active you can shortcut references to the same blueprint by prefixing the local endpoint with a dot (.). This will reference the index function local to the current blueprint: url_for('.index')
 See URL Building. Configuration values APPLICATION_ROOT and SERVER_NAME are only used when generating URLs outside of a request context. To integrate applications, Flask has a hook to intercept URL build errors through Flask.url_build_error_handlers. The url_for function results in a BuildError when the current app does not have a URL for the given endpoint and values. When it does, the current_app calls its url_build_error_handlers if it is not None, which can return a string to use as the result of url_for (instead of url_for’s default to raise the BuildError exception) or re-raise the exception. An example: def external_url_handler(error, endpoint, values):
    "Looks up an external URL when `url_for` cannot build a URL."
    # This is an example of hooking the build_error_handler.
    # Here, lookup_url is some utility function you've built
    # which looks up the endpoint in some external URL registry.
    url = lookup_url(endpoint, **values)
    if url is None:
        # External lookup did not have a URL.
        # Re-raise the BuildError, in context of original traceback.
        exc_type, exc_value, tb = sys.exc_info()
        if exc_value is error:
            raise exc_type(exc_value).with_traceback(tb)
        else:
            raise error
    # url_for will use this result, instead of raising BuildError.
    return url

app.url_build_error_handlers.append(external_url_handler)
 Here, error is the instance of BuildError, and endpoint and values are the arguments passed into url_for. Note that this is for building URLs outside the current application, and not for handling 404 NotFound errors.  Changelog New in version 0.10: The _scheme parameter was added.   New in version 0.9: The _anchor and _method parameters were added.   New in version 0.9: Calls Flask.handle_build_error() on BuildError.   Parameters

endpoint (str) – the endpoint of the URL (name of the function)
values (Any) – the variable arguments of the URL rule
_external – if set to True, an absolute URL is generated. Server address can be changed via SERVER_NAME configuration variable which falls back to the Host header, then to the IP and port of the request.
_scheme – a string specifying the desired URL scheme. The _external parameter must be set to True or a ValueError is raised. The default behavior uses the same scheme as the current request, or PREFERRED_URL_SCHEME if no request context is available. This also can be set to an empty string to build protocol-relative URLs.
_anchor – if provided this is added as anchor to the URL.
_method – if provided this explicitly specifies an HTTP method.   Return type
str


USE_X_SENDFILE
When serving files, set the X-Sendfile header instead of serving the data with Flask. Some web servers, such as Apache, recognize this and serve the data more efficiently. This only makes sense when using such a server. Default: False


uWSGI uWSGI is a deployment option on servers like nginx, lighttpd, and cherokee; see FastCGI and Standalone WSGI Containers for other options. To use your WSGI application with uWSGI protocol you will need a uWSGI server first. uWSGI is both a protocol and an application server; the application server can serve uWSGI, FastCGI, and HTTP protocols. The most popular uWSGI server is uwsgi, which we will use for this guide. Make sure to have it installed to follow along.  Watch Out Please make sure in advance that any app.run() calls you might have in your application file are inside an if __name__ ==
'__main__': block or moved to a separate file. Just make sure it’s not called because this will always start a local WSGI server which we do not want if we deploy that application to uWSGI.  Starting your app with uwsgi uwsgi is designed to operate on WSGI callables found in python modules. Given a flask application in myapp.py, use the following command: $ uwsgi -s /tmp/yourapplication.sock --manage-script-name --mount /yourapplication=myapp:app
 The --manage-script-name will move the handling of SCRIPT_NAME to uwsgi, since it is smarter about that. It is used together with the --mount directive which will make requests to /yourapplication be directed to myapp:app. If your application is accessible at root level, you can use a single / instead of /yourapplication. myapp refers to the name of the file of your flask application (without extension) or the module which provides app. app is the callable inside of your application (usually the line reads app = Flask(__name__). If you want to deploy your flask application inside of a virtual environment, you need to also add --virtualenv /path/to/virtual/environment. You might also need to add --plugin python or --plugin python3 depending on which python version you use for your project. Configuring nginx A basic flask nginx configuration looks like this: location = /yourapplication { rewrite ^ /yourapplication/; }
location /yourapplication { try_files $uri @yourapplication; }
location @yourapplication {
  include uwsgi_params;
  uwsgi_pass unix:/tmp/yourapplication.sock;
}
 This configuration binds the application to /yourapplication. If you want to have it in the URL root its a bit simpler: location / { try_files $uri @yourapplication; }
location @yourapplication {
    include uwsgi_params;
    uwsgi_pass unix:/tmp/yourapplication.sock;
}


class flask.views.View
Alternative way to use view functions. A subclass has to implement dispatch_request() which is called with the view arguments from the URL routing system. If methods is provided the methods do not have to be passed to the add_url_rule() method explicitly: class MyView(View):
    methods = ['GET']

    def dispatch_request(self, name):
        return f"Hello {name}!"

app.add_url_rule('/hello/<name>', view_func=MyView.as_view('myview'))
 When you want to decorate a pluggable view you will have to either do that when the view function is created (by wrapping the return value of as_view()) or you can use the decorators attribute: class SecretView(View):
    methods = ['GET']
    decorators = [superuser_required]

    def dispatch_request(self):
        ...
 The decorators stored in the decorators list are applied one after another when the view function is created. Note that you can not use the class based decorators since those would decorate the view class and not the generated view function!
classmethod as_view(name, *class_args, **class_kwargs)
Converts the class into an actual view function that can be used with the routing system. Internally this generates a function on the fly which will instantiate the View on each request and call the dispatch_request() method on it. The arguments passed to as_view() are forwarded to the constructor of the class.  Parameters

name (str) –
class_args (Any) –
class_kwargs (Any) –    Return type
Callable

decorators: List[Callable] = []
The canonical way to decorate class-based views is to decorate the return value of as_view(). However since this moves parts of the logic from the class declaration to the place where it’s hooked into the routing system. You can place one or more decorators in this list and whenever the view function is created the result is automatically decorated.  Changelog New in version 0.8.

dispatch_request()
Subclasses have to override this method to implement the actual view function code. This method is called with all the arguments from the URL rule.  Return type
Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], Union[Headers, Dict[str, Union[str, List[str], Tuple[str, …]]], List[Tuple[str, Union[str, List[str], Tuple[str, …]]]]]], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], int], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], int, Union[Headers, Dict[str, Union[str, List[str], Tuple[str, …]]], List[Tuple[str, Union[str, List[str], Tuple[str, …]]]]]], WSGIApplication]

methods: Optional[List[str]] = None
A list of methods this view can handle.

provide_automatic_options: Optional[bool] = None
Setting this disables or force-enables the automatic options handling.


classmethod as_view(name, *class_args, **class_kwargs)
Converts the class into an actual view function that can be used with the routing system. Internally this generates a function on the fly which will instantiate the View on each request and call the dispatch_request() method on it. The arguments passed to as_view() are forwarded to the constructor of the class.  Parameters

name (str) –
class_args (Any) –
class_kwargs (Any) –    Return type
Callable


decorators: List[Callable] = []
The canonical way to decorate class-based views is to decorate the return value of as_view(). However since this moves parts of the logic from the class declaration to the place where it’s hooked into the routing system. You can place one or more decorators in this list and whenever the view function is created the result is automatically decorated.  Changelog New in version 0.8.


dispatch_request()
Subclasses have to override this method to implement the actual view function code. This method is called with all the arguments from the URL rule.  Return type
Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], Union[Headers, Dict[str, Union[str, List[str], Tuple[str, …]]], List[Tuple[str, Union[str, List[str], Tuple[str, …]]]]]], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], int], Tuple[Union[Response, AnyStr, Dict[str, Any], Generator[AnyStr, None, None]], int, Union[Headers, Dict[str, Union[str, List[str], Tuple[str, …]]], List[Tuple[str, Union[str, List[str], Tuple[str, …]]]]]], WSGIApplication]


methods: Optional[List[str]] = None
A list of methods this view can handle.


provide_automatic_options: Optional[bool] = None
Setting this disables or force-enables the automatic options handling.


flask.cli.with_appcontext(f)
Wraps a callback so that it’s guaranteed to be executed with the script’s application context. If callbacks are registered directly to the app.cli object then they are wrapped with this function by default unless it’s disabled.


class flask.ctx._AppCtxGlobals
A plain object. Used as a namespace for storing data during an application context. Creating an app context automatically creates this object, which is made available as the g proxy.   'key' in g

Check whether an attribute is present.  Changelog New in version 0.10.

   iter(g)

Return an iterator over the attribute names.  Changelog New in version 0.10.

get(name, default=None)
Get an attribute by name, or a default value. Like dict.get().  Parameters

name (str) – Name of attribute to get.
default (Optional[Any]) – Value to return if the attribute is not present.   Return type
Any    Changelog New in version 0.10.

pop(name, default=<object object>)
Get and remove an attribute by name. Like dict.pop().  Parameters

name (str) – Name of attribute to pop.
default (Any) – Value to return if the attribute is not present, instead of raising a KeyError.   Return type
Any    Changelog New in version 0.11.

setdefault(name, default=None)
Get the value of an attribute if it is present, otherwise set and return a default value. Like dict.setdefault().  Parameters

name (str) – Name of attribute to get.
default (Optional[Any]) – Value to set and return if the attribute is not present.   Return type
Any    Changelog New in version 0.11.


get(name, default=None)
Get an attribute by name, or a default value. Like dict.get().  Parameters

name (str) – Name of attribute to get.
default (Optional[Any]) – Value to return if the attribute is not present.   Return type
Any    Changelog New in version 0.10.


pop(name, default=<object object>)
Get and remove an attribute by name. Like dict.pop().  Parameters

name (str) – Name of attribute to pop.
default (Any) – Value to return if the attribute is not present, instead of raising a KeyError.   Return type
Any    Changelog New in version 0.11.


setdefault(name, default=None)
Get the value of an attribute if it is present, otherwise set and return a default value. Like dict.setdefault().  Parameters

name (str) – Name of attribute to get.
default (Optional[Any]) – Value to set and return if the attribute is not present.   Return type
Any    Changelog New in version 0.11.


action(*, permissions=None, description=None)
 New in Django 3.2.  This decorator can be used for setting specific attributes on custom action functions that can be used with actions: @admin.action(
    permissions=['publish'],
    description='Mark selected stories as published',
)
def make_published(self, request, queryset):
    queryset.update(status='p')
 This is equivalent to setting some attributes (with the original, longer names) on the function directly: def make_published(self, request, queryset):
    queryset.update(status='p')
make_published.allowed_permissions = ['publish']
make_published.short_description = 'Mark selected stories as published'
 Use of this decorator is not compulsory to make an action function, but it can be useful to use it without arguments as a marker in your source to identify the purpose of the function: @admin.action
def make_inactive(self, request, queryset):
    queryset.update(is_active=False)
 In this case it will add no attributes to the function.


class AdminSite(name='admin')
A Django administrative site is represented by an instance of django.contrib.admin.sites.AdminSite; by default, an instance of this class is created as django.contrib.admin.site and you can register your models and ModelAdmin instances with it. If you want to customize the default admin site, you can override it. When constructing an instance of an AdminSite, you can provide a unique instance name using the name argument to the constructor. This instance name is used to identify the instance, especially when reversing admin URLs. If no instance name is provided, a default instance name of admin will be used. See Customizing the AdminSite class for an example of customizing the AdminSite class.


AdminSite.add_action(action, name=None)
Some actions are best if they’re made available to any object in the admin site – the export action defined above would be a good candidate. You can make an action globally available using AdminSite.add_action(). For example: from django.contrib import admin

admin.site.add_action(export_selected_objects)
 This makes the export_selected_objects action globally available as an action named “export_selected_objects”. You can explicitly give the action a name – good if you later want to programmatically remove the action – by passing a second argument to AdminSite.add_action(): admin.site.add_action(export_selected_objects, 'export_selected')


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


AdminSite.disable_action(name)
If you need to disable a site-wide action you can call AdminSite.disable_action(). For example, you can use this method to remove the built-in “delete selected objects” action: admin.site.disable_action('delete_selected')
 Once you’ve done the above, that action will no longer be available site-wide. If, however, you need to re-enable a globally-disabled action for one particular model, list it explicitly in your ModelAdmin.actions list: # Globally disable delete selected
admin.site.disable_action('delete_selected')

# This ModelAdmin will not have delete_selected available
class SomeModelAdmin(admin.ModelAdmin):
    actions = ['some_other_action']
    ...

# This one will
class AnotherModelAdmin(admin.ModelAdmin):
    actions = ['delete_selected', 'a_third_action']
    ...


AdminSite.each_context(request)
Returns a dictionary of variables to put in the template context for every 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 the list 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 of the module’s index page is permitted for the current user
models: a list of the models available in the application  Each model is a dict with the following keys:
model: the model class
object_name: class name of the model
name: plural name of the model
perms: a dict tracking add, change, delete, and view permissions
admin_url: admin changelist URL for the model
add_url: admin URL to add a new model instance     Changed in Django 4.0: The model variable for each model was added.


AdminSite.empty_value_display
The string to use for displaying empty values in the admin site’s change list. Defaults to a dash. The value can also be overridden on a per ModelAdmin basis and on a custom field within a ModelAdmin by setting an empty_value_display attribute on the field. See ModelAdmin.empty_value_display for examples.


AdminSite.enable_nav_sidebar
A boolean value that determines whether to show the navigation sidebar on larger screens. By default, it is set to True.


AdminSite.final_catch_all_view
 New in Django 3.2.  A boolean value that determines whether to add a final catch-all view to the admin that redirects unauthenticated users to the login page. By default, it is set to True.  Warning Setting this to False is not recommended as the view protects against a potential model enumeration privacy issue.


AdminSite.has_permission(request)
Returns True if the user for the given HttpRequest has permission to view at least one page in the admin site. Defaults to requiring both User.is_active and User.is_staff to be True.


AdminSite.index_template
Path to a custom template that will be used by the admin site main index view.


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


AdminSite.login_form
Subclass of AuthenticationForm that will be used by the admin site login view.


AdminSite.login_template
Path to a custom template that will 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_done_template
Path to a custom template that will be used by the admin site password change done view.


AdminSite.password_change_template
Path to a custom template that will be used by the admin site password change view.


AdminSite.register(model_or_iterable, admin_class=None, **options)
Registers the given model class (or iterable of classes) with the given admin_class. admin_class defaults to ModelAdmin (the default admin options). If keyword arguments are given – e.g. list_display – they’ll be applied as options to the admin class. Raises ImproperlyConfigured if a model is abstract. and django.contrib.admin.sites.AlreadyRegistered if a model is already registered.


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). By default, 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 if the current request has request.META['SCRIPT_NAME'] set and uses that value if site_url isn’t set to something other than /.


AdminSite.unregister(model_or_iterable)
Unregisters the given model class (or iterable of classes). Raises django.contrib.admin.sites.NotRegistered if a model isn’t already registered.


class apps.AdminConfig
This is the default AppConfig class for the admin. It calls autodiscover() when Django starts.


class apps.SimpleAdminConfig
This class works like AdminConfig, except it doesn’t call autodiscover().
default_site
A dotted import path to the default admin site’s class or to a callable that returns a site instance. Defaults to 'django.contrib.admin.sites.AdminSite'. See Overriding the default admin site for usage.


default_site
A dotted import path to the default admin site’s class or to a callable that returns a site instance. Defaults to 'django.contrib.admin.sites.AdminSite'. See Overriding the default admin site for usage.


autodiscover()
This function attempts to import an admin module in each installed application. Such modules are expected to register models with the admin. Typically you won’t need to call this function directly as AdminConfig calls it when Django starts.


display(*, boolean=None, ordering=None, description=None, empty_value=None)
 New in Django 3.2.  This decorator can be used for setting specific attributes on custom display functions that can be used with list_display or readonly_fields: @admin.display(
    boolean=True,
    ordering='-publish_date',
    description='Is Published?',
)
def is_published(self, obj):
    return obj.publish_date is not None
 This is equivalent to setting some attributes (with the original, longer names) on the function directly: def is_published(self, obj):
    return obj.publish_date is not None
is_published.boolean = True
is_published.admin_order_field = '-publish_date'
is_published.short_description = 'Is Published?'
 Also note that the empty_value decorator parameter maps to the empty_value_display attribute assigned directly to the function. It cannot be used in conjunction with boolean – they are mutually exclusive. Use of this decorator is not compulsory to make a display function, but it can be useful to use it without arguments as a marker in your source to identify the purpose of the function: @admin.display
def published_year(self, obj):
    return obj.publish_date.year
 In this case it will add no attributes to the function.


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


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


InlineModelAdmin.extra
This controls the number of extra forms the formset will display in addition to the initial forms. Defaults to 3. See the formsets documentation for more information. For users with JavaScript-enabled browsers, an “Add another” link is provided to enable any number of additional inlines to be added in addition to those provided as a result of the extra argument. The dynamic link will not appear if the number of currently displayed forms exceeds max_num, or if the user does not have JavaScript enabled. InlineModelAdmin.get_extra() also allows you to customize the number of extra forms.


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


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


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


InlineModelAdmin.get_extra(request, obj=None, **kwargs)
Returns the number of extra inline forms to use. By default, returns the InlineModelAdmin.extra attribute. Override this method to programmatically determine the number of extra inline forms. For example, this may be based on the model instance (passed as the keyword argument obj): class BinaryTreeAdmin(admin.TabularInline):
    model = BinaryTree

    def get_extra(self, request, obj=None, **kwargs):
        extra = 2
        if obj:
            return extra - obj.binarytree_set.count()
        return extra


InlineModelAdmin.get_formset(request, obj=None, **kwargs)
Returns a BaseInlineFormSet class for use in admin add/change views. obj is the parent object being edited or None when adding a new parent. See the example for ModelAdmin.get_formsets_with_inlines.


InlineModelAdmin.get_max_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 of inline forms. For example, this may be based on the model instance (passed as the keyword argument obj): class BinaryTreeAdmin(admin.TabularInline):
    model = BinaryTree

    def get_max_num(self, request, obj=None, **kwargs):
        max_num = 10
        if obj and obj.parent:
            return max_num - 5
        return max_num


InlineModelAdmin.get_min_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 of inline forms. For example, this may be based on the model instance (passed as the keyword argument obj).


InlineModelAdmin.has_add_permission(request, obj)
Should return True if adding an inline object is permitted, False otherwise. obj is the parent object being edited or None when adding a new parent.


InlineModelAdmin.has_change_permission(request, obj=None)
Should return True if editing an inline object is permitted, False otherwise. obj is the parent object being edited.


InlineModelAdmin.has_delete_permission(request, obj=None)
Should return True if deleting an inline object is permitted, False otherwise. obj is the parent object being edited.


InlineModelAdmin.max_num
This controls the maximum number of forms to show in the inline. This doesn’t directly correlate to the number of objects, but can if the value is small enough. See Limiting the number of editable objects for more information. InlineModelAdmin.get_max_num() also allows you to customize the maximum number of extra forms.


InlineModelAdmin.min_num
This controls the minimum number of forms to show in the inline. See modelformset_factory() for more information. InlineModelAdmin.get_min_num() also allows you to customize the minimum number of displayed forms.


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


InlineModelAdmin.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_fields is a list of fields you would like to change into an Input widget for either a ForeignKey or ManyToManyField: class BookInline(admin.TabularInline):
    model = Book
    raw_id_fields = ("pages",)


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


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


InlineModelAdmin.verbose_name
An override to the verbose_name from the model’s inner Meta class.


InlineModelAdmin.verbose_name_plural
An override to the verbose_name_plural from the model’s inner Meta class. If this isn’t given and the InlineModelAdmin.verbose_name is defined, Django will use InlineModelAdmin.verbose_name + 's'.  Changed in Django 4.0: The fallback to InlineModelAdmin.verbose_name was added.


class ModelAdmin
The ModelAdmin class is the representation of a model in the admin interface. Usually, these are stored in a file named admin.py in your application. Let’s take a look at an example of the ModelAdmin: from django.contrib import admin
from myapp.models import Author

class AuthorAdmin(admin.ModelAdmin):
    pass
admin.site.register(Author, AuthorAdmin)
  Do you need a ModelAdmin object at all? In the preceding example, the ModelAdmin class doesn’t define any custom values (yet). As a result, the default admin interface will be provided. If you are happy with the default admin interface, you don’t need to define a ModelAdmin object at all – you can register the model class without providing a ModelAdmin description. The preceding example could be simplified to: from django.contrib import admin
from myapp.models import Author

admin.site.register(Author)


ModelAdmin.actions
A list of actions to make available on the change list page. See Admin actions for details.


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.add_form_template
Path to a custom template, used by add_view().


ModelAdmin.add_view(request, form_url='', extra_context=None)
Django view for the model instance addition page. See note below.


ModelAdmin.autocomplete_fields
autocomplete_fields is a list of ForeignKey and/or ManyToManyField fields 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_fields on the related object’s ModelAdmin because the autocomplete search uses it. To avoid unauthorized data disclosure, users must have the view or change permission to the related object in order to use autocomplete. Ordering and pagination of the results are controlled by the related ModelAdmin’s get_ordering() and get_paginator() methods. In the following example, ChoiceAdmin has an autocomplete field for the ForeignKey to the Question. The results are filtered by the question_text field and ordered by the date_created field: 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.ordering may 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 Paginator on very large tables as the default paginator always performs a count() query. For example, you could override the default implementation of the Paginator.count property.


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.change_view(request, object_id, form_url='', extra_context=None)
Django view for the model instance editing page. See note below.


ModelAdmin.changelist_view(request, extra_context=None)
Django view for the model instances change list/actions page. See note below.


ModelAdmin.date_hierarchy
Set date_hierarchy to the name of a DateField or DateTimeField in your model, and the change list page will include a date-based drilldown navigation by that field. Example: date_hierarchy = 'pub_date'
 You can also specify a field on a related model using the __ lookup, for example: date_hierarchy = 'author__pub_date'
 This will intelligently populate itself based on available data, e.g. if all the dates are in one month, it’ll show the day-level drill-down only.  Note date_hierarchy uses QuerySet.datetimes() internally. Please refer to its documentation for some caveats when time zone support is enabled (USE_TZ = True).


ModelAdmin.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_model(request, obj)
The delete_model method is given the HttpRequest and a model instance. Overriding this method allows doing pre- or post-delete operations. Call super().delete_model() to delete the object using Model.delete().


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


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


ModelAdmin.delete_view(request, object_id, extra_context=None)
Django view for the model instance(s) deletion confirmation page. See note below.


ModelAdmin.empty_value_display
This attribute overrides the default display value for record’s fields that are empty (None, empty string, etc.). The default value is - (a dash). For example: from django.contrib import admin

class AuthorAdmin(admin.ModelAdmin):
    empty_value_display = '-empty-'
 You can also override empty_value_display for all admin pages with AdminSite.empty_value_display, or for specific fields like this: from django.contrib import admin

class AuthorAdmin(admin.ModelAdmin):
    fields = ('name', 'title', 'view_birth_date')

    @admin.display(empty_value='???')
    def view_birth_date(self, obj):
        return obj.birth_date
  Changed in Django 3.2: The empty_value argument to the display() decorator is equivalent to setting the empty_value_display attribute on the display function directly in previous versions. Setting the attribute directly is still supported for backward compatibility.


ModelAdmin.exclude
This attribute, if given, should be a list of field names to exclude from the form. For example, let’s consider the following model: from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=100)
    title = models.CharField(max_length=3)
    birth_date = models.DateField(blank=True, null=True)
 If you want a form for the Author model that includes only the name and title fields, you would specify fields or exclude like this: from django.contrib import admin

class AuthorAdmin(admin.ModelAdmin):
    fields = ('name', 'title')

class AuthorAdmin(admin.ModelAdmin):
    exclude = ('birth_date',)
 Since the Author model only has three fields, name, title, and birth_date, the forms resulting from the above declarations will contain exactly the same fields.


ModelAdmin.fields
Use the fields option to make simple layout changes in the forms on the “add” and “change” pages such as showing only a subset of available fields, modifying their order, or grouping them into rows. For example, you could define a simpler version of the admin form for the django.contrib.flatpages.models.FlatPage model as follows: class FlatPageAdmin(admin.ModelAdmin):
    fields = ('url', 'title', 'content')
 In the above example, only the fields url, title and content will be displayed, sequentially, in the form. fields can contain values defined in ModelAdmin.readonly_fields to be displayed as read-only. For more complex layout needs, see the fieldsets option. The fields option accepts the same types of values as list_display, except that callables aren’t accepted. Names of model and model admin methods will only be used if they’re listed in readonly_fields. To display multiple fields on the same line, wrap those fields in their own tuple. In this example, the url and title fields will display on the same line and the content field will be displayed below them on its own line: class FlatPageAdmin(admin.ModelAdmin):
    fields = (('url', 'title'), 'content')
  Note This fields option should not be confused with the fields dictionary key that is within the fieldsets option, as described in the next section.  If neither fields nor fieldsets options are present, Django will default to displaying each field that isn’t an AutoField and has editable=True, in a single fieldset, in the same order as the fields are defined in the model.


ModelAdmin.fieldsets
Set fieldsets to control the layout of admin “add” and “change” pages. fieldsets is a list of two-tuples, in which each two-tuple represents a <fieldset> on the admin form page. (A <fieldset> is a “section” of the form.) The two-tuples are in the format (name, field_options), where name is a string representing the title of the fieldset and field_options is a dictionary of information about the fieldset, including a list of fields to be displayed in it. A full example, taken from the django.contrib.flatpages.models.FlatPage model: from django.contrib import admin

class FlatPageAdmin(admin.ModelAdmin):
    fieldsets = (
        (None, {
            'fields': ('url', 'title', 'content', 'sites')
        }),
        ('Advanced options', {
            'classes': ('collapse',),
            'fields': ('registration_required', 'template_name'),
        }),
    )
 This results in an admin page that looks like:  If neither fieldsets nor fields options are present, Django will default to displaying each field that isn’t an AutoField and has editable=True, in a single fieldset, in the same order as the fields are defined in the model. The field_options dictionary can have the following keys:

fields
A tuple of field names to display in this fieldset. This key is required. Example: {
'fields': ('first_name', 'last_name', 'address', 'city', 'state'),
}
 As with the fields option, to display multiple fields on the same line, wrap those fields in their own tuple. In this example, the first_name and last_name fields will display on the same line: {
'fields': (('first_name', 'last_name'), 'address', 'city', 'state'),
}
 fields can contain values defined in readonly_fields to be displayed as read-only. If you add the name of a callable to fields, the same rule applies as with the fields option: the callable must be listed in readonly_fields.

classes
A list or tuple containing extra CSS classes to apply to the fieldset. Example: {
'classes': ('wide', 'extrapretty'),
}
 Two useful classes defined by the default admin site stylesheet are collapse and wide. Fieldsets with the collapse style will be initially collapsed in the admin and replaced with a small “click to expand” link. Fieldsets with the wide style will be given extra horizontal space.

description
A string of optional extra text to be displayed at the top of each fieldset, under the heading of the fieldset. This string is not rendered for TabularInline due to its layout. Note that this value is not HTML-escaped when it’s displayed in the admin interface. This lets you include HTML if you so desire. Alternatively you can use plain text and django.utils.html.escape() to escape any HTML special characters.


ModelAdmin.filter_horizontal
By default, a ManyToManyField is displayed in the admin site with a <select multiple>. However, multiple-select boxes can be difficult to use when selecting many items. Adding a ManyToManyField to this list will instead use a nifty unobtrusive JavaScript “filter” interface that allows searching within the options. The unselected and selected options appear in two boxes side by side. See filter_vertical to use a vertical interface.


ModelAdmin.filter_vertical
Same as filter_horizontal, but uses a vertical display of the filter interface with the box of unselected options appearing above the box of selected options.


ModelAdmin.form
By default a ModelForm is dynamically created for your model. It is used to create the form presented on both the add/change pages. You can easily provide your own ModelForm to override any default form behavior on the add/change pages. Alternatively, you can customize the default form rather than specifying an entirely new one by using the ModelAdmin.get_form() method. For an example see the section Adding custom validation to the admin.  Note If you define the Meta.model attribute on a ModelForm, you must also define the Meta.fields attribute (or the Meta.exclude attribute). However, since the admin has its own way of defining fields, the Meta.fields attribute will be ignored. If the ModelForm is only going to be used for the admin, the easiest solution is to omit the Meta.model attribute, since ModelAdmin will provide the correct model to use. Alternatively, you can set fields = [] in the Meta class to satisfy the validation on the ModelForm.   Note If your ModelForm and ModelAdmin both define an exclude option then ModelAdmin takes precedence: from django import forms
from django.contrib import admin
from myapp.models import Person

class PersonForm(forms.ModelForm):

    class Meta:
        model = Person
        exclude = ['name']

class PersonAdmin(admin.ModelAdmin):
    exclude = ['age']
    form = PersonForm
 In the above example, the “age” field will be excluded but the “name” field will be included in the generated form.


ModelAdmin.formfield_for_choice_field(db_field, request, **kwargs)
Like the formfield_for_foreignkey and formfield_for_manytomany methods, the formfield_for_choice_field method can be overridden to change the default formfield for a field that has declared choices. For example, if the choices available to a superuser should be different than those available to regular staff, you could proceed as follows: class MyModelAdmin(admin.ModelAdmin):
    def formfield_for_choice_field(self, db_field, request, **kwargs):
        if db_field.name == "status":
            kwargs['choices'] = (
                ('accepted', 'Accepted'),
                ('denied', 'Denied'),
            )
            if request.user.is_superuser:
                kwargs['choices'] += (('ready', 'Ready for deployment'),)
        return super().formfield_for_choice_field(db_field, request, **kwargs)
  Note Any choices attribute set on the formfield will be limited to the form field only. If the corresponding field on the model has choices set, the choices provided to the form must be a valid subset of those choices, otherwise the form submission will fail with a ValidationError when the model itself is validated before saving.


ModelAdmin.formfield_for_foreignkey(db_field, request, **kwargs)
The formfield_for_foreignkey method on a ModelAdmin allows you to override the default formfield for a foreign keys field. For example, to return a subset of objects for this foreign key field based on the user: class MyModelAdmin(admin.ModelAdmin):
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == "car":
            kwargs["queryset"] = Car.objects.filter(owner=request.user)
        return super().formfield_for_foreignkey(db_field, request, **kwargs)
 This uses the HttpRequest instance to filter the Car foreign key field to only display the cars owned by the User instance. For more complex filters, you can use ModelForm.__init__() method to filter based on an instance of your model (see Fields which handle relationships). For example: class CountryAdminForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['capital'].queryset = self.instance.cities.all()

class CountryAdmin(admin.ModelAdmin):
    form = CountryAdminForm


ModelAdmin.formfield_for_manytomany(db_field, request, **kwargs)
Like the formfield_for_foreignkey method, the formfield_for_manytomany method can be overridden to change the default formfield for a many to many field. For example, if an owner can own multiple cars and cars can belong to multiple owners – a many to many relationship – you could filter the Car foreign key field to only display the cars owned by the User: class MyModelAdmin(admin.ModelAdmin):
    def formfield_for_manytomany(self, db_field, request, **kwargs):
        if db_field.name == "cars":
            kwargs["queryset"] = Car.objects.filter(owner=request.user)
        return super().formfield_for_manytomany(db_field, request, **kwargs)


ModelAdmin.formfield_overrides
This provides a quick-and-dirty way to override some of the Field options for use in the admin. formfield_overrides is a dictionary mapping a field class to a dict of arguments to pass to the field at construction time. Since that’s a bit abstract, let’s look at a concrete example. The most common use of formfield_overrides is to add a custom widget for a certain type of field. So, imagine we’ve written a RichTextEditorWidget that we’d like to use for large text fields instead of the default <textarea>. Here’s how we’d do that: from django.contrib import admin
from django.db import models

# 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.  Warning If you want to use a custom widget with a relation field (i.e. ForeignKey or ManyToManyField), make sure you haven’t included that field’s name in raw_id_fields, radio_fields, or autocomplete_fields. formfield_overrides won’t let you change the widget on relation fields that have raw_id_fields, radio_fields, or autocomplete_fields set. That’s because raw_id_fields, radio_fields, and autocomplete_fields imply custom widgets of their own.


ModelAdmin.get_actions(request)
Finally, you can conditionally enable or disable actions on a per-request (and hence per-user basis) by overriding ModelAdmin.get_actions(). This returns a dictionary of actions allowed. The keys are action names, and the values are (function, name, short_description) tuples. For example, if you only want users whose names begin with ‘J’ to be able to delete objects in bulk: class MyModelAdmin(admin.ModelAdmin):
    ...

    def get_actions(self, request):
        actions = super().get_actions(request)
        if request.user.username[0].upper() != 'J':
            if 'delete_selected' in actions:
                del actions['delete_selected']
        return actions


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


ModelAdmin.get_changeform_initial_data(request)
A hook for the initial data on admin change forms. By default, fields are given initial values from GET parameters. For instance, ?name=initial_value will set the name field’s initial value to be initial_value. This method should return a dictionary in the form {'fieldname': 'fieldval'}: def get_changeform_initial_data(self, request):
    return {'name': 'custom_initial_value'}


ModelAdmin.get_changelist(request, **kwargs)
Returns the Changelist class to be used for listing. By default, django.contrib.admin.views.main.ChangeList is used. By inheriting this class you can change the behavior of the listing.


ModelAdmin.get_changelist_form(request, **kwargs)
Returns a ModelForm class for use in the Formset on the changelist page. To use a custom form, for example: from django import forms

class MyForm(forms.ModelForm):
    pass

class MyModelAdmin(admin.ModelAdmin):
    def get_changelist_form(self, request, **kwargs):
        return MyForm
  Note If you define the Meta.model attribute on a ModelForm, you must also define the Meta.fields attribute (or the Meta.exclude attribute). However, ModelAdmin ignores this value, overriding it with the ModelAdmin.list_editable attribute. The easiest solution is to omit the Meta.model attribute, since ModelAdmin will provide the correct model to use.


ModelAdmin.get_changelist_formset(request, **kwargs)
Returns a ModelFormSet class for use on the changelist page if list_editable is used. To use a custom formset, for example: from django.forms import BaseModelFormSet

class MyAdminFormSet(BaseModelFormSet):
    pass

class MyModelAdmin(admin.ModelAdmin):
    def get_changelist_formset(self, request, **kwargs):
        kwargs['formset'] = MyAdminFormSet
        return super().get_changelist_formset(request, **kwargs)


ModelAdmin.get_deleted_objects(objs, request)
A hook for customizing the deletion process of the delete_view() and the “delete selected” action. The objs argument is a homogeneous iterable of objects (a QuerySet or a list of model instances) to be deleted, and request is the HttpRequest. This method must return a 4-tuple of (deleted_objects, model_count, perms_needed, protected). deleted_objects is a list of strings representing all the objects that will be deleted. If there are any related objects to be deleted, the list is nested and includes those related objects. The list is formatted in the template using the unordered_list filter. model_count is a dictionary mapping each model’s verbose_name_plural to the number of objects that will be deleted. perms_needed is a set of verbose_names of the models that the user doesn’t have permission to delete. protected is a list of strings representing of all the protected related objects that can’t be deleted. The list is displayed in the template.


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


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


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


ModelAdmin.get_form(request, obj=None, **kwargs)
Returns a ModelForm class for use in the admin add and change views, see add_view() and change_view(). The base implementation uses modelform_factory() to subclass form, modified by attributes such as fields and exclude. So, for example, if you wanted to offer additional fields to superusers, you could swap in a different base form like so: class MyModelAdmin(admin.ModelAdmin):
    def get_form(self, request, obj=None, **kwargs):
        if request.user.is_superuser:
            kwargs['form'] = MySuperuserForm
        return super().get_form(request, obj, **kwargs)
 You may also return a custom ModelForm class directly.


ModelAdmin.get_formset_kwargs(request, obj, inline, prefix)
 New in Django 4.0.  A hook for customizing the keyword arguments passed to the constructor of a formset. For example, to pass request to formset forms: class MyModelAdmin(admin.ModelAdmin):
    def get_formset_kwargs(self, request, obj, inline, prefix):
        return {
            **super().get_formset_kwargs(request, obj, inline, prefix),
            'form_kwargs': {'request': request},
        }
 You can also used it to set initial for formset forms.


ModelAdmin.get_formsets_with_inlines(request, obj=None)
Yields (FormSet, InlineModelAdmin) pairs for use in admin add and change views. For example if you wanted to display a particular inline only in the change view, you could override get_formsets_with_inlines as follows: class MyModelAdmin(admin.ModelAdmin):
    inlines = [MyInline, SomeOtherInline]

    def get_formsets_with_inlines(self, request, obj=None):
        for inline in self.get_inline_instances(request, obj):
            # hide MyInline in the add view
            if not isinstance(inline, MyInline) or obj is not None:
                yield inline.get_formset(request, obj), inline


ModelAdmin.get_inline_instances(request, obj=None)
The get_inline_instances method is given the HttpRequest and the obj being edited (or None on an add form) and is expected to return a list or tuple of InlineModelAdmin objects, as described below in the InlineModelAdmin section. For example, the following would return inlines without the default filtering based on add, change, delete, and view permissions: 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 inlines or you might encounter a “Bad Request” error when adding related objects.


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


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


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


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


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


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

    def get_ordering(self, request):
        if request.user.is_superuser:
            return ['name', 'rank']
        else:
            return ['name']


ModelAdmin.get_paginator(request, queryset, per_page, orphans=0, allow_empty_first_page=True)
Returns an instance of the paginator to use for this view. By default, instantiates an instance of paginator.


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


ModelAdmin.get_queryset(request)
The get_queryset method on a ModelAdmin returns a QuerySet of all model instances that can be edited by the admin site. One use case for overriding this method is to show objects owned by the logged-in user: class MyModelAdmin(admin.ModelAdmin):
    def get_queryset(self, request):
        qs = super().get_queryset(request)
        if request.user.is_superuser:
            return qs
        return qs.filter(author=request.user)


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


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


ModelAdmin.get_search_results(request, queryset, search_term)
The get_search_results method modifies the list of objects displayed into those that match the provided search term. It accepts the request, a queryset that applies the current filters, and the user-provided search term. It returns a tuple containing a queryset modified to implement the search, and a boolean indicating if the results may contain duplicates. The default implementation searches the fields named in ModelAdmin.search_fields. This method may be overridden with your own custom search method. For example, you might wish to search by an integer field, or use an external tool such as Solr or Haystack. You must establish if the queryset changes implemented by your search method may introduce duplicates into the results, and return True in the second element of the return value. For example, to search by name and age, you could use: 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.


ModelAdmin.get_sortable_by(request)
The get_sortable_by() method is passed the HttpRequest and is expected to return a collection (e.g. list, tuple, or set) of field names that will be sortable in the change list page. Its default implementation returns sortable_by if it’s set, otherwise it defers to get_list_display(). For example, to prevent one or more columns from being sortable: class PersonAdmin(admin.ModelAdmin):

    def get_sortable_by(self, request):
        return {*self.get_list_display(request)} - {'rank'}


ModelAdmin.get_urls()
The get_urls method on a ModelAdmin returns the URLs to be used for that ModelAdmin in the same way as a URLconf. Therefore you can extend them as documented in URL dispatcher: from django.contrib import admin
from django.template.response import TemplateResponse
from django.urls import path

class MyModelAdmin(admin.ModelAdmin):
    def get_urls(self):
        urls = super().get_urls()
        my_urls = [
            path('my_view/', self.my_view),
        ]
        return my_urls + urls

    def my_view(self, request):
        # ...
        context = dict(
           # Include common variables for rendering the admin template.
           self.admin_site.each_context(request),
           # Anything else you want in the context...
           key=value,
        )
        return TemplateResponse(request, "sometemplate.html", context)
 If you want to use the admin layout, extend from admin/base_site.html: {% extends "admin/base_site.html" %}
{% block content %}
...
{% endblock %}
  Note Notice that the custom patterns are included before the regular admin URLs: the admin URL patterns are very permissive and will match nearly anything, so you’ll usually want to prepend your custom URLs to the built-in ones. In this example, my_view will be accessed at /admin/myapp/mymodel/my_view/ (assuming the admin URLs are included at /admin/.)  However, the self.my_view function registered above suffers from two problems:  It will not perform any permission checks, so it will be accessible to the general public. It will not provide any header details to prevent caching. This means if the page retrieves data from the database, and caching middleware is active, the page could show outdated information.  Since this is usually not what you want, Django provides a convenience wrapper to check permissions and mark the view as non-cacheable. This wrapper is AdminSite.admin_view() (i.e. self.admin_site.admin_view inside a ModelAdmin instance); use it like so: class MyModelAdmin(admin.ModelAdmin):
    def get_urls(self):
        urls = super().get_urls()
        my_urls = [
            path('my_view/', self.admin_site.admin_view(self.my_view))
        ]
        return my_urls + urls
 Notice the wrapped view in the fifth line above: path('my_view/', self.admin_site.admin_view(self.my_view))
 This wrapping will protect self.my_view from unauthorized access and will apply the django.views.decorators.cache.never_cache() decorator to make sure it is not cached if the cache middleware is active. If the page is cacheable, but you still want the permission check to be performed, you can pass a cacheable=True argument to AdminSite.admin_view(): path('my_view/', self.admin_site.admin_view(self.my_view, cacheable=True))
 ModelAdmin views have model_admin attributes. Other AdminSite views have admin_site attributes.


ModelAdmin.has_add_permission(request)
Should return True if adding an object is permitted, False otherwise.


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


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


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


ModelAdmin.has_view_permission(request, obj=None)
Should return True if viewing obj is permitted, False otherwise. If obj is None, should return True or False to indicate whether viewing of objects of this type is permitted in general (e.g., False will be interpreted as meaning that the current user is not permitted to view any object of this type). The default implementation returns True if the user has either the “change” or “view” permission.


ModelAdmin.history_view(request, object_id, extra_context=None)
Django view for the page that shows the modification history for a given model instance.


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


ModelAdmin.list_display
Set list_display to control which fields are displayed on the change list page of the admin. 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 four types of values that can be used in list_display. All but the simplest may use the display() decorator 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')

A callable that accepts one argument, the model instance. For example: @admin.display(description='Name')
def upper_case_name(obj):
    return ("%s %s" % (obj.first_name, obj.last_name)).upper()

class PersonAdmin(admin.ModelAdmin):
    list_display = (upper_case_name,)

A string representing a ModelAdmin method 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 ("%s %s" % (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):
        return '%d’s' % (self.birthday.year // 10 * 10)

class PersonAdmin(admin.ModelAdmin):
    list_display = ('name', 'decade_born_in')
   A few special cases to note about list_display:  If the field is a ForeignKey, Django will display the __str__() of the related object.
ManyToManyField fields aren’t supported, because that would entail executing a separate SQL statement for each row in the table. If you want to do this nonetheless, give your model a custom method, and add that method’s name to list_display. (See below for more on custom methods in list_display.)  If the field is a BooleanField, Django will display a pretty “yes”, “no”, or “unknown” icon instead of True, False, or None.
If the string given is a method of the model, ModelAdmin or a callable, Django will HTML-escape the output by default. To escape user input and allow your own unescaped tags, use format_html(). Here’s a full example model: 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(
            '{} {}',
            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 ModelAdmin method, you can customize the column’s title by wrapping the callable with the display() decorator and passing the description argument.  Changed in Django 3.2: The description argument to the display() decorator is equivalent to setting the short_description attribute on the display function directly in previous versions. Setting the attribute directly is still supported for backward compatibility.
If the value of a field is None, an empty string, or an iterable without elements, Django will display - (a dash). You can override this with AdminSite.empty_value_display: 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
  Changed in Django 3.2: The empty_value argument to the display() decorator is equivalent to setting the empty_value_display attribute on the display function directly in previous versions. Setting the attribute directly is still supported for backward compatibility.
If the string given is a method of the model, ModelAdmin or a callable that returns True, False, or None, Django will display a pretty “yes”, “no”, or “unknown” icon if you wrap the method with the display() decorator passing the boolean argument with the value set to True: 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')
  Changed in Django 3.2: The boolean argument to the display() decorator is equivalent to setting the boolean attribute on the display function directly in previous versions. Setting the attribute directly is still supported for backward compatibility.
The __str__() method is just as valid in list_display as any other model method, so it’s perfectly OK to do this: list_display = ('__str__', 'some_other_field')

Usually, elements of list_display that aren’t actual database fields can’t be used in sorting (because Django does all the sorting at the database level). However, if an element of list_display represents a certain database field, you can indicate this fact by using the display() decorator on the method, passing the ordering argument: 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(
            '{}',
            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_name field when trying to sort by colored_first_name in the admin. To indicate descending order with the ordering argument you can use a hyphen prefix on the field name. Using the above example, this would look like: @admin.display(ordering='-first_name')
 The ordering argument 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 ordering argument: 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
  Changed in Django 3.2: The ordering argument to the display() decorator is equivalent to setting the admin_order_field attribute on the display function directly in previous versions. Setting the attribute directly is still supported for backward compatibility.
Elements of list_display can also be properties: class 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',
    )
    def full_name(self):
        return self.first_name + ' ' + self.last_name

class PersonAdmin(admin.ModelAdmin):
    list_display = ('full_name',)
 Note that @property must be above @display. If you’re using the old way – setting the display-related attributes directly rather than using the display() decorator – be aware that the property() function and not the @property decorator 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'

full_name = property(my_property)
  The field names in list_display will also appear as CSS classes in the HTML output, in the form of column-<field_name> on each  element. This can be used to set column widths in a CSS file for example.
Django will try to interpret every element of list_display in this order:  A field of the model. A callable. A string representing a ModelAdmin attribute. A string representing a model attribute.  For example if you have first_name as a model field and as a ModelAdmin attribute, the model field will be used.


ModelAdmin.list_display_links
Use list_display_links to control if and which fields in list_display should be linked to the “change” page for an object. By default, the change list page will link the first column – the first field specified in list_display – to the change page for each item. But list_display_links lets you change this:  Set it to None to get no links at all.
Set it to a list or tuple of fields (in the same format as list_display) whose columns you want converted to links. You can specify one or many fields. As long as the fields appear in list_display, Django doesn’t care how many (or how few) fields are linked. The only requirement is that if you want to use list_display_links in this fashion, you must define list_display.   In this example, the first_name and last_name fields will be linked on the change list page: 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_editable to a list of field names on the model which will allow editing on the change list page. That is, fields listed in list_editable will be displayed as form widgets on the change list page, allowing users to edit and save multiple rows at once.  Note list_editable interacts with a couple of other options in particular ways; you should note the following rules:  Any field in list_editable must also be in list_display. You can’t edit a field that’s not displayed! The same field can’t be listed in both list_editable and list_display_links – a field can’t be both a form and a link.  You’ll get a validation error if either of these rules are broken.


ModelAdmin.list_filter
Set list_filter to activate filters in the right sidebar of the change list page of the admin, as illustrated in the following screenshot:  list_filter should be a list or tuple of elements, where each element should be of one of the following types:
a field name, where the specified field should be either a BooleanField, CharField, DateField, DateTimeField, IntegerField, ForeignKey or ManyToManyField, for example: class PersonAdmin(admin.ModelAdmin):
    list_filter = ('is_staff', 'company')
 Field names in list_filter can also span relations using the __ lookup, for example: class PersonAdmin(admin.UserAdmin):
    list_filter = ('company__name',)

a class inheriting from django.contrib.admin.SimpleListFilter, which you need to provide the title and parameter_name attributes to and override the lookups and queryset methods, e.g.: from datetime import date

from django.contrib import admin
from django.utils.translation import gettext_lazy as _

class DecadeBornListFilter(admin.SimpleListFilter):
    # Human-readable title which will be displayed in the
    # right admin sidebar just above the filter options.
    title = _('decade born')

    # Parameter for the filter that will be used in the URL query.
    parameter_name = 'decade'

    def lookups(self, request, model_admin):
        """
        Returns a list of tuples. The first element in each
        tuple is the coded value for the option that will
        appear in the URL query. The second element is the
        human-readable name for the option that will appear
        in the right sidebar.
        """
        return (
            ('80s', _('in the eighties')),
            ('90s', _('in the nineties')),
        )

    def queryset(self, request, queryset):
        """
        Returns the filtered queryset based on the value
        provided in the query string and retrievable via
        `self.value()`.
        """
        # Compare the requested value (either '80s' or '90s')
        # to decide how to filter the queryset.
        if self.value() == '80s':
            return queryset.filter(birthday__gte=date(1980, 1, 1),
                                    birthday__lte=date(1989, 12, 31))
        if self.value() == '90s':
            return queryset.filter(birthday__gte=date(1990, 1, 1),
                                    birthday__lte=date(1999, 12, 31))

class PersonAdmin(admin.ModelAdmin):
    list_filter = (DecadeBornListFilter,)
  Note As a convenience, the HttpRequest object is passed to the lookups and queryset methods, for example: class AuthDecadeBornListFilter(DecadeBornListFilter):

    def lookups(self, request, model_admin):
        if request.user.is_superuser:
            return super().lookups(request, model_admin)

    def queryset(self, request, queryset):
        if request.user.is_superuser:
            return super().queryset(request, queryset)
 Also as a convenience, the ModelAdmin object is passed to the lookups method, for example if you want to base the lookups on the available data: class AdvancedDecadeBornListFilter(DecadeBornListFilter):

    def lookups(self, request, model_admin):
        """
        Only show the lookups if there actually is
        anyone born in the corresponding decades.
        """
        qs = model_admin.get_queryset(request)
        if qs.filter(birthday__gte=date(1980, 1, 1),
                      birthday__lte=date(1989, 12, 31)).exists():
            yield ('80s', _('in the eighties'))
        if qs.filter(birthday__gte=date(1990, 1, 1),
                      birthday__lte=date(1999, 12, 31)).exists():
            yield ('90s', _('in the nineties'))

a tuple, where the first element is a field name and the second element is a class inheriting from django.contrib.admin.FieldListFilter, for example: class PersonAdmin(admin.ModelAdmin):
    list_filter = (
        ('is_staff', admin.BooleanFieldListFilter),
    )
 You can limit the choices of a related model to the objects involved in that relation using RelatedOnlyFieldListFilter: class BookAdmin(admin.ModelAdmin):
    list_filter = (
        ('author', admin.RelatedOnlyFieldListFilter),
    )
 Assuming author is a ForeignKey to a User model, this will limit the list_filter choices to the users who have written a book instead of listing all users. You can filter empty values using EmptyFieldListFilter, which can filter on both empty strings and nulls, depending on what the field allows to store: class BookAdmin(admin.ModelAdmin):
    list_filter = (
        ('title', admin.EmptyFieldListFilter),
    )
  Note The FieldListFilter API is considered internal and might be changed.   Note The GenericForeignKey field is not supported.    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: class FilterWithCustomTemplate(admin.SimpleListFilter):
    template = "custom_template.html"
 See the default template provided by Django (admin/filter.html) for a concrete example.


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


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


ModelAdmin.list_select_related
Set list_select_related to tell Django to use select_related() in retrieving the list of objects on the admin change list page. This can save you a bunch of database queries. The value should be either a boolean, a list or a tuple. Default is False. When value is True, select_related() will always be called. When value is set to False, Django will look at list_display and call select_related() if any ForeignKey is present. If you need more fine-grained control, use a tuple (or list) as value for list_select_related. Empty tuple will prevent Django from calling select_related at all. Any other tuple will be passed directly to select_related as parameters. For example: 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.  Note ModelAdmin ignores this attribute when select_related() was already called on the changelist’s QuerySet.


ModelAdmin.lookup_allowed(lookup, value)
The objects in the changelist page can be filtered with lookups from the URL’s query string. This is how list_filter works, for example. The lookups are similar to what’s used in QuerySet.filter() (e.g. user__email=user@example.com). Since the lookups in the query string can be manipulated by the user, they must be sanitized to prevent unauthorized data exposure. The lookup_allowed() method is given a lookup path from the query string (e.g. 'user__email') and the corresponding value (e.g. 'user@example.com'), and returns a boolean indicating whether filtering the changelist’s QuerySet using the parameters is permitted. If lookup_allowed() returns False, DisallowedModelAdminLookup (subclass of SuspiciousOperation) is raised. By default, lookup_allowed() allows access to a model’s local fields, field paths used in list_filter (but not paths from get_list_filter()), and lookups required for limit_choices_to to function correctly in raw_id_fields. Override this method to customize the lookups permitted for your ModelAdmin subclass.


ModelAdmin.message_user(request, message, level=messages.INFO, extra_tags='', fail_silently=False)
Sends a message to the user using the django.contrib.messages backend. See the custom ModelAdmin example. Keyword arguments allow you to change the message level, add extra CSS tags, or fail silently if the contrib.messages framework is not installed. These keyword arguments match those for django.contrib.messages.add_message(), see that function’s documentation for more details. One difference is that the level may be passed as a string label in addition to integer/constant.


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


ModelAdmin.ordering
Set ordering to specify how lists of objects should be ordered in the Django admin views. This should be a list or tuple in the same format as a model’s ordering parameter. If this isn’t provided, the Django admin will use the model’s default ordering. If you need to specify a dynamic order (for example depending on user or language) you can implement a get_ordering() method.  Performance considerations with ordering and sorting To ensure a deterministic ordering of results, the changelist adds pk to the ordering if it can’t find a single or unique together set of fields that provide total ordering. For example, if the default ordering is by a non-unique name field, then the changelist is sorted by name and pk. This could perform poorly if you have a lot of rows and don’t have an index on name and pk.


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


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


ModelAdmin.prepopulated_fields
Set prepopulated_fields to 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 SlugField fields from one or more other fields. The generated value is produced by concatenating the values of the source fields, and then by transforming that result into a valid slug (e.g. substituting dashes for spaces 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_fields doesn’t accept DateTimeField, ForeignKey, OneToOneField, and ManyToManyField fields.  Changed in Django 3.2: In older versions, various English stop words are removed from generated values.


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


ModelAdmin.radio_fields
By default, Django’s admin uses a select-box interface (<select>) for fields that are ForeignKey or have choices set. If a field is present in radio_fields, Django will use a radio-button interface instead. Assuming group is a ForeignKey on the Person model: class PersonAdmin(admin.ModelAdmin):
    radio_fields = {"group": admin.VERTICAL}
 You have the choice of using HORIZONTAL or VERTICAL from the django.contrib.admin module. Don’t include a field in radio_fields unless it’s a ForeignKey or has choices set.


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_fields is a list of fields you would like to change into an Input widget for either a ForeignKey or ManyToManyField: class ArticleAdmin(admin.ModelAdmin):
    raw_id_fields = ("newspaper",)
 The raw_id_fields Input widget should contain a primary key if the field is a ForeignKey or a comma separated list of values if the field is a ManyToManyField. The raw_id_fields widget shows a magnifying glass button next to the field which allows users to search for and select a value:


ModelAdmin.readonly_fields
By default the admin shows all fields as editable. Any fields in this option (which should be a list or tuple) will display its data as-is and non-editable; they are also excluded from the ModelForm used for creating and editing. Note that when specifying ModelAdmin.fields or ModelAdmin.fieldsets the read-only fields must be present to be shown (they are ignored otherwise). If readonly_fields is used without defining explicit ordering through ModelAdmin.fields or ModelAdmin.fieldsets they will be added last after all editable fields. A read-only field can not only display data from a model’s field, it can also display the output of a model’s method or a method of the ModelAdmin class itself. This is very similar to the way ModelAdmin.list_display behaves. This provides a way to use the admin interface to provide feedback on the status of the objects being edited, for example: 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('
'),
            '{}',
            ((line,) for line in instance.get_full_address()),
        ) or mark_safe("I can't determine this address.")


ModelAdmin.response_add(request, obj, post_url_continue=None)
Determines the HttpResponse for the add_view() stage. response_add is called after the admin form is submitted and just after the object and all the related instances have been created and saved. You can override it to change the default behavior after the object has been created.


ModelAdmin.response_change(request, obj)
Determines the HttpResponse for the change_view() stage. response_change is called after the admin form is submitted and just after the object and all the related instances have been saved. You can override it to change the default behavior after the object has been changed.


ModelAdmin.response_delete(request, obj_display, obj_id)
Determines the HttpResponse for the delete_view() stage. response_delete is called after the object has been deleted. You can override it to change the default behavior after the object has been deleted. obj_display is a string with the name of the deleted object. obj_id is the serialized identifier used to retrieve the object to be deleted.


ModelAdmin.save_as
Set save_as to enable a “save as new” feature on admin change forms. Normally, objects have three save options: “Save”, “Save and continue editing”, and “Save and add another”. If save_as is True, “Save and add another” will be replaced by a “Save as new” button that creates a new object (with a new ID) rather than updating the existing object. By default, save_as is set to False.


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