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:
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.


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.


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.


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.


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.


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


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:


Returns an instance of the paginator to use for this view. By default, instantiates an instance of paginator.


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.


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:


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.


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.


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:
This implementation is more efficient than search_fields =
('name', '=age') which results in a string comparison for the numeric field, for example ... OR UPPER("polls_choice"."votes"::text) = UPPER('4') on PostgreSQL.


The 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:


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:
If you want to use the admin layout, extend from admin/base_site.html:
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:
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:
Notice the wrapped view in the fifth line above:
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():
ModelAdmin views have model_admin attributes. Other AdminSite views have admin_site attributes.


Should return True if adding an object is permitted, False otherwise.


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).


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).


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.


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 view for the page that shows the modification history for a given model instance.


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


Set list_display to control which fields are displayed on the change list page of the admin.
Example:
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:
A callable that accepts one argument, the model instance. For example:
A string representing a ModelAdmin method that accepts one argument, the model instance. For example:
A string representing a model attribute or method (without any required arguments). For example:
A few special cases to note about list_display:
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:
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.
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:
You can also use ModelAdmin.empty_value_display:
Or on a field level:
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:
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:
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:
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:
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:
Query expressions may be used with the ordering argument:
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:
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:
Django will try to interpret every element of list_display in this order:
For example if you have first_name as a model field and as a ModelAdmin attribute, the model field will be used.


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 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:
In this example, the change list page grid will have no links:


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:
You’ll get a validation error if either of these rules are broken.


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:
Field names in list_filter can also span relations using the __ lookup, for example:
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.:
Note
As a convenience, the HttpRequest object is passed to the lookups and queryset methods, for example:
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:
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:
You can limit the choices of a related model to the objects involved in that relation using 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:
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:
See the default template provided by Django (admin/filter.html) for a concrete example.


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.


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


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:
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.


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


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.


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


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.


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().


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


Set prepopulated_fields to a dictionary mapping field names to the fields it should prepopulate from:
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.
In older versions, various English stop words are removed from generated values.


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.


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:
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.


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:
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:


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:


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.


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.


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.


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.


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.


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:
See also Saving objects in the formset.


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:


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.


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.


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:
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:
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:
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:
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:
If you need to customize search you can use ModelAdmin.get_search_results() to provide additional or alternate search behavior.
Support for searching against quoted phrases with spaces was added.


Set search_help_text to specify a descriptive text for the search box which will be displayed below it.


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.


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.


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:
In case it is a callable, it accepts the model instance as a parameter. For example:


The LogEntry class tracks additions, changes, and deletions of objects done through the admin interface.


The type of action logged: ADDITION, CHANGE, DELETION.
For example, to get a list of all additions done through the admin:


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.


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.


A shortcut that returns the referenced object.


The textual representation of the modified object’s primary key.


