doc_content
stringlengths
1
386k
doc_id
stringlengths
5
188
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
flask.config.index#USE_X_SENDFILE
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; }
flask.deploying.uwsgi.index
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.
flask.api.index#flask.views.View
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
flask.api.index#flask.views.View.as_view
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.
flask.api.index#flask.views.View.decorators
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]
flask.api.index#flask.views.View.dispatch_request
methods: Optional[List[str]] = None A list of methods this view can handle.
flask.api.index#flask.views.View.methods
provide_automatic_options: Optional[bool] = None Setting this disables or force-enables the automatic options handling.
flask.api.index#flask.views.View.provide_automatic_options
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.
flask.api.index#flask.cli.with_appcontext
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.
flask.api.index#flask.ctx._AppCtxGlobals
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.
flask.api.index#flask.ctx._AppCtxGlobals.get
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.
flask.api.index#flask.ctx._AppCtxGlobals.pop
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.
flask.api.index#flask.ctx._AppCtxGlobals.setdefault
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.
django.ref.contrib.admin.actions#django.contrib.admin.action
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.
django.ref.contrib.admin.index#django.contrib.admin.AdminSite
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')
django.ref.contrib.admin.actions#django.contrib.admin.AdminSite.add_action
AdminSite.app_index_template Path to a custom template that will be used by the admin site app index view.
django.ref.contrib.admin.index#django.contrib.admin.AdminSite.app_index_template
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'] ...
django.ref.contrib.admin.actions#django.contrib.admin.AdminSite.disable_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.
django.ref.contrib.admin.index#django.contrib.admin.AdminSite.each_context
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.
django.ref.contrib.admin.index#django.contrib.admin.AdminSite.empty_value_display
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.
django.ref.contrib.admin.index#django.contrib.admin.AdminSite.enable_nav_sidebar
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.
django.ref.contrib.admin.index#django.contrib.admin.AdminSite.final_catch_all_view
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.
django.ref.contrib.admin.index#django.contrib.admin.AdminSite.has_permission
AdminSite.index_template Path to a custom template that will be used by the admin site main index view.
django.ref.contrib.admin.index#django.contrib.admin.AdminSite.index_template
AdminSite.index_title The text to put at the top of the admin index page (a string). By default, this is “Site administration”.
django.ref.contrib.admin.index#django.contrib.admin.AdminSite.index_title
AdminSite.login_form Subclass of AuthenticationForm that will be used by the admin site login view.
django.ref.contrib.admin.index#django.contrib.admin.AdminSite.login_form
AdminSite.login_template Path to a custom template that will be used by the admin site login view.
django.ref.contrib.admin.index#django.contrib.admin.AdminSite.login_template
AdminSite.logout_template Path to a custom template that will be used by the admin site logout view.
django.ref.contrib.admin.index#django.contrib.admin.AdminSite.logout_template
AdminSite.password_change_done_template Path to a custom template that will be used by the admin site password change done view.
django.ref.contrib.admin.index#django.contrib.admin.AdminSite.password_change_done_template
AdminSite.password_change_template Path to a custom template that will be used by the admin site password change view.
django.ref.contrib.admin.index#django.contrib.admin.AdminSite.password_change_template
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.
django.ref.contrib.admin.index#django.contrib.admin.AdminSite.register
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”.
django.ref.contrib.admin.index#django.contrib.admin.AdminSite.site_header
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”.
django.ref.contrib.admin.index#django.contrib.admin.AdminSite.site_title
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 /.
django.ref.contrib.admin.index#django.contrib.admin.AdminSite.site_url
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.
django.ref.contrib.admin.index#django.contrib.admin.AdminSite.unregister
class apps.AdminConfig This is the default AppConfig class for the admin. It calls autodiscover() when Django starts.
django.ref.contrib.admin.index#django.contrib.admin.apps.AdminConfig
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.
django.ref.contrib.admin.index#django.contrib.admin.apps.SimpleAdminConfig
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.
django.ref.contrib.admin.index#django.contrib.admin.apps.SimpleAdminConfig.default_site
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.
django.ref.contrib.admin.index#django.contrib.admin.autodiscover
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.
django.ref.contrib.admin.index#django.contrib.admin.display
class InlineModelAdmin
django.ref.contrib.admin.index#django.contrib.admin.InlineModelAdmin
InlineModelAdmin.can_delete Specifies whether or not inline objects can be deleted in the inline. Defaults to True.
django.ref.contrib.admin.index#django.contrib.admin.InlineModelAdmin.can_delete
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.
django.ref.contrib.admin.index#django.contrib.admin.InlineModelAdmin.classes
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.
django.ref.contrib.admin.index#django.contrib.admin.InlineModelAdmin.extra
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.
django.ref.contrib.admin.index#django.contrib.admin.InlineModelAdmin.fk_name
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.
django.ref.contrib.admin.index#django.contrib.admin.InlineModelAdmin.form
InlineModelAdmin.formset This defaults to BaseInlineFormSet. Using your own formset can give you many possibilities of customization. Inlines are built around model formsets.
django.ref.contrib.admin.index#django.contrib.admin.InlineModelAdmin.formset
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
django.ref.contrib.admin.index#django.contrib.admin.InlineModelAdmin.get_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.
django.ref.contrib.admin.index#django.contrib.admin.InlineModelAdmin.get_formset
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
django.ref.contrib.admin.index#django.contrib.admin.InlineModelAdmin.get_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).
django.ref.contrib.admin.index#django.contrib.admin.InlineModelAdmin.get_min_num
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.
django.ref.contrib.admin.index#django.contrib.admin.InlineModelAdmin.has_add_permission
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.
django.ref.contrib.admin.index#django.contrib.admin.InlineModelAdmin.has_change_permission
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.
django.ref.contrib.admin.index#django.contrib.admin.InlineModelAdmin.has_delete_permission
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.
django.ref.contrib.admin.index#django.contrib.admin.InlineModelAdmin.max_num
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.
django.ref.contrib.admin.index#django.contrib.admin.InlineModelAdmin.min_num
InlineModelAdmin.model The model which the inline is using. This is required.
django.ref.contrib.admin.index#django.contrib.admin.InlineModelAdmin.model
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",)
django.ref.contrib.admin.index#django.contrib.admin.InlineModelAdmin.raw_id_fields
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.
django.ref.contrib.admin.index#django.contrib.admin.InlineModelAdmin.show_change_link
InlineModelAdmin.template The template used to render the inline on the page.
django.ref.contrib.admin.index#django.contrib.admin.InlineModelAdmin.template
InlineModelAdmin.verbose_name An override to the verbose_name from the model’s inner Meta class.
django.ref.contrib.admin.index#django.contrib.admin.InlineModelAdmin.verbose_name
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.
django.ref.contrib.admin.index#django.contrib.admin.InlineModelAdmin.verbose_name_plural
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)
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin
ModelAdmin.actions A list of actions to make available on the change list page. See Admin actions for details.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.actions
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).
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.actions_on_bottom
ModelAdmin.actions_on_top
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.actions_on_top
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).
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.actions_selection_counter
ModelAdmin.add_form_template Path to a custom template, used by add_view().
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.add_form_template
ModelAdmin.add_view(request, form_url='', extra_context=None) Django view for the model instance addition page. See note below.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.add_view
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.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.autocomplete_fields
ModelAdmin.change_form_template Path to a custom template, used by change_view().
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.change_form_template
ModelAdmin.change_list_template Path to a custom template, used by changelist_view().
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.change_list_template
ModelAdmin.change_view(request, object_id, form_url='', extra_context=None) Django view for the model instance editing page. See note below.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.change_view
ModelAdmin.changelist_view(request, extra_context=None) Django view for the model instances change list/actions page. See note below.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.changelist_view
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).
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.date_hierarchy
ModelAdmin.delete_confirmation_template Path to a custom template, used by delete_view() for displaying a confirmation page when deleting one or more objects.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.delete_confirmation_template
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().
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.delete_model
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.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.delete_queryset
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.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.delete_selected_confirmation_template
ModelAdmin.delete_view(request, object_id, extra_context=None) Django view for the model instance(s) deletion confirmation page. See note below.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.delete_view
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.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.empty_value_display
ModelAdmin.exclude This attribute, if given, should be a list of field names to exclude from the form. For example, let’s consider the following model: 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.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.exclude
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.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.fields
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.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.fieldsets
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.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.filter_horizontal
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.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.filter_vertical
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.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.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.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.formfield_for_choice_field
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
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.formfield_for_foreignkey
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)
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.formfield_for_manytomany
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.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.formfield_overrides
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
django.ref.contrib.admin.actions#django.contrib.admin.ModelAdmin.get_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.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.get_autocomplete_fields
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'}
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.get_changeform_initial_data
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.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.get_changelist
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.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.get_changelist_form
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)
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.get_changelist_formset
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.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.get_deleted_objects
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.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.get_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.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.get_fields