doc_content
stringlengths
1
386k
doc_id
stringlengths
5
188
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.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.get_fieldsets
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.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.get_form
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.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.get_formset_kwargs
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
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.get_formsets_with_inlines
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.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.get_inline_instances
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.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.get_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.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.get_list_display
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.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.get_list_display_links
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.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.get_list_filter
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.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.get_list_select_related
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']
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.get_ordering
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.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.get_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.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.get_prepopulated_fields
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)
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.get_queryset
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.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.get_readonly_fields
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.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.get_search_fields
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.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.get_search_results
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'}
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.get_sortable_by
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.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.get_urls
ModelAdmin.has_add_permission(request) Should return True if adding an object is permitted, False otherwise.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.has_add_permission
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).
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.has_change_permission
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).
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.has_delete_permission
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.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.has_module_permission
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.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.has_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.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.history_view
ModelAdmin.inlines See InlineModelAdmin objects below as well as ModelAdmin.get_formsets_with_inlines().
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.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( '<span style="color: #{};">{} {}</span>', self.color_code, self.first_name, self.last_name, ) class PersonAdmin(admin.ModelAdmin): list_display = ('first_name', 'last_name', 'colored_name') As some examples have already demonstrated, when using a callable, a model method, or a 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( '<span style="color: #{};">{}</span>', self.color_code, self.first_name, ) class PersonAdmin(admin.ModelAdmin): list_display = ('first_name', 'colored_first_name') The above will tell Django to order by the first_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 <th> element. This can be used to set column widths in a CSS file for example. Django will try to interpret every element of list_display in this order: A field of the model. A callable. A string representing a ModelAdmin attribute. A string representing a model attribute. For example if you have first_name as a model field and as a ModelAdmin attribute, the model field will be used.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.list_display
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
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.list_display_links
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.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.list_editable
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.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.list_filter
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.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.list_max_show_all
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.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.list_per_page
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.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.list_select_related
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. [email protected]). 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. '[email protected]'), 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.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.lookup_allowed
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.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.message_user
ModelAdmin.object_history_template Path to a custom template, used by history_view().
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.object_history_template
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.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.ordering
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().
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.paginator
ModelAdmin.popup_response_template Path to a custom template, used by response_add(), response_change(), and response_delete().
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.popup_response_template
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.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.prepopulated_fields
ModelAdmin.preserve_filters By default, applied filters are preserved on the list view after creating, editing, or deleting an object. You can have filters cleared by setting this attribute to False.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.preserve_filters
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.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.radio_fields
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:
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.raw_id_fields
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('<br>'), '{}', ((line,) for line in instance.get_full_address()), ) or mark_safe("<span class='errors'>I can't determine this address.</span>")
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.readonly_fields
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.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.response_add
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.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.response_change
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.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.response_delete
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.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.save_as
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.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.save_as_continue
ModelAdmin.save_formset(request, form, formset, change) The save_formset method is given the HttpRequest, the parent ModelForm instance and a boolean value based on whether it is adding or changing the parent object. For example, to attach request.user to each changed formset model instance: class ArticleAdmin(admin.ModelAdmin): def save_formset(self, request, form, formset, change): instances = formset.save(commit=False) for obj in formset.deleted_objects: obj.delete() for instance in instances: instance.user = request.user instance.save() formset.save_m2m() See also Saving objects in the formset.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.save_formset
ModelAdmin.save_model(request, obj, form, change) The save_model method is given the HttpRequest, a model instance, a ModelForm instance, and a boolean value based on whether it is adding or changing the object. Overriding this method allows doing pre- or post-save operations. Call super().save_model() to save the object using Model.save(). For example to attach request.user to the object prior to saving: from django.contrib import admin class ArticleAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): obj.user = request.user super().save_model(request, obj, form, change)
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.save_model
ModelAdmin.save_on_top Set save_on_top to add save buttons across the top of your admin change forms. Normally, the save buttons appear only at the bottom of the forms. If you set save_on_top, the buttons will appear both on the top and the bottom. By default, save_on_top is set to False.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.save_on_top
ModelAdmin.save_related(request, form, formsets, change) The save_related method is given the HttpRequest, the parent ModelForm instance, the list of inline formsets and a boolean value based on whether the parent is being added or changed. Here you can do any pre- or post-save operations for objects related to the parent. Note that at this point the parent object and its form have already been saved.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.save_related
ModelAdmin.search_fields Set search_fields to enable a search box on the admin change list page. This should be set to a list of field names that will be searched whenever somebody submits a search query in that text box. These fields should be some kind of text field, such as CharField or TextField. You can also perform a related lookup on a ForeignKey or ManyToManyField with the lookup API “follow” notation: search_fields = ['foreign_key__related_fieldname'] For example, if you have a blog entry with an author, the following definition would enable searching blog entries by the email address of the author: search_fields = ['user__email'] When somebody does a search in the admin search box, Django splits the search query into words and returns all objects that contain each of the words, case-insensitive (using the icontains lookup), where each word must be in at least one of search_fields. For example, if search_fields is set to ['first_name', 'last_name'] and a user searches for john lennon, Django will do the equivalent of this SQL WHERE clause: WHERE (first_name ILIKE '%john%' OR last_name ILIKE '%john%') AND (first_name ILIKE '%lennon%' OR last_name ILIKE '%lennon%') The search query can contain quoted phrases with spaces. For example, if a user searches for "john winston" or 'john winston', Django will do the equivalent of this SQL WHERE clause: WHERE (first_name ILIKE '%john winston%' OR last_name ILIKE '%john winston%') If you don’t want to use icontains as the lookup, you can use any lookup by appending it the field. For example, you could use exact by setting search_fields to ['first_name__exact']. Some (older) shortcuts for specifying a field lookup are also available. You can prefix a field in search_fields with the following characters and it’s equivalent to adding __<lookup> to the field: Prefix Lookup ^ startswith = iexact @ search None icontains If you need to customize search you can use ModelAdmin.get_search_results() to provide additional or alternate search behavior. Changed in Django 3.2: Support for searching against quoted phrases with spaces was added.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.search_fields
ModelAdmin.search_help_text New in Django 4.0. Set search_help_text to specify a descriptive text for the search box which will be displayed below it.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.search_help_text
ModelAdmin.show_full_result_count Set show_full_result_count to control whether the full count of objects should be displayed on a filtered admin page (e.g. 99 results (103 total)). If this option is set to False, a text like 99 results (Show all) is displayed instead. The default of show_full_result_count=True generates a query to perform a full count on the table which can be expensive if the table contains a large number of rows.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.show_full_result_count
ModelAdmin.sortable_by By default, the change list page allows sorting by all model fields (and callables that use the ordering argument to the display() decorator or have the admin_order_field attribute) specified in list_display. If you want to disable sorting for some columns, set sortable_by to a collection (e.g. list, tuple, or set) of the subset of list_display that you want to be sortable. An empty collection disables sorting for all columns. If you need to specify this list dynamically, implement a get_sortable_by() method instead.
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.sortable_by
ModelAdmin.view_on_site Set view_on_site to control whether or not to display the “View on site” link. This link should bring you to a URL where you can display the saved object. This value can be either a boolean flag or a callable. If True (the default), the object’s get_absolute_url() method will be used to generate the url. If your model has a get_absolute_url() method but you don’t want the “View on site” button to appear, you only need to set view_on_site to False: from django.contrib import admin class PersonAdmin(admin.ModelAdmin): view_on_site = False In case it is a callable, it accepts the model instance as a parameter. For example: from django.contrib import admin from django.urls import reverse class PersonAdmin(admin.ModelAdmin): def view_on_site(self, obj): url = reverse('person-detail', kwargs={'slug': obj.slug}) return 'https://example.com' + url
django.ref.contrib.admin.index#django.contrib.admin.ModelAdmin.view_on_site
class models.LogEntry The LogEntry class tracks additions, changes, and deletions of objects done through the admin interface.
django.ref.contrib.admin.index#django.contrib.admin.models.LogEntry
LogEntry.action_flag The type of action logged: ADDITION, CHANGE, DELETION. For example, to get a list of all additions done through the admin: from django.contrib.admin.models import ADDITION, LogEntry LogEntry.objects.filter(action_flag=ADDITION)
django.ref.contrib.admin.index#django.contrib.admin.models.LogEntry.action_flag
LogEntry.action_time The date and time of the action.
django.ref.contrib.admin.index#django.contrib.admin.models.LogEntry.action_time
LogEntry.change_message The detailed description of the modification. In the case of an edit, for example, the message contains a list of the edited fields. The Django admin site formats this content as a JSON structure, so that get_change_message() can recompose a message translated in the current user language. Custom code might set this as a plain string though. You are advised to use the get_change_message() method to retrieve this value instead of accessing it directly.
django.ref.contrib.admin.index#django.contrib.admin.models.LogEntry.change_message
LogEntry.content_type The ContentType of the modified object.
django.ref.contrib.admin.index#django.contrib.admin.models.LogEntry.content_type
LogEntry.get_change_message() Formats and translates change_message into the current user language. Messages created before Django 1.10 will always be displayed in the language in which they were logged.
django.ref.contrib.admin.index#django.contrib.admin.models.LogEntry.get_change_message
LogEntry.get_edited_object() A shortcut that returns the referenced object.
django.ref.contrib.admin.index#django.contrib.admin.models.LogEntry.get_edited_object
LogEntry.object_id The textual representation of the modified object’s primary key.
django.ref.contrib.admin.index#django.contrib.admin.models.LogEntry.object_id
LogEntry.object_repr The object`s repr() after the modification.
django.ref.contrib.admin.index#django.contrib.admin.models.LogEntry.object_repr
LogEntry.user The user (an AUTH_USER_MODEL instance) who performed the action.
django.ref.contrib.admin.index#django.contrib.admin.models.LogEntry.user
register(*models, site=django.contrib.admin.sites.site) There is also a decorator for registering your ModelAdmin classes: from django.contrib import admin from .models import Author @admin.register(Author) class AuthorAdmin(admin.ModelAdmin): pass It’s given one or more model classes to register with the ModelAdmin. If you’re using a custom AdminSite, pass it using the site keyword argument: from django.contrib import admin from .models import Author, Editor, Reader from myproject.admin_site import custom_admin_site @admin.register(Author, Reader, Editor, site=custom_admin_site) class PersonAdmin(admin.ModelAdmin): pass You can’t use this decorator if you have to reference your model admin class in its __init__() method, e.g. super(PersonAdmin, self).__init__(*args, **kwargs). You can use super().__init__(*args, **kwargs).
django.ref.contrib.admin.index#django.contrib.admin.register
class StackedInline The admin interface has the ability to edit models on the same page as a parent model. These are called inlines. Suppose you have these two models: from django.db import models class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) title = models.CharField(max_length=100) You can edit the books authored by an author on the author page. You add inlines to a model by specifying them in a ModelAdmin.inlines: from django.contrib import admin class BookInline(admin.TabularInline): model = Book class AuthorAdmin(admin.ModelAdmin): inlines = [ BookInline, ] Django provides two subclasses of InlineModelAdmin and they are: TabularInline StackedInline The difference between these two is merely the template used to render them.
django.ref.contrib.admin.index#django.contrib.admin.StackedInline
class TabularInline
django.ref.contrib.admin.index#django.contrib.admin.TabularInline
staff_member_required(redirect_field_name='next', login_url='admin:login') This decorator is used on the admin views that require authorization. A view decorated with this function will have the following behavior: If the user is logged in, is a staff member (User.is_staff=True), and is active (User.is_active=True), execute the view normally. Otherwise, the request will be redirected to the URL specified by the login_url parameter, with the originally requested path in a query string variable specified by redirect_field_name. For example: /admin/login/?next=/admin/polls/question/3/. Example usage: from django.contrib.admin.views.decorators import staff_member_required @staff_member_required def my_view(request): ...
django.ref.contrib.admin.index#django.contrib.admin.views.decorators.staff_member_required
Aggregation The topic guide on Django’s database-abstraction API described the way that you can use Django queries that create, retrieve, update and delete individual objects. However, sometimes you will need to retrieve values that are derived by summarizing or aggregating a collection of objects. This topic guide describes the ways that aggregate values can be generated and returned using Django queries. Throughout this guide, we’ll refer to the following models. These models are used to track the inventory for a series of online bookstores: from django.db import models class Author(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() class Publisher(models.Model): name = models.CharField(max_length=300) class Book(models.Model): name = models.CharField(max_length=300) pages = models.IntegerField() price = models.DecimalField(max_digits=10, decimal_places=2) rating = models.FloatField() authors = models.ManyToManyField(Author) publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE) pubdate = models.DateField() class Store(models.Model): name = models.CharField(max_length=300) books = models.ManyToManyField(Book) Cheat sheet In a hurry? Here’s how to do common aggregate queries, assuming the models above: # Total number of books. >>> Book.objects.count() 2452 # Total number of books with publisher=BaloneyPress >>> Book.objects.filter(publisher__name='BaloneyPress').count() 73 # Average price across all books. >>> from django.db.models import Avg >>> Book.objects.all().aggregate(Avg('price')) {'price__avg': 34.35} # Max price across all books. >>> from django.db.models import Max >>> Book.objects.all().aggregate(Max('price')) {'price__max': Decimal('81.20')} # Difference between the highest priced book and the average price of all books. >>> from django.db.models import FloatField >>> Book.objects.aggregate( ... price_diff=Max('price', output_field=FloatField()) - Avg('price')) {'price_diff': 46.85} # All the following queries involve traversing the Book<->Publisher # foreign key relationship backwards. # Each publisher, each with a count of books as a "num_books" attribute. >>> from django.db.models import Count >>> pubs = Publisher.objects.annotate(num_books=Count('book')) >>> pubs <QuerySet [<Publisher: BaloneyPress>, <Publisher: SalamiPress>, ...]> >>> pubs[0].num_books 73 # Each publisher, with a separate count of books with a rating above and below 5 >>> from django.db.models import Q >>> above_5 = Count('book', filter=Q(book__rating__gt=5)) >>> below_5 = Count('book', filter=Q(book__rating__lte=5)) >>> pubs = Publisher.objects.annotate(below_5=below_5).annotate(above_5=above_5) >>> pubs[0].above_5 23 >>> pubs[0].below_5 12 # The top 5 publishers, in order by number of books. >>> pubs = Publisher.objects.annotate(num_books=Count('book')).order_by('-num_books')[:5] >>> pubs[0].num_books 1323 Generating aggregates over a QuerySet Django provides two ways to generate aggregates. The first way is to generate summary values over an entire QuerySet. For example, say you wanted to calculate the average price of all books available for sale. Django’s query syntax provides a means for describing the set of all books: >>> Book.objects.all() What we need is a way to calculate summary values over the objects that belong to this QuerySet. This is done by appending an aggregate() clause onto the QuerySet: >>> from django.db.models import Avg >>> Book.objects.all().aggregate(Avg('price')) {'price__avg': 34.35} The all() is redundant in this example, so this could be simplified to: >>> Book.objects.aggregate(Avg('price')) {'price__avg': 34.35} The argument to the aggregate() clause describes the aggregate value that we want to compute - in this case, the average of the price field on the Book model. A list of the aggregate functions that are available can be found in the QuerySet reference. aggregate() is a terminal clause for a QuerySet that, when invoked, returns a dictionary of name-value pairs. The name is an identifier for the aggregate value; the value is the computed aggregate. The name is automatically generated from the name of the field and the aggregate function. If you want to manually specify a name for the aggregate value, you can do so by providing that name when you specify the aggregate clause: >>> Book.objects.aggregate(average_price=Avg('price')) {'average_price': 34.35} If you want to generate more than one aggregate, you add another argument to the aggregate() clause. So, if we also wanted to know the maximum and minimum price of all books, we would issue the query: >>> from django.db.models import Avg, Max, Min >>> Book.objects.aggregate(Avg('price'), Max('price'), Min('price')) {'price__avg': 34.35, 'price__max': Decimal('81.20'), 'price__min': Decimal('12.99')} Generating aggregates for each item in a QuerySet The second way to generate summary values is to generate an independent summary for each object in a QuerySet. For example, if you are retrieving a list of books, you may want to know how many authors contributed to each book. Each Book has a many-to-many relationship with the Author; we want to summarize this relationship for each book in the QuerySet. Per-object summaries can be generated using the annotate() clause. When an annotate() clause is specified, each object in the QuerySet will be annotated with the specified values. The syntax for these annotations is identical to that used for the aggregate() clause. Each argument to annotate() describes an aggregate that is to be calculated. For example, to annotate books with the number of authors: # Build an annotated queryset >>> from django.db.models import Count >>> q = Book.objects.annotate(Count('authors')) # Interrogate the first object in the queryset >>> q[0] <Book: The Definitive Guide to Django> >>> q[0].authors__count 2 # Interrogate the second object in the queryset >>> q[1] <Book: Practical Django Projects> >>> q[1].authors__count 1 As with aggregate(), the name for the annotation is automatically derived from the name of the aggregate function and the name of the field being aggregated. You can override this default name by providing an alias when you specify the annotation: >>> q = Book.objects.annotate(num_authors=Count('authors')) >>> q[0].num_authors 2 >>> q[1].num_authors 1 Unlike aggregate(), annotate() is not a terminal clause. The output of the annotate() clause is a QuerySet; this QuerySet can be modified using any other QuerySet operation, including filter(), order_by(), or even additional calls to annotate(). Combining multiple aggregations Combining multiple aggregations with annotate() will yield the wrong results because joins are used instead of subqueries: >>> book = Book.objects.first() >>> book.authors.count() 2 >>> book.store_set.count() 3 >>> q = Book.objects.annotate(Count('authors'), Count('store')) >>> q[0].authors__count 6 >>> q[0].store__count 6 For most aggregates, there is no way to avoid this problem, however, the Count aggregate has a distinct parameter that may help: >>> q = Book.objects.annotate(Count('authors', distinct=True), Count('store', distinct=True)) >>> q[0].authors__count 2 >>> q[0].store__count 3 If in doubt, inspect the SQL query! In order to understand what happens in your query, consider inspecting the query property of your QuerySet. Joins and aggregates So far, we have dealt with aggregates over fields that belong to the model being queried. However, sometimes the value you want to aggregate will belong to a model that is related to the model you are querying. When specifying the field to be aggregated in an aggregate function, Django will allow you to use the same double underscore notation that is used when referring to related fields in filters. Django will then handle any table joins that are required to retrieve and aggregate the related value. For example, to find the price range of books offered in each store, you could use the annotation: >>> from django.db.models import Max, Min >>> Store.objects.annotate(min_price=Min('books__price'), max_price=Max('books__price')) This tells Django to retrieve the Store model, join (through the many-to-many relationship) with the Book model, and aggregate on the price field of the book model to produce a minimum and maximum value. The same rules apply to the aggregate() clause. If you wanted to know the lowest and highest price of any book that is available for sale in any of the stores, you could use the aggregate: >>> Store.objects.aggregate(min_price=Min('books__price'), max_price=Max('books__price')) Join chains can be as deep as you require. For example, to extract the age of the youngest author of any book available for sale, you could issue the query: >>> Store.objects.aggregate(youngest_age=Min('books__authors__age')) Following relationships backwards In a way similar to Lookups that span relationships, aggregations and annotations on fields of models or models that are related to the one you are querying can include traversing “reverse” relationships. The lowercase name of related models and double-underscores are used here too. For example, we can ask for all publishers, annotated with their respective total book stock counters (note how we use 'book' to specify the Publisher -> Book reverse foreign key hop): >>> from django.db.models import Avg, Count, Min, Sum >>> Publisher.objects.annotate(Count('book')) (Every Publisher in the resulting QuerySet will have an extra attribute called book__count.) We can also ask for the oldest book of any of those managed by every publisher: >>> Publisher.objects.aggregate(oldest_pubdate=Min('book__pubdate')) (The resulting dictionary will have a key called 'oldest_pubdate'. If no such alias were specified, it would be the rather long 'book__pubdate__min'.) This doesn’t apply just to foreign keys. It also works with many-to-many relations. For example, we can ask for every author, annotated with the total number of pages considering all the books the author has (co-)authored (note how we use 'book' to specify the Author -> Book reverse many-to-many hop): >>> Author.objects.annotate(total_pages=Sum('book__pages')) (Every Author in the resulting QuerySet will have an extra attribute called total_pages. If no such alias were specified, it would be the rather long book__pages__sum.) Or ask for the average rating of all the books written by author(s) we have on file: >>> Author.objects.aggregate(average_rating=Avg('book__rating')) (The resulting dictionary will have a key called 'average_rating'. If no such alias were specified, it would be the rather long 'book__rating__avg'.) Aggregations and other QuerySet clauses filter() and exclude() Aggregates can also participate in filters. Any filter() (or exclude()) applied to normal model fields will have the effect of constraining the objects that are considered for aggregation. When used with an annotate() clause, a filter has the effect of constraining the objects for which an annotation is calculated. For example, you can generate an annotated list of all books that have a title starting with “Django” using the query: >>> from django.db.models import Avg, Count >>> Book.objects.filter(name__startswith="Django").annotate(num_authors=Count('authors')) When used with an aggregate() clause, a filter has the effect of constraining the objects over which the aggregate is calculated. For example, you can generate the average price of all books with a title that starts with “Django” using the query: >>> Book.objects.filter(name__startswith="Django").aggregate(Avg('price')) Filtering on annotations Annotated values can also be filtered. The alias for the annotation can be used in filter() and exclude() clauses in the same way as any other model field. For example, to generate a list of books that have more than one author, you can issue the query: >>> Book.objects.annotate(num_authors=Count('authors')).filter(num_authors__gt=1) This query generates an annotated result set, and then generates a filter based upon that annotation. If you need two annotations with two separate filters you can use the filter argument with any aggregate. For example, to generate a list of authors with a count of highly rated books: >>> highly_rated = Count('book', filter=Q(book__rating__gte=7)) >>> Author.objects.annotate(num_books=Count('book'), highly_rated_books=highly_rated) Each Author in the result set will have the num_books and highly_rated_books attributes. See also Conditional aggregation. Choosing between filter and QuerySet.filter() Avoid using the filter argument with a single annotation or aggregation. It’s more efficient to use QuerySet.filter() to exclude rows. The aggregation filter argument is only useful when using two or more aggregations over the same relations with different conditionals. Order of annotate() and filter() clauses When developing a complex query that involves both annotate() and filter() clauses, pay particular attention to the order in which the clauses are applied to the QuerySet. When an annotate() clause is applied to a query, the annotation is computed over the state of the query up to the point where the annotation is requested. The practical implication of this is that filter() and annotate() are not commutative operations. Given: Publisher A has two books with ratings 4 and 5. Publisher B has two books with ratings 1 and 4. Publisher C has one book with rating 1. Here’s an example with the Count aggregate: >>> a, b = Publisher.objects.annotate(num_books=Count('book', distinct=True)).filter(book__rating__gt=3.0) >>> a, a.num_books (<Publisher: A>, 2) >>> b, b.num_books (<Publisher: B>, 2) >>> a, b = Publisher.objects.filter(book__rating__gt=3.0).annotate(num_books=Count('book')) >>> a, a.num_books (<Publisher: A>, 2) >>> b, b.num_books (<Publisher: B>, 1) Both queries return a list of publishers that have at least one book with a rating exceeding 3.0, hence publisher C is excluded. In the first query, the annotation precedes the filter, so the filter has no effect on the annotation. distinct=True is required to avoid a query bug. The second query counts the number of books that have a rating exceeding 3.0 for each publisher. The filter precedes the annotation, so the filter constrains the objects considered when calculating the annotation. Here’s another example with the Avg aggregate: >>> a, b = Publisher.objects.annotate(avg_rating=Avg('book__rating')).filter(book__rating__gt=3.0) >>> a, a.avg_rating (<Publisher: A>, 4.5) # (5+4)/2 >>> b, b.avg_rating (<Publisher: B>, 2.5) # (1+4)/2 >>> a, b = Publisher.objects.filter(book__rating__gt=3.0).annotate(avg_rating=Avg('book__rating')) >>> a, a.avg_rating (<Publisher: A>, 4.5) # (5+4)/2 >>> b, b.avg_rating (<Publisher: B>, 4.0) # 4/1 (book with rating 1 excluded) The first query asks for the average rating of all a publisher’s books for publisher’s that have at least one book with a rating exceeding 3.0. The second query asks for the average of a publisher’s book’s ratings for only those ratings exceeding 3.0. It’s difficult to intuit how the ORM will translate complex querysets into SQL queries so when in doubt, inspect the SQL with str(queryset.query) and write plenty of tests. order_by() Annotations can be used as a basis for ordering. When you define an order_by() clause, the aggregates you provide can reference any alias defined as part of an annotate() clause in the query. For example, to order a QuerySet of books by the number of authors that have contributed to the book, you could use the following query: >>> Book.objects.annotate(num_authors=Count('authors')).order_by('num_authors') values() Ordinarily, annotations are generated on a per-object basis - an annotated QuerySet will return one result for each object in the original QuerySet. However, when a values() clause is used to constrain the columns that are returned in the result set, the method for evaluating annotations is slightly different. Instead of returning an annotated result for each result in the original QuerySet, the original results are grouped according to the unique combinations of the fields specified in the values() clause. An annotation is then provided for each unique group; the annotation is computed over all members of the group. For example, consider an author query that attempts to find out the average rating of books written by each author: >>> Author.objects.annotate(average_rating=Avg('book__rating')) This will return one result for each author in the database, annotated with their average book rating. However, the result will be slightly different if you use a values() clause: >>> Author.objects.values('name').annotate(average_rating=Avg('book__rating')) In this example, the authors will be grouped by name, so you will only get an annotated result for each unique author name. This means if you have two authors with the same name, their results will be merged into a single result in the output of the query; the average will be computed as the average over the books written by both authors. Order of annotate() and values() clauses As with the filter() clause, the order in which annotate() and values() clauses are applied to a query is significant. If the values() clause precedes the annotate(), the annotation will be computed using the grouping described by the values() clause. However, if the annotate() clause precedes the values() clause, the annotations will be generated over the entire query set. In this case, the values() clause only constrains the fields that are generated on output. For example, if we reverse the order of the values() and annotate() clause from our previous example: >>> Author.objects.annotate(average_rating=Avg('book__rating')).values('name', 'average_rating') This will now yield one unique result for each author; however, only the author’s name and the average_rating annotation will be returned in the output data. You should also note that average_rating has been explicitly included in the list of values to be returned. This is required because of the ordering of the values() and annotate() clause. If the values() clause precedes the annotate() clause, any annotations will be automatically added to the result set. However, if the values() clause is applied after the annotate() clause, you need to explicitly include the aggregate column. Interaction with order_by() Fields that are mentioned in the order_by() part of a queryset are used when selecting the output data, even if they are not otherwise specified in the values() call. These extra fields are used to group “like” results together and they can make otherwise identical result rows appear to be separate. This shows up, particularly, when counting things. By way of example, suppose you have a model like this: from django.db import models class Item(models.Model): name = models.CharField(max_length=10) data = models.IntegerField() If you want to count how many times each distinct data value appears in an ordered queryset, you might try this: items = Item.objects.order_by('name') # Warning: not quite correct! items.values('data').annotate(Count('id')) …which will group the Item objects by their common data values and then count the number of id values in each group. Except that it won’t quite work. The ordering by name will also play a part in the grouping, so this query will group by distinct (data, name) pairs, which isn’t what you want. Instead, you should construct this queryset: items.values('data').annotate(Count('id')).order_by() …clearing any ordering in the query. You could also order by, say, data without any harmful effects, since that is already playing a role in the query. This behavior is the same as that noted in the queryset documentation for distinct() and the general rule is the same: normally you won’t want extra columns playing a part in the result, so clear out the ordering, or at least make sure it’s restricted only to those fields you also select in a values() call. Note You might reasonably ask why Django doesn’t remove the extraneous columns for you. The main reason is consistency with distinct() and other places: Django never removes ordering constraints that you have specified (and we can’t change those other methods’ behavior, as that would violate our API stability policy). Aggregating annotations You can also generate an aggregate on the result of an annotation. When you define an aggregate() clause, the aggregates you provide can reference any alias defined as part of an annotate() clause in the query. For example, if you wanted to calculate the average number of authors per book you first annotate the set of books with the author count, then aggregate that author count, referencing the annotation field: >>> from django.db.models import Avg, Count >>> Book.objects.annotate(num_authors=Count('authors')).aggregate(Avg('num_authors')) {'num_authors__avg': 1.66}
django.topics.db.aggregation
Applications Django contains a registry of installed applications that stores configuration and provides introspection. It also maintains a list of available models. This registry is called apps and it’s available in django.apps: >>> from django.apps import apps >>> apps.get_app_config('admin').verbose_name 'Administration' Projects and applications The term project describes a Django web application. The project Python package is defined primarily by a settings module, but it usually contains other things. For example, when you run django-admin startproject mysite you’ll get a mysite project directory that contains a mysite Python package with settings.py, urls.py, asgi.py and wsgi.py. The project package is often extended to include things like fixtures, CSS, and templates which aren’t tied to a particular application. A project’s root directory (the one that contains manage.py) is usually the container for all of a project’s applications which aren’t installed separately. The term application describes a Python package that provides some set of features. Applications may be reused in various projects. Applications include some combination of models, views, templates, template tags, static files, URLs, middleware, etc. They’re generally wired into projects with the INSTALLED_APPS setting and optionally with other mechanisms such as URLconfs, the MIDDLEWARE setting, or template inheritance. It is important to understand that a Django application is a set of code that interacts with various parts of the framework. There’s no such thing as an Application object. However, there’s a few places where Django needs to interact with installed applications, mainly for configuration and also for introspection. That’s why the application registry maintains metadata in an AppConfig instance for each installed application. There’s no restriction that a project package can’t also be considered an application and have models, etc. (which would require adding it to INSTALLED_APPS). Configuring applications To configure an application, create an apps.py module inside the application, then define a subclass of AppConfig there. When INSTALLED_APPS contains the dotted path to an application module, by default, if Django finds exactly one AppConfig subclass in the apps.py submodule, it uses that configuration for the application. This behavior may be disabled by setting AppConfig.default to False. If the apps.py module contains more than one AppConfig subclass, Django will look for a single one where AppConfig.default is True. If no AppConfig subclass is found, the base AppConfig class will be used. Alternatively, INSTALLED_APPS may contain the dotted path to a configuration class to specify it explicitly: INSTALLED_APPS = [ ... 'polls.apps.PollsAppConfig', ... ] For application authors If you’re creating a pluggable app called “Rock ’n’ roll”, here’s how you would provide a proper name for the admin: # rock_n_roll/apps.py from django.apps import AppConfig class RockNRollConfig(AppConfig): name = 'rock_n_roll' verbose_name = "Rock ’n’ roll" RockNRollConfig will be loaded automatically when INSTALLED_APPS contains 'rock_n_roll'. If you need to prevent this, set default to False in the class definition. You can provide several AppConfig subclasses with different behaviors. To tell Django which one to use by default, set default to True in its definition. If your users want to pick a non-default configuration, they must replace 'rock_n_roll' with the dotted path to that specific class in their INSTALLED_APPS setting. The AppConfig.name attribute tells Django which application this configuration applies to. You can define any other attribute documented in the AppConfig API reference. AppConfig subclasses may be defined anywhere. The apps.py convention merely allows Django to load them automatically when INSTALLED_APPS contains the path to an application module rather than the path to a configuration class. Note If your code imports the application registry in an application’s __init__.py, the name apps will clash with the apps submodule. The best practice is to move that code to a submodule and import it. A workaround is to import the registry under a different name: from django.apps import apps as django_apps Changed in Django 3.2: In previous versions, a default_app_config variable in the application module was used to identify the default application configuration class. For application users If you’re using “Rock ’n’ roll” in a project called anthology, but you want it to show up as “Jazz Manouche” instead, you can provide your own configuration: # anthology/apps.py from rock_n_roll.apps import RockNRollConfig class JazzManoucheConfig(RockNRollConfig): verbose_name = "Jazz Manouche" # anthology/settings.py INSTALLED_APPS = [ 'anthology.apps.JazzManoucheConfig', # ... ] This example shows project-specific configuration classes located in a submodule called apps.py. This is a convention, not a requirement. AppConfig subclasses may be defined anywhere. In this situation, INSTALLED_APPS must contain the dotted path to the configuration class because it lives outside of an application and thus cannot be automatically detected. Application configuration class AppConfig Application configuration objects store metadata for an application. Some attributes can be configured in AppConfig subclasses. Others are set by Django and read-only. Configurable attributes AppConfig.name Full Python path to the application, e.g. 'django.contrib.admin'. This attribute defines which application the configuration applies to. It must be set in all AppConfig subclasses. It must be unique across a Django project. AppConfig.label Short name for the application, e.g. 'admin' This attribute allows relabeling an application when two applications have conflicting labels. It defaults to the last component of name. It should be a valid Python identifier. It must be unique across a Django project. AppConfig.verbose_name Human-readable name for the application, e.g. “Administration”. This attribute defaults to label.title(). AppConfig.path Filesystem path to the application directory, e.g. '/usr/lib/pythonX.Y/dist-packages/django/contrib/admin'. In most cases, Django can automatically detect and set this, but you can also provide an explicit override as a class attribute on your AppConfig subclass. In a few situations this is required; for instance if the app package is a namespace package with multiple paths. AppConfig.default New in Django 3.2. Set this attribute to False to prevent Django from selecting a configuration class automatically. This is useful when apps.py defines only one AppConfig subclass but you don’t want Django to use it by default. Set this attribute to True to tell Django to select a configuration class automatically. This is useful when apps.py defines more than one AppConfig subclass and you want Django to use one of them by default. By default, this attribute isn’t set. AppConfig.default_auto_field New in Django 3.2. The implicit primary key type to add to models within this app. You can use this to keep AutoField as the primary key type for third party applications. By default, this is the value of DEFAULT_AUTO_FIELD. Read-only attributes AppConfig.module Root module for the application, e.g. <module 'django.contrib.admin' from 'django/contrib/admin/__init__.py'>. AppConfig.models_module Module containing the models, e.g. <module 'django.contrib.admin.models' from 'django/contrib/admin/models.py'>. It may be None if the application doesn’t contain a models module. Note that the database related signals such as pre_migrate and post_migrate are only emitted for applications that have a models module. Methods AppConfig.get_models() Returns an iterable of Model classes for this application. Requires the app registry to be fully populated. AppConfig.get_model(model_name, require_ready=True) Returns the Model with the given model_name. model_name is case-insensitive. Raises LookupError if no such model exists in this application. Requires the app registry to be fully populated unless the require_ready argument is set to False. require_ready behaves exactly as in apps.get_model(). AppConfig.ready() Subclasses can override this method to perform initialization tasks such as registering signals. It is called as soon as the registry is fully populated. Although you can’t import models at the module-level where AppConfig classes are defined, you can import them in ready(), using either an import statement or get_model(). If you’re registering model signals, you can refer to the sender by its string label instead of using the model class itself. Example: from django.apps import AppConfig from django.db.models.signals import pre_save class RockNRollConfig(AppConfig): # ... def ready(self): # importing model classes from .models import MyModel # or... MyModel = self.get_model('MyModel') # registering signals with the model's string label pre_save.connect(receiver, sender='app_label.MyModel') Warning Although you can access model classes as described above, avoid interacting with the database in your ready() implementation. This includes model methods that execute queries (save(), delete(), manager methods etc.), and also raw SQL queries via django.db.connection. Your ready() method will run during startup of every management command. For example, even though the test database configuration is separate from the production settings, manage.py test would still execute some queries against your production database! Note In the usual initialization process, the ready method is only called once by Django. But in some corner cases, particularly in tests which are fiddling with installed applications, ready might be called more than once. In that case, either write idempotent methods, or put a flag on your AppConfig classes to prevent re-running code which should be executed exactly one time. Namespace packages as apps Python packages without an __init__.py file are known as “namespace packages” and may be spread across multiple directories at different locations on sys.path (see PEP 420). Django applications require a single base filesystem path where Django (depending on configuration) will search for templates, static assets, etc. Thus, namespace packages may only be Django applications if one of the following is true: The namespace package actually has only a single location (i.e. is not spread across more than one directory.) The AppConfig class used to configure the application has a path class attribute, which is the absolute directory path Django will use as the single base path for the application. If neither of these conditions is met, Django will raise ImproperlyConfigured. Application registry apps The application registry provides the following public API. Methods that aren’t listed below are considered private and may change without notice. apps.ready Boolean attribute that is set to True after the registry is fully populated and all AppConfig.ready() methods are called. apps.get_app_configs() Returns an iterable of AppConfig instances. apps.get_app_config(app_label) Returns an AppConfig for the application with the given app_label. Raises LookupError if no such application exists. apps.is_installed(app_name) Checks whether an application with the given name exists in the registry. app_name is the full name of the app, e.g. 'django.contrib.admin'. apps.get_model(app_label, model_name, require_ready=True) Returns the Model with the given app_label and model_name. As a shortcut, this method also accepts a single argument in the form app_label.model_name. model_name is case-insensitive. Raises LookupError if no such application or model exists. Raises ValueError when called with a single argument that doesn’t contain exactly one dot. Requires the app registry to be fully populated unless the require_ready argument is set to False. Setting require_ready to False allows looking up models while the app registry is being populated, specifically during the second phase where it imports models. Then get_model() has the same effect as importing the model. The main use case is to configure model classes with settings, such as AUTH_USER_MODEL. When require_ready is False, get_model() returns a model class that may not be fully functional (reverse accessors may be missing, for example) until the app registry is fully populated. For this reason, it’s best to leave require_ready to the default value of True whenever possible. Initialization process How applications are loaded When Django starts, django.setup() is responsible for populating the application registry. setup(set_prefix=True) [source] Configures Django by: Loading the settings. Setting up logging. If set_prefix is True, setting the URL resolver script prefix to FORCE_SCRIPT_NAME if defined, or / otherwise. Initializing the application registry. This function is called automatically: When running an HTTP server via Django’s WSGI support. When invoking a management command. It must be called explicitly in other cases, for instance in plain Python scripts. The application registry is initialized in three stages. At each stage, Django processes all applications in the order of INSTALLED_APPS. First Django imports each item in INSTALLED_APPS. If it’s an application configuration class, Django imports the root package of the application, defined by its name attribute. If it’s a Python package, Django looks for an application configuration in an apps.py submodule, or else creates a default application configuration. At this stage, your code shouldn’t import any models! In other words, your applications’ root packages and the modules that define your application configuration classes shouldn’t import any models, even indirectly. Strictly speaking, Django allows importing models once their application configuration is loaded. However, in order to avoid needless constraints on the order of INSTALLED_APPS, it’s strongly recommended not import any models at this stage. Once this stage completes, APIs that operate on application configurations such as get_app_config() become usable. Then Django attempts to import the models submodule of each application, if there is one. You must define or import all models in your application’s models.py or models/__init__.py. Otherwise, the application registry may not be fully populated at this point, which could cause the ORM to malfunction. Once this stage completes, APIs that operate on models such as get_model() become usable. Finally Django runs the ready() method of each application configuration. Troubleshooting Here are some common problems that you may encounter during initialization: AppRegistryNotReady: This happens when importing an application configuration or a models module triggers code that depends on the app registry. For example, gettext() uses the app registry to look up translation catalogs in applications. To translate at import time, you need gettext_lazy() instead. (Using gettext() would be a bug, because the translation would happen at import time, rather than at each request depending on the active language.) Executing database queries with the ORM at import time in models modules will also trigger this exception. The ORM cannot function properly until all models are available. This exception also happens if you forget to call django.setup() in a standalone Python script. ImportError: cannot import name ... This happens if the import sequence ends up in a loop. To eliminate such problems, you should minimize dependencies between your models modules and do as little work as possible at import time. To avoid executing code at import time, you can move it into a function and cache its results. The code will be executed when you first need its results. This concept is known as “lazy evaluation”. django.contrib.admin automatically performs autodiscovery of admin modules in installed applications. To prevent it, change your INSTALLED_APPS to contain 'django.contrib.admin.apps.SimpleAdminConfig' instead of 'django.contrib.admin'.
django.ref.applications
class AppConfig Application configuration objects store metadata for an application. Some attributes can be configured in AppConfig subclasses. Others are set by Django and read-only.
django.ref.applications#django.apps.AppConfig
AppConfig.default New in Django 3.2. Set this attribute to False to prevent Django from selecting a configuration class automatically. This is useful when apps.py defines only one AppConfig subclass but you don’t want Django to use it by default. Set this attribute to True to tell Django to select a configuration class automatically. This is useful when apps.py defines more than one AppConfig subclass and you want Django to use one of them by default. By default, this attribute isn’t set.
django.ref.applications#django.apps.AppConfig.default
AppConfig.default_auto_field New in Django 3.2. The implicit primary key type to add to models within this app. You can use this to keep AutoField as the primary key type for third party applications. By default, this is the value of DEFAULT_AUTO_FIELD.
django.ref.applications#django.apps.AppConfig.default_auto_field
AppConfig.get_model(model_name, require_ready=True) Returns the Model with the given model_name. model_name is case-insensitive. Raises LookupError if no such model exists in this application. Requires the app registry to be fully populated unless the require_ready argument is set to False. require_ready behaves exactly as in apps.get_model().
django.ref.applications#django.apps.AppConfig.get_model
AppConfig.get_models() Returns an iterable of Model classes for this application. Requires the app registry to be fully populated.
django.ref.applications#django.apps.AppConfig.get_models
AppConfig.label Short name for the application, e.g. 'admin' This attribute allows relabeling an application when two applications have conflicting labels. It defaults to the last component of name. It should be a valid Python identifier. It must be unique across a Django project.
django.ref.applications#django.apps.AppConfig.label
AppConfig.models_module Module containing the models, e.g. <module 'django.contrib.admin.models' from 'django/contrib/admin/models.py'>. It may be None if the application doesn’t contain a models module. Note that the database related signals such as pre_migrate and post_migrate are only emitted for applications that have a models module.
django.ref.applications#django.apps.AppConfig.models_module
AppConfig.module Root module for the application, e.g. <module 'django.contrib.admin' from 'django/contrib/admin/__init__.py'>.
django.ref.applications#django.apps.AppConfig.module
AppConfig.name Full Python path to the application, e.g. 'django.contrib.admin'. This attribute defines which application the configuration applies to. It must be set in all AppConfig subclasses. It must be unique across a Django project.
django.ref.applications#django.apps.AppConfig.name
AppConfig.path Filesystem path to the application directory, e.g. '/usr/lib/pythonX.Y/dist-packages/django/contrib/admin'. In most cases, Django can automatically detect and set this, but you can also provide an explicit override as a class attribute on your AppConfig subclass. In a few situations this is required; for instance if the app package is a namespace package with multiple paths.
django.ref.applications#django.apps.AppConfig.path
AppConfig.ready() Subclasses can override this method to perform initialization tasks such as registering signals. It is called as soon as the registry is fully populated. Although you can’t import models at the module-level where AppConfig classes are defined, you can import them in ready(), using either an import statement or get_model(). If you’re registering model signals, you can refer to the sender by its string label instead of using the model class itself. Example: from django.apps import AppConfig from django.db.models.signals import pre_save class RockNRollConfig(AppConfig): # ... def ready(self): # importing model classes from .models import MyModel # or... MyModel = self.get_model('MyModel') # registering signals with the model's string label pre_save.connect(receiver, sender='app_label.MyModel') Warning Although you can access model classes as described above, avoid interacting with the database in your ready() implementation. This includes model methods that execute queries (save(), delete(), manager methods etc.), and also raw SQL queries via django.db.connection. Your ready() method will run during startup of every management command. For example, even though the test database configuration is separate from the production settings, manage.py test would still execute some queries against your production database! Note In the usual initialization process, the ready method is only called once by Django. But in some corner cases, particularly in tests which are fiddling with installed applications, ready might be called more than once. In that case, either write idempotent methods, or put a flag on your AppConfig classes to prevent re-running code which should be executed exactly one time.
django.ref.applications#django.apps.AppConfig.ready
AppConfig.verbose_name Human-readable name for the application, e.g. “Administration”. This attribute defaults to label.title().
django.ref.applications#django.apps.AppConfig.verbose_name
apps The application registry provides the following public API. Methods that aren’t listed below are considered private and may change without notice.
django.ref.applications#django.apps.apps
apps.get_app_config(app_label) Returns an AppConfig for the application with the given app_label. Raises LookupError if no such application exists.
django.ref.applications#django.apps.apps.get_app_config
apps.get_app_configs() Returns an iterable of AppConfig instances.
django.ref.applications#django.apps.apps.get_app_configs
apps.get_model(app_label, model_name, require_ready=True) Returns the Model with the given app_label and model_name. As a shortcut, this method also accepts a single argument in the form app_label.model_name. model_name is case-insensitive. Raises LookupError if no such application or model exists. Raises ValueError when called with a single argument that doesn’t contain exactly one dot. Requires the app registry to be fully populated unless the require_ready argument is set to False. Setting require_ready to False allows looking up models while the app registry is being populated, specifically during the second phase where it imports models. Then get_model() has the same effect as importing the model. The main use case is to configure model classes with settings, such as AUTH_USER_MODEL. When require_ready is False, get_model() returns a model class that may not be fully functional (reverse accessors may be missing, for example) until the app registry is fully populated. For this reason, it’s best to leave require_ready to the default value of True whenever possible.
django.ref.applications#django.apps.apps.get_model
apps.is_installed(app_name) Checks whether an application with the given name exists in the registry. app_name is the full name of the app, e.g. 'django.contrib.admin'.
django.ref.applications#django.apps.apps.is_installed
apps.ready Boolean attribute that is set to True after the registry is fully populated and all AppConfig.ready() methods are called.
django.ref.applications#django.apps.apps.ready
authenticate(request=None, **credentials) Use authenticate() to verify a set of credentials. It takes credentials as keyword arguments, username and password for the default case, checks them against each authentication backend, and returns a User object if the credentials are valid for a backend. If the credentials aren’t valid for any backend or if a backend raises PermissionDenied, it returns None. For example: from django.contrib.auth import authenticate user = authenticate(username='john', password='secret') if user is not None: # A backend authenticated the credentials else: # No backend authenticated the credentials request is an optional HttpRequest which is passed on the authenticate() method of the authentication backends. Note This is a low level way to authenticate a set of credentials; for example, it’s used by the RemoteUserMiddleware. Unless you are writing your own authentication system, you probably won’t use this. Rather if you’re looking for a way to login a user, use the LoginView.
django.topics.auth.default#django.contrib.auth.authenticate
class AllowAllUsersModelBackend Same as ModelBackend except that it doesn’t reject inactive users because user_can_authenticate() always returns True. When using this backend, you’ll likely want to customize the AuthenticationForm used by the LoginView by overriding the confirm_login_allowed() method as it rejects inactive users.
django.ref.contrib.auth#django.contrib.auth.backends.AllowAllUsersModelBackend
class AllowAllUsersRemoteUserBackend Same as RemoteUserBackend except that it doesn’t reject inactive users because user_can_authenticate always returns True.
django.ref.contrib.auth#django.contrib.auth.backends.AllowAllUsersRemoteUserBackend
class BaseBackend A base class that provides default implementations for all required methods. By default, it will reject any user and provide no permissions. get_user_permissions(user_obj, obj=None) Returns an empty set. get_group_permissions(user_obj, obj=None) Returns an empty set. get_all_permissions(user_obj, obj=None) Uses get_user_permissions() and get_group_permissions() to get the set of permission strings the user_obj has. has_perm(user_obj, perm, obj=None) Uses get_all_permissions() to check if user_obj has the permission string perm.
django.ref.contrib.auth#django.contrib.auth.backends.BaseBackend
get_all_permissions(user_obj, obj=None) Uses get_user_permissions() and get_group_permissions() to get the set of permission strings the user_obj has.
django.ref.contrib.auth#django.contrib.auth.backends.BaseBackend.get_all_permissions
get_group_permissions(user_obj, obj=None) Returns an empty set.
django.ref.contrib.auth#django.contrib.auth.backends.BaseBackend.get_group_permissions
get_user_permissions(user_obj, obj=None) Returns an empty set.
django.ref.contrib.auth#django.contrib.auth.backends.BaseBackend.get_user_permissions
has_perm(user_obj, perm, obj=None) Uses get_all_permissions() to check if user_obj has the permission string perm.
django.ref.contrib.auth#django.contrib.auth.backends.BaseBackend.has_perm