The object`s repr() after the modification.


The user (an AUTH_USER_MODEL instance) who performed the action.


There is also a decorator for registering your ModelAdmin classes:
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:
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).


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:
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:
Django provides two subclasses of InlineModelAdmin and they are:
The difference between these two is merely the template used to render them.


This decorator is used on the admin views that require authorization. A view decorated with this function will have the following behavior:
Example usage:


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:
In a hurry? Here’s how to do common aggregate queries, assuming the models above:
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:
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:
The all() is redundant in this example, so this could be simplified to:
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:
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:
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:
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:
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 with annotate() will yield the wrong results because joins are used instead of subqueries:
For most aggregates, there is no way to avoid this problem, however, the Count aggregate has a distinct parameter that may help:
If in doubt, inspect the SQL query!
In order to understand what happens in your query, consider inspecting the query property of your QuerySet.
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:
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:
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:
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):
(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:
(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):
(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:
(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'.)
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:
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:
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:
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:
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.
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:
Here’s an example with the Count aggregate:
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:
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.
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:
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:
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:
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.
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:
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.
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:
If you want to count how many times each distinct data value appears in an ordered queryset, you might try this:
…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:
…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).
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:


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:
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).
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:
If you’re creating a pluggable app called “Rock ’n’ roll”, here’s how you would provide a proper name for the admin:
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:
In previous versions, a default_app_config variable in the application module was used to identify the default application configuration class.
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:
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 objects store metadata for an application. Some attributes can be configured in AppConfig subclasses. Others are set by Django and read-only.
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.
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.
Human-readable name for the application, e.g. “Administration”.
This attribute defaults to label.title().
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.
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.
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.
Root module for the application, e.g. <module 'django.contrib.admin' from
'django/contrib/admin/__init__.py'>.
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.
Returns an iterable of Model classes for this application.
Requires the app registry to be fully populated.
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().
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:
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.
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:
If neither of these conditions is met, Django will raise ImproperlyConfigured.
The application registry provides the following public API. Methods that aren’t listed below are considered private and may change without notice.
Boolean attribute that is set to True after the registry is fully populated and all AppConfig.ready() methods are called.
Returns an iterable of AppConfig instances.
Returns an AppConfig for the application with the given app_label. Raises LookupError if no such application exists.
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'.
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.
When Django starts, django.setup() is responsible for populating the application registry.
Configures Django by:
This function is called automatically:
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.
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”.


Application configuration objects store metadata for an application. Some attributes can be configured in AppConfig subclasses. Others are set by Django and read-only.


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.


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.


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().


Returns an iterable of Model classes for this application.
Requires the app registry to be fully populated.


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.


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.


Root module for the application, e.g. <module 'django.contrib.admin' from
'django/contrib/admin/__init__.py'>.


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.


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.


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:
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.


Human-readable name for the application, e.g. “Administration”.
This attribute defaults to label.title().


The application registry provides the following public API. Methods that aren’t listed below are considered private and may change without notice.


Returns an AppConfig for the application with the given app_label. Raises LookupError if no such application exists.


Returns an iterable of AppConfig instances.


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.


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'.


Boolean attribute that is set to True after the registry is fully populated and all AppConfig.ready() methods are called.


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:
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.


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.


Same as RemoteUserBackend except that it doesn’t reject inactive users because user_can_authenticate always returns True.


A base class that provides default implementations for all required methods. By default, it will reject any user and provide no permissions.
Returns an empty set.
Returns an empty set.
Uses get_user_permissions() and get_group_permissions() to get the set of permission strings the user_obj has.
Uses get_all_permissions() to check if user_obj has the permission string perm.


Uses get_user_permissions() and get_group_permissions() to get the set of permission strings the user_obj has.


Uses get_all_permissions() to check if user_obj has the permission string perm.


This is the default authentication backend used by Django. It authenticates using credentials consisting of a user identifier and password. For Django’s default user model, the user identifier is the username, for custom user models it is the field specified by USERNAME_FIELD (see Customizing Users and authentication).
It also handles the default permissions model as defined for User and PermissionsMixin.
has_perm(), get_all_permissions(), get_user_permissions(), and get_group_permissions() allow an object to be passed as a parameter for object-specific permissions, but this backend does not implement them other than returning an empty set of permissions if obj is not None.
with_perm() also allows an object to be passed as a parameter, but unlike others methods it returns an empty queryset if obj is not None.
Tries to authenticate username with password by calling User.check_password. If no username is provided, it tries to fetch a username from kwargs using the key CustomUser.USERNAME_FIELD. Returns an authenticated user or None.
request is an HttpRequest and may be None if it wasn’t provided to authenticate() (which passes it on to the backend).
Returns the set of permission strings the user_obj has from their own user permissions. Returns an empty set if is_anonymous or is_active is False.
Returns the set of permission strings the user_obj has from the permissions of the groups they belong. Returns an empty set if is_anonymous or is_active is False.
Returns the set of permission strings the user_obj has, including both user permissions and group permissions. Returns an empty set if is_anonymous or is_active is False.
Uses get_all_permissions() to check if user_obj has the permission string perm. Returns False if the user is not is_active.
Returns whether the user_obj has any permissions on the app app_label.
Returns whether the user is allowed to authenticate. To match the behavior of AuthenticationForm which prohibits inactive users from logging in, this method returns False for users with is_active=False. Custom user models that don’t have an is_active field are allowed.
Returns all active users who have the permission perm either in the form of "<app label>.<permission codename>" or a Permission instance. Returns an empty queryset if no users who have the perm found.
If is_active is True (default), returns only active users, or if False, returns only inactive users. Use None to return all users irrespective of active state.
If include_superusers is True (default), the result will include superusers.


Tries to authenticate username with password by calling User.check_password. If no username is provided, it tries to fetch a username from kwargs using the key CustomUser.USERNAME_FIELD. Returns an authenticated user or None.
request is an HttpRequest and may be None if it wasn’t provided to authenticate() (which passes it on to the backend).


Returns the set of permission strings the user_obj has, including both user permissions and group permissions. Returns an empty set if is_anonymous or is_active is False.


Returns the set of permission strings the user_obj has from the permissions of the groups they belong. Returns an empty set if is_anonymous or is_active is False.


Returns the set of permission strings the user_obj has from their own user permissions. Returns an empty set if is_anonymous or is_active is False.


Returns whether the user_obj has any permissions on the app app_label.


Uses get_all_permissions() to check if user_obj has the permission string perm. Returns False if the user is not is_active.


Returns whether the user is allowed to authenticate. To match the behavior of AuthenticationForm which prohibits inactive users from logging in, this method returns False for users with is_active=False. Custom user models that don’t have an is_active field are allowed.


Returns all active users who have the permission perm either in the form of "<app label>.<permission codename>" or a Permission instance. Returns an empty queryset if no users who have the perm found.
If is_active is True (default), returns only active users, or if False, returns only inactive users. Use None to return all users irrespective of active state.
If include_superusers is True (default), the result will include superusers.


Use this backend to take advantage of external-to-Django-handled authentication. It authenticates using usernames passed in request.META['REMOTE_USER']. See the Authenticating against REMOTE_USER documentation.
If you need more control, you can create your own authentication backend that inherits from this class and override these attributes or methods:
True or False. Determines whether or not a user object is created if not already in the database Defaults to True.
The username passed as remote_user is considered trusted. This method returns the user object with the given username, creating a new user object if create_unknown_user is True.
Returns None if create_unknown_user is False and a User object with the given username is not found in the database.
request is an HttpRequest and may be None if it wasn’t provided to authenticate() (which passes it on to the backend).
Performs any cleaning on the username (e.g. stripping LDAP DN information) prior to using it to get or create a user object. Returns the cleaned username.
Configures a newly created user. This method is called immediately after a new user is created, and can be used to perform custom setup actions, such as setting the user’s groups based on attributes in an LDAP directory. Returns the user object.
request is an HttpRequest and may be None if it wasn’t provided to authenticate() (which passes it on to the backend).
Returns whether the user is allowed to authenticate. This method returns False for users with is_active=False. Custom user models that don’t have an is_active field are allowed.


The username passed as remote_user is considered trusted. This method returns the user object with the given username, creating a new user object if create_unknown_user is True.
Returns None if create_unknown_user is False and a User object with the given username is not found in the database.
request is an HttpRequest and may be None if it wasn’t provided to authenticate() (which passes it on to the backend).


Performs any cleaning on the username (e.g. stripping LDAP DN information) prior to using it to get or create a user object. Returns the cleaned username.


Configures a newly created user. This method is called immediately after a new user is created, and can be used to perform custom setup actions, such as setting the user’s groups based on attributes in an LDAP directory. Returns the user object.
request is an HttpRequest and may be None if it wasn’t provided to authenticate() (which passes it on to the backend).


True or False. Determines whether or not a user object is created if not already in the database Defaults to True.


Returns whether the user is allowed to authenticate. This method returns False for users with is_active=False. Custom user models that don’t have an is_active field are allowed.


As a shortcut, you can use the convenient login_required() decorator:
login_required() does the following:
By default, the path that the user should be redirected to upon successful authentication is stored in a query string parameter called "next". If you would prefer to use a different name for this parameter, login_required() takes an optional redirect_field_name parameter:
Note that if you provide a value to redirect_field_name, you will most likely need to customize your login template as well, since the template context variable which stores the redirect path will use the value of redirect_field_name as its key rather than "next" (the default).
login_required() also takes an optional login_url parameter. Example:
Note that if you don’t specify the login_url parameter, you’ll need to ensure that the settings.LOGIN_URL and your login view are properly associated. For example, using the defaults, add the following lines to your URLconf:
The settings.LOGIN_URL also accepts view function names and named URL patterns. This allows you to freely remap your login view within your URLconf without having to update the setting.


It’s a relatively common task to check whether a user has a particular permission. For that reason, Django provides a shortcut for that case: the permission_required() decorator.:
Just like the has_perm() method, permission names take the form "<app label>.<permission codename>" (i.e. polls.add_choice for a permission on a model in the polls application).
The decorator may also take an iterable of permissions, in which case the user must have all of the permissions in order to access the view.
Note that permission_required() also takes an optional login_url parameter:
As in the login_required() decorator, login_url defaults to settings.LOGIN_URL.
If the raise_exception parameter is given, the decorator will raise PermissionDenied, prompting the 403 (HTTP Forbidden) view instead of redirecting to the login page.
If you want to use raise_exception but also give your users a chance to login first, you can add the login_required() decorator:
This also avoids a redirect loop when LoginView’s redirect_authenticated_user=True and the logged-in user doesn’t have all of the required permissions.


As a shortcut, you can use the convenient user_passes_test decorator which performs a redirect when the callable returns False:
user_passes_test() takes a required argument: a callable that takes a User object and returns True if the user is allowed to view the page. Note that user_passes_test() does not automatically check that the User is not anonymous.
user_passes_test() takes two optional arguments:
For example:


A form used in the admin interface to change a user’s password.
Takes the user as the first positional argument.


A form for logging a user in.
Takes request as its first positional argument, which is stored on the form instance for use by sub-classes.
By default, AuthenticationForm rejects users whose is_active flag is set to False. You may override this behavior with a custom policy to determine which users can log in. Do this with a custom form that subclasses AuthenticationForm and overrides the confirm_login_allowed() method. This method should raise a ValidationError if the given user may not log in.
For example, to allow all users to log in regardless of “active” status:
(In this case, you’ll also need to use an authentication backend that allows inactive users, such as AllowAllUsersModelBackend.)
Or to allow only some active users to log in:


By default, AuthenticationForm rejects users whose is_active flag is set to False. You may override this behavior with a custom policy to determine which users can log in. Do this with a custom form that subclasses AuthenticationForm and overrides the confirm_login_allowed() method. This method should raise a ValidationError if the given user may not log in.
For example, to allow all users to log in regardless of “active” status:
(In this case, you’ll also need to use an authentication backend that allows inactive users, such as AllowAllUsersModelBackend.)
Or to allow only some active users to log in:


A form for allowing a user to change their password.


A form for generating and emailing a one-time use link to reset a user’s password.
Uses the arguments to send an EmailMultiAlternatives. Can be overridden to customize how the email is sent to the user.
By default, save() populates the context with the same variables that PasswordResetView passes to its email context.


Uses the arguments to send an EmailMultiAlternatives. Can be overridden to customize how the email is sent to the user.
By default, save() populates the context with the same variables that PasswordResetView passes to its email context.


A form that lets a user change their password without entering the old password.


A form used in the admin interface to change a user’s information and permissions.


A ModelForm for creating a new user.
It has three fields: username (from the user model), password1, and password2. It verifies that password1 and password2 match, validates the password using validate_password(), and sets the user’s password using set_password().


Returns the user model instance associated with the given request’s session.
It checks if the authentication backend stored in the session is present in AUTHENTICATION_BACKENDS. If so, it uses the backend’s get_user() method to retrieve the user model instance and then verifies the session by calling the user model’s get_session_auth_hash() method.
Returns an instance of AnonymousUser if the authentication backend stored in the session is no longer in AUTHENTICATION_BACKENDS, if a user isn’t returned by the backend’s get_user() method, or if the session auth hash doesn’t validate.


Instead of referring to User directly, you should reference the user model using django.contrib.auth.get_user_model(). This method will return the currently active user model – the custom user model if one is specified, or User otherwise.
When you define a foreign key or many-to-many relations to the user model, you should specify the custom model using the AUTH_USER_MODEL setting. For example:
When connecting to signals sent by the user model, you should specify the custom model using the AUTH_USER_MODEL setting. For example:
Generally speaking, it’s easiest to refer to the user model with the AUTH_USER_MODEL setting in code that’s executed at import time, however, it’s also possible to call get_user_model() while Django is importing models, so you could use models.ForeignKey(get_user_model(), ...).
If your app is tested with multiple user models, using @override_settings(AUTH_USER_MODEL=...) for example, and you cache the result of get_user_model() in a module-level variable, you may need to listen to the setting_changed signal to clear the cache. For example:


If you’d like to manually authenticate a user by comparing a plain-text password to the hashed password in the database, use the convenience function check_password(). It takes two arguments: the plain-text password to check, and the full value of a user’s password field in the database to check against, and returns True if they match, False otherwise.


Returns False if the password is a result of User.set_unusable_password().


Creates a hashed password in the format used by this application. It takes one mandatory argument: the password in plain-text (string or bytes). Optionally, you can provide a salt and a hashing algorithm to use, if you don’t want to use the defaults (first entry of PASSWORD_HASHERS setting). See Included hashers for the algorithm name of each hasher. If the password argument is None, an unusable password is returned (one that will never be accepted by check_password()).


Returns True if the user account is currently active.


Returns True if the user is allowed to have access to the admin site.


To log a user in, from a view, use login(). It takes an HttpRequest object and a User object. login() saves the user’s ID in the session, using Django’s session framework.
Note that any data set during the anonymous session is retained in the session after a user logs in.
This example shows how you might use both authenticate() and login():


To log out a user who has been logged in via django.contrib.auth.login(), use django.contrib.auth.logout() within your view. It takes an HttpRequest object and has no return value. Example:
Note that logout() doesn’t throw any errors if the user wasn’t logged in.
When you call logout(), the session data for the current request is completely cleaned out. All existing data is removed. This is to prevent another person from using the same web browser to log in and have access to the previous user’s session data. If you want to put anything into the session that will be available to the user immediately after logging out, do that after calling django.contrib.auth.logout().


Default return value for get_login_url(). Defaults to None in which case get_login_url() falls back to settings.LOGIN_URL.
Default return value for get_permission_denied_message(). Defaults to an empty string.
Default return value for get_redirect_field_name(). Defaults to "next".
If this attribute is set to True, a PermissionDenied exception is raised when the conditions are not met. When False (the default), anonymous users are redirected to the login page.
Returns the URL that users who don’t pass the test will be redirected to. Returns login_url if set, or settings.LOGIN_URL otherwise.
When raise_exception is True, this method can be used to control the error message passed to the error handler for display to the user. Returns the permission_denied_message attribute by default.
Returns the name of the query parameter that will contain the URL the user should be redirected to after a successful login. If you set this to None, a query parameter won’t be added. Returns the redirect_field_name attribute by default.
Depending on the value of raise_exception, the method either raises a PermissionDenied exception or redirects the user to the login_url, optionally including the redirect_field_name if it is set.


Returns the URL that users who don’t pass the test will be redirected to. Returns login_url if set, or settings.LOGIN_URL otherwise.


When raise_exception is True, this method can be used to control the error message passed to the error handler for display to the user. Returns the permission_denied_message attribute by default.


Returns the name of the query parameter that will contain the URL the user should be redirected to after a successful login. If you set this to None, a query parameter won’t be added. Returns the redirect_field_name attribute by default.


Depending on the value of raise_exception, the method either raises a PermissionDenied exception or redirects the user to the login_url, optionally including the redirect_field_name if it is set.


Default return value for get_login_url(). Defaults to None in which case get_login_url() falls back to settings.LOGIN_URL.


Default return value for get_permission_denied_message(). Defaults to an empty string.


If this attribute is set to True, a PermissionDenied exception is raised when the conditions are not met. When False (the default), anonymous users are redirected to the login page.


Default return value for get_redirect_field_name(). Defaults to "next".


If a view is using this mixin, all requests by non-authenticated users will be redirected to the login page or shown an HTTP 403 Forbidden error, depending on the raise_exception parameter.
You can set any of the parameters of AccessMixin to customize the handling of unauthorized users:


This mixin, just like the permission_required decorator, checks whether the user accessing a view has all given permissions. You should specify the permission (or an iterable of permissions) using the permission_required parameter:
You can set any of the parameters of AccessMixin to customize the handling of unauthorized users.
You may also override these methods:
Returns an iterable of permission names used by the mixin. Defaults to the permission_required attribute, converted to a tuple if necessary.
Returns a boolean denoting whether the current user has permission to execute the decorated view. By default, this returns the result of calling has_perms() with the list of permissions returned by get_permission_required().


Returns an iterable of permission names used by the mixin. Defaults to the permission_required attribute, converted to a tuple if necessary.


Returns a boolean denoting whether the current user has permission to execute the decorated view. By default, this returns the result of calling has_perms() with the list of permissions returned by get_permission_required().


When using class-based views, you can use the UserPassesTestMixin to do this.
You have to override the test_func() method of the class to provide the test that is performed. Furthermore, you can set any of the parameters of AccessMixin to customize the handling of unauthorized users:
You can also override the get_test_func() method to have the mixin use a differently named function for its checks (instead of test_func()).
Stacking UserPassesTestMixin
Due to the way UserPassesTestMixin is implemented, you cannot stack them in your inheritance list. The following does NOT work:
If TestMixin1 would call super() and take that result into account, TestMixin1 wouldn’t work standalone anymore.


You can also override the get_test_func() method to have the mixin use a differently named function for its checks (instead of test_func()).


You have to override the test_func() method of the class to provide the test that is performed. Furthermore, you can set any of the parameters of AccessMixin to customize the handling of unauthorized users:


Returns the value of the field nominated by USERNAME_FIELD.
Normalizes the username by calling normalize_username(). If you override this method, be sure to call super() to retain the normalization.
Returns the name of the email field specified by the EMAIL_FIELD attribute. Defaults to 'email' if EMAIL_FIELD isn’t specified.
Applies NFKC Unicode normalization to usernames so that visually identical characters with different Unicode code points are considered identical.
Read-only attribute which is always True (as opposed to AnonymousUser.is_authenticated which is always False). This is a way to tell if the user has been authenticated. This does not imply any permissions and doesn’t check if the user is active or has a valid session. Even though normally you will check this attribute on request.user to find out whether it has been populated by the AuthenticationMiddleware (representing the currently logged-in user), you should know this attribute is True for any User instance.
Read-only attribute which is always False. This is a way of differentiating User and AnonymousUser objects. Generally, you should prefer using is_authenticated to this attribute.
Sets the user’s password to the given raw string, taking care of the password hashing. Doesn’t save the AbstractBaseUser object.
When the raw_password is None, the password will be set to an unusable password, as if set_unusable_password() were used.
Returns True if the given raw string is the correct password for the user. (This takes care of the password hashing in making the comparison.)
Marks the user as having no password set. This isn’t the same as having a blank string for a password. check_password() for this user will never return True. Doesn’t save the AbstractBaseUser object.
You may need this if authentication for your application takes place against an existing external source such as an LDAP directory.
Returns False if set_unusable_password() has been called for this user.
Returns an HMAC of the password field. Used for Session invalidation on password change.


Returns True if the given raw string is the correct password for the user. (This takes care of the password hashing in making the comparison.)


Normalizes the username by calling normalize_username(). If you override this method, be sure to call super() to retain the normalization.


Returns an HMAC of the password field. Used for Session invalidation on password change.


Returns the value of the field nominated by USERNAME_FIELD.


Returns False if set_unusable_password() has been called for this user.


Read-only attribute which is always False. This is a way of differentiating User and AnonymousUser objects. Generally, you should prefer using is_authenticated to this attribute.


Read-only attribute which is always True (as opposed to AnonymousUser.is_authenticated which is always False). This is a way to tell if the user has been authenticated. This does not imply any permissions and doesn’t check if the user is active or has a valid session. Even though normally you will check this attribute on request.user to find out whether it has been populated by the AuthenticationMiddleware (representing the currently logged-in user), you should know this attribute is True for any User instance.


Sets the user’s password to the given raw string, taking care of the password hashing. Doesn’t save the AbstractBaseUser object.
When the raw_password is None, the password will be set to an unusable password, as if set_unusable_password() were used.


Marks the user as having no password set. This isn’t the same as having a blank string for a password. check_password() for this user will never return True. Doesn’t save the AbstractBaseUser object.
You may need this if authentication for your application takes place against an existing external source such as an LDAP directory.


Normalizes the email by calling BaseUserManager.normalize_email(). If you override this method, be sure to call super() to retain the normalization.


django.contrib.auth.models.AnonymousUser is a class that implements the django.contrib.auth.models.User interface, with these differences:


Normalizes email addresses by lowercasing the domain portion of the email address.
Retrieves a user instance using the contents of the field nominated by USERNAME_FIELD.
Returns a random password with the given length and given string of allowed characters. Note that the default value of allowed_chars doesn’t contain letters that can cause user confusion, including:


Retrieves a user instance using the contents of the field nominated by USERNAME_FIELD.


Returns a random password with the given length and given string of allowed characters. Note that the default value of allowed_chars doesn’t contain letters that can cause user confusion, including:


A string describing the name of the field on the user model that is used as the unique identifier. This will usually be a username of some kind, but it can also be an email address, or any other unique identifier. The field must be unique (i.e., have unique=True set in its definition), unless you use a custom authentication backend that can support non-unique usernames.
In the following example, the field identifier is used as the identifying field:
A string describing the name of the email field on the User model. This value is returned by get_email_field_name().
A list of the field names that will be prompted for when creating a user via the createsuperuser management command. The user will be prompted to supply a value for each of these fields. It must include any field for which blank is False or undefined and may include additional fields you want prompted for when a user is created interactively. REQUIRED_FIELDS has no effect in other parts of Django, like creating a user in the admin.
For example, here is the partial definition for a user model that defines two required fields - a date of birth and height:
Note
REQUIRED_FIELDS must contain all required fields on your user model, but should not contain the USERNAME_FIELD or password as these fields will always be prompted for.
A boolean attribute that indicates whether the user is considered “active”. This attribute is provided as an attribute on AbstractBaseUser defaulting to True. How you choose to implement it will depend on the details of your chosen auth backends. See the documentation of the is_active attribute on the built-in
user model for details.
Optional. A longer formal identifier for the user such as their full name. If implemented, this appears alongside the username in an object’s history in django.contrib.admin.
Optional. A short, informal identifier for the user such as their first name. If implemented, this replaces the username in the greeting to the user in the header of django.contrib.admin.
Importing AbstractBaseUser
AbstractBaseUser and BaseUserManager are importable from django.contrib.auth.base_user so that they can be imported without including django.contrib.auth in INSTALLED_APPS.


A string describing the name of the email field on the User model. This value is returned by get_email_field_name().


Optional. A longer formal identifier for the user such as their full name. If implemented, this appears alongside the username in an object’s history in django.contrib.admin.


Optional. A short, informal identifier for the user such as their first name. If implemented, this replaces the username in the greeting to the user in the header of django.contrib.admin.


A boolean attribute that indicates whether the user is considered “active”. This attribute is provided as an attribute on AbstractBaseUser defaulting to True. How you choose to implement it will depend on the details of your chosen auth backends. See the documentation of the is_active attribute on the built-in
user model for details.


A list of the field names that will be prompted for when creating a user via the createsuperuser management command. The user will be prompted to supply a value for each of these fields. It must include any field for which blank is False or undefined and may include additional fields you want prompted for when a user is created interactively. REQUIRED_FIELDS has no effect in other parts of Django, like creating a user in the admin.
For example, here is the partial definition for a user model that defines two required fields - a date of birth and height:
Note
REQUIRED_FIELDS must contain all required fields on your user model, but should not contain the USERNAME_FIELD or password as these fields will always be prompted for.


A string describing the name of the field on the user model that is used as the unique identifier. This will usually be a username of some kind, but it can also be an email address, or any other unique identifier. The field must be unique (i.e., have unique=True set in its definition), unless you use a custom authentication backend that can support non-unique usernames.
In the following example, the field identifier is used as the identifying field:


The prototype of create_user() should accept the username field, plus all required fields as arguments. For example, if your user model uses email as the username field, and has date_of_birth as a required field, then create_user should be defined as:
The prototype of create_superuser() should accept the username field, plus all required fields as arguments. For example, if your user model uses email as the username field, and has date_of_birth as a required field, then create_superuser should be defined as:


The prototype of create_superuser() should accept the username field, plus all required fields as arguments. For example, if your user model uses email as the username field, and has date_of_birth as a required field, then create_superuser should be defined as:


The prototype of create_user() should accept the username field, plus all required fields as arguments. For example, if your user model uses email as the username field, and has date_of_birth as a required field, then create_user should be defined as:


Required. 150 characters or fewer. Any characters are permitted. Example: 'Awesome Users'.


Required. 100 characters or fewer. Example: 'can_vote'.


Required. A reference to the django_content_type database table, which contains a record for each installed model.


Required. 255 characters or fewer. Example: 'Can vote'.


Boolean. Designates that this user has all permissions without explicitly assigning them.
Returns a set of permission strings that the user has directly.
If obj is passed in, only returns the user permissions for this specific object.
Returns a set of permission strings that the user has, through their groups.
If obj is passed in, only returns the group permissions for this specific object.
Returns a set of permission strings that the user has, both through group and user permissions.
If obj is passed in, only returns the permissions for this specific object.
Returns True if the user has the specified permission, where perm is in the format "<app label>.<permission codename>" (see permissions). If User.is_active and is_superuser are both True, this method always returns True.
If obj is passed in, this method won’t check for a permission for the model, but for this specific object.
Returns True if the user has each of the specified permissions, where each perm is in the format "<app label>.<permission codename>". If User.is_active and is_superuser are both True, this method always returns True.
If obj is passed in, this method won’t check for permissions for the model, but for the specific object.
Returns True if the user has any permissions in the given package (the Django app label). If User.is_active and is_superuser are both True, this method always returns True.


Returns a set of permission strings that the user has, both through group and user permissions.
If obj is passed in, only returns the permissions for this specific object.


Returns a set of permission strings that the user has, through their groups.
If obj is passed in, only returns the group permissions for this specific object.


Returns a set of permission strings that the user has directly.
If obj is passed in, only returns the user permissions for this specific object.


Returns True if the user has any permissions in the given package (the Django app label). If User.is_active and is_superuser are both True, this method always returns True.


Returns True if the user has the specified permission, where perm is in the format "<app label>.<permission codename>" (see permissions). If User.is_active and is_superuser are both True, this method always returns True.
If obj is passed in, this method won’t check for a permission for the model, but for this specific object.


Returns True if the user has each of the specified permissions, where each perm is in the format "<app label>.<permission codename>". If User.is_active and is_superuser are both True, this method always returns True.
If obj is passed in, this method won’t check for permissions for the model, but for the specific object.


Boolean. Designates that this user has all permissions without explicitly assigning them.


Returns True if the given raw string is the correct password for the user. (This takes care of the password hashing in making the comparison.)


A datetime designating when the account was created. Is set to the current date/time by default when the account is created.


Sends an email to the user. If from_email is None, Django uses the DEFAULT_FROM_EMAIL. Any **kwargs are passed to the underlying send_mail() call.


Optional (blank=True). 150 characters or fewer.


Returns the first_name plus the last_name, with a space in between.


Returns the username for the user. Since the User model can be swapped out, you should use this method instead of referencing the username attribute directly.