Optional.
This attribute defines the protocol ('http' or 'https') of the URLs in the sitemap. If it isn’t set, the protocol with which the sitemap was requested is used. If the sitemap is built outside the context of a request, the default is 'http'.
Deprecated since version 4.0: The default protocol for sitemaps built outside the context of a request will change from 'http' to 'https' in Django 5.0.


Optional.
A boolean attribute. When True the alternate links generated by alternates will contain a hreflang="x-default" fallback entry with a value of LANGUAGE_CODE. The default is False.


A model for storing the domain and name attributes of a website.
The fully qualified domain name associated with the website. For example, www.example.com.
A human-readable “verbose” name for the website.


The fully qualified domain name associated with the website. For example, www.example.com.


A human-readable “verbose” name for the website.


A class that shares the primary interface of Site (i.e., it has domain and name attributes) but gets its data from a Django HttpRequest object rather than from a database.
Sets the name and domain attributes to the value of get_host().


Sets the name and domain attributes to the value of get_host().


A function that checks if django.contrib.sites is installed and returns either the current Site object or a RequestSite object based on the request. It looks up the current site based on request.get_host() if the SITE_ID setting is not defined.
Both a domain and a port may be returned by request.get_host() when the Host header has a port explicitly specified, e.g. example.com:80. In such cases, if the lookup fails because the host does not match a record in the database, the port is stripped and the lookup is retried with the domain part only. This does not apply to RequestSite which will always use the unmodified host.


There is also a way to pass additional information to title and description templates, if you need to supply more than the two variables mentioned before. You can provide your implementation of get_context_data method in your Feed subclass. For example:


A common paradigm for optimizing performance in database systems is the use of tablespaces to organize disk layout.
Warning
Django does not create the tablespaces for you. Please refer to your database engine’s documentation for details on creating and managing tablespaces.
A tablespace can be specified for the table generated by a model by supplying the db_tablespace option inside the model’s class Meta. This option also affects tables automatically created for ManyToManyFields in the model.
You can use the DEFAULT_TABLESPACE setting to specify a default value for db_tablespace. This is useful for setting a tablespace for the built-in Django apps and other applications whose code you cannot control.
You can pass the db_tablespace option to an Index constructor to specify the name of a tablespace to use for the index. For single field indexes, you can pass the db_tablespace option to a Field constructor to specify an alternate tablespace for the field’s column index. If the column doesn’t have an index, the option is ignored.
You can use the DEFAULT_INDEX_TABLESPACE setting to specify a default value for db_tablespace.
If db_tablespace isn’t specified and you didn’t set DEFAULT_INDEX_TABLESPACE, the index is created in the same tablespace as the tables.
In this example, the tables generated by the TablespaceExample model (i.e. the model table and the many-to-many table) would be stored in the tables tablespace. The index for the name field and the indexes on the many-to-many table would be stored in the indexes tablespace. The data field would also generate an index, but no tablespace for it is specified, so it would be stored in the model tablespace tables by default. The index for the shortcut field would be stored in the other_indexes tablespace.
PostgreSQL and Oracle support tablespaces. SQLite, MariaDB and MySQL don’t.
When you use a backend that lacks support for tablespaces, Django ignores all tablespace-related options.


Renders this template with a given context.
If context is provided, it must be a dict. If it isn’t provided, the engine will render the template with an empty context.
If request is provided, it must be an HttpRequest. Then the engine must make it, as well as the CSRF token, available in the template. How this is achieved is up to each backend.


The path to the template as returned by the template loader. For loaders that read from the file system, this is the full path to the template.
If the template is instantiated directly rather than through a template loader, this is a string value of <unknown_source>.
The relative path to the template as passed into the template loader.
If the template is instantiated directly rather than through a template loader, this is None.
The template loader instance that constructed this Origin.
If the template is instantiated directly rather than through a template loader, this is None.
django.template.loaders.cached.Loader requires all of its wrapped loaders to set this attribute, typically by instantiating the Origin with loader=self.


The template loader instance that constructed this Origin.
If the template is instantiated directly rather than through a template loader, this is None.
django.template.loaders.cached.Loader requires all of its wrapped loaders to set this attribute, typically by instantiating the Origin with loader=self.


The path to the template as returned by the template loader. For loaders that read from the file system, this is the full path to the template.
If the template is instantiated directly rather than through a template loader, this is a string value of <unknown_source>.


The relative path to the template as passed into the template loader.
If the template is instantiated directly rather than through a template loader, this is None.


The constructor of django.template.Context takes an optional argument — a dictionary mapping variable names to variable values.
For details, see Playing with Context objects below.


Returns the value for key if key is in the context, else returns otherwise.


If key is in the context, returns its value. Otherwise inserts key with a value of default and returns default.


When instantiating an Engine all arguments must be passed as keyword arguments:
dirs is a list of directories where the engine should look for template source files. It is used to configure filesystem.Loader.
It defaults to an empty list.
app_dirs only affects the default value of loaders. See below.
It defaults to False.
autoescape controls whether HTML autoescaping is enabled.
It defaults to True.
Warning
Only set it to False if you’re rendering non-HTML templates!
context_processors is a list of dotted Python paths to callables that are used to populate the context when a template is rendered with a request. These callables take a request object as their argument and return a dict of items to be merged into the context.
It defaults to an empty list.
See RequestContext for more information.
debug is a boolean that turns on/off template debug mode. If it is True, the template engine will store additional debug information which can be used to display a detailed report for any exception raised during template rendering.
It defaults to False.
loaders is a list of template loader classes, specified as strings. Each Loader class knows how to import templates from a particular source. Optionally, a tuple can be used instead of a string. The first item in the tuple should be the Loader class name, subsequent items are passed to the Loader during initialization.
It defaults to a list containing:
If debug is False, these loaders are wrapped in django.template.loaders.cached.Loader.
See Loader types for details.
string_if_invalid is the output, as a string, that the template system should use for invalid (e.g. misspelled) variables.
It defaults to the empty string.
See How invalid variables are handled for details.
file_charset is the charset used to read template files on disk.
It defaults to 'utf-8'.
'libraries': A dictionary of labels and dotted Python paths of template tag modules to register with the template engine. This is used to add new libraries or provide alternate labels for existing ones. For example:
Libraries can be loaded by passing the corresponding dictionary key to the {% load %} tag.
'builtins': A list of dotted Python paths of template tag modules to add to built-ins. For example:
Tags and filters from built-in libraries can be used without first calling the {% load %} tag.


Compiles the given template code and returns a Template object.


Loads a template with the given name, compiles it and returns a Template object.


Like get_template(), except it takes a list of names and returns the first template that was found.


Template engines are available in django.template.engines:
The lookup key — 'django' in this example — is the engine’s NAME.


This function loads the template with the given name and returns a Template object.
The exact type of the return value depends on the backend that loaded the template. Each backend has its own Template class.
get_template() tries each template engine in order until one succeeds. If the template cannot be found, it raises TemplateDoesNotExist. If the template is found but contains invalid syntax, it raises TemplateSyntaxError.
How templates are searched and loaded depends on each engine’s backend and configuration.
If you want to restrict the search to a particular template engine, pass the engine’s NAME in the using argument.


render_to_string() loads a template like get_template() and calls its render() method immediately. It takes the following arguments.
Usage example:


select_template() is just like get_template(), except it takes a list of template names. It tries each name in order and returns the first template that exists.


Loads templates from Django apps on the filesystem. For each app in INSTALLED_APPS, the loader looks for a templates subdirectory. If the directory exists, Django looks for templates in there.
This means you can store templates with your individual apps. This also helps to distribute Django apps with default templates.
For example, for this setting:
…then get_template('foo.html') will look for foo.html in these directories, in this order:
… and will use the one it finds first.
The order of INSTALLED_APPS is significant! For example, if you want to customize the Django admin, you might choose to override the standard admin/base_site.html template, from django.contrib.admin, with your own admin/base_site.html in myproject.polls. You must then make sure that your myproject.polls comes before django.contrib.admin in INSTALLED_APPS, otherwise django.contrib.admin’s will be loaded first and yours will be ignored.
Note that the loader performs an optimization when it first runs: it caches a list of which INSTALLED_APPS packages have a templates subdirectory.
You can enable this loader by setting APP_DIRS to True:


Loads templates from a given source, such as the filesystem or a database.
A method that takes a template_name and yields Origin instances for each possible source.
For example, the filesystem loader may receive 'index.html' as a template_name argument. This method would yield origins for the full path of index.html as it appears in each template directory the loader looks at.
The method doesn’t need to verify that the template exists at a given path, but it should ensure the path is valid. For instance, the filesystem loader makes sure the path lies under a valid template directory.
Returns the contents for a template given a Origin instance.
This is where a filesystem loader would read contents from the filesystem, or a database loader would read from the database. If a matching template doesn’t exist, this should raise a TemplateDoesNotExist error.
Returns a Template object for a given template_name by looping through results from get_template_sources() and calling get_contents(). This returns the first matching template. If no template is found, TemplateDoesNotExist is raised.
The optional skip argument is a list of origins to ignore when extending templates. This allow templates to extend other templates of the same name. It also used to avoid recursion errors.
In general, it is enough to define get_template_sources() and get_contents() for custom template loaders. get_template() will usually not need to be overridden.


Returns the contents for a template given a Origin instance.
This is where a filesystem loader would read contents from the filesystem, or a database loader would read from the database. If a matching template doesn’t exist, this should raise a TemplateDoesNotExist error.


Returns a Template object for a given template_name by looping through results from get_template_sources() and calling get_contents(). This returns the first matching template. If no template is found, TemplateDoesNotExist is raised.
The optional skip argument is a list of origins to ignore when extending templates. This allow templates to extend other templates of the same name. It also used to avoid recursion errors.
In general, it is enough to define get_template_sources() and get_contents() for custom template loaders. get_template() will usually not need to be overridden.


A method that takes a template_name and yields Origin instances for each possible source.
For example, the filesystem loader may receive 'index.html' as a template_name argument. This method would yield origins for the full path of index.html as it appears in each template directory the loader looks at.
The method doesn’t need to verify that the template exists at a given path, but it should ensure the path is valid. For instance, the filesystem loader makes sure the path lies under a valid template directory.


By default (when DEBUG is True), the template system reads and compiles your templates every time they’re rendered. While the Django template system is quite fast, the overhead from reading and compiling templates can add up.
You configure the cached template loader with a list of other loaders that it should wrap. The wrapped loaders are used to locate unknown templates when they’re first encountered. The cached loader then stores the compiled Template in memory. The cached Template instance is returned for subsequent requests to load the same template.
This loader is automatically enabled if OPTIONS['loaders'] isn’t specified and OPTIONS['debug'] is False (the latter option defaults to the value of DEBUG).
You can also enable template caching with some custom template loaders using settings like this:
Note
All of the built-in Django template tags are safe to use with the cached loader, but if you’re using custom template tags that come from third party packages, or that you wrote yourself, you should ensure that the Node implementation for each tag is thread-safe. For more information, see template tag thread safety considerations.


Loads templates from the filesystem, according to DIRS.
This loader is enabled by default. However it won’t find any templates until you set DIRS to a non-empty list:
You can also override 'DIRS' and specify specific directories for a particular filesystem loader:


Loads templates from a Python dictionary. This is useful for testing.
This loader takes a dictionary of templates as its first argument:
This loader is disabled by default.


Instantiates a SimpleTemplateResponse object with the given template, context, content type, HTTP status, and charset.
The headers parameter was added.


Add a callback that will be invoked after rendering has taken place. This hook can be used to defer certain processing operations (such as caching) until after rendering has occurred.
If the SimpleTemplateResponse has already been rendered, the callback will be invoked immediately.
When called, callbacks will be passed a single argument – the rendered SimpleTemplateResponse instance.
If the callback returns a value that is not None, this will be used as the response instead of the original response object (and will be passed to the next post rendering callback etc.)


The context data to be used when rendering the template. It must be a dict.
Example: {'foo': 123}


A boolean indicating whether the response content has been rendered.


Sets response.content to the result obtained by SimpleTemplateResponse.rendered_content, runs all post-rendering callbacks, and returns the resulting response object.
render() will only have an effect the first time it is called. On subsequent calls, it will return the result obtained from the first call.


The current rendered value of the response content, using the current template and context data.


Preprocesses context data that will be used for rendering a template. Accepts a dict of context data. By default, returns the same dict.
Override this method in order to customize the context.


Resolves the template instance to use for rendering. Accepts a backend-dependent template object (such as those returned by get_template()), the name of a template, or a list of template names.
Returns the backend-dependent template object instance to be rendered.
Override this method in order to customize template loading.


The name of the template to be rendered. Accepts a backend-dependent template object (such as those returned by get_template()), the name of a template, or a list of template names.
Example: ['foo.html', 'path/to/bar.html']


TemplateResponse is a subclass of SimpleTemplateResponse that knows about the current HttpRequest.


Instantiates a TemplateResponse object with the given request, template, context, content type, HTTP status, and charset.
The headers parameter was added.


This class lives at django.template.Template. The constructor takes one argument — the raw template code:


Call the Template object’s render() method with a Context to “fill” the template:


Django’s template engine provides a powerful mini-language for defining the user-facing layer of your application, encouraging a clean separation of application and presentation logic. Templates can be maintained by anyone with an understanding of HTML; no knowledge of Python is required. For introductory material, see Templates topic guide.
See also
For information on writing your own custom tags and filters, see How to create custom template tags and filters.
To learn how to override templates in other Django applications, see How to override templates.


Being a web framework, Django needs a convenient way to generate HTML dynamically. The most common approach relies on templates. A template contains the static parts of the desired HTML output as well as some special syntax describing how dynamic content will be inserted. For a hands-on example of creating HTML pages with templates, see Tutorial 3.
A Django project can be configured with one or several template engines (or even zero if you don’t use templates). Django ships built-in backends for its own template system, creatively called the Django template language (DTL), and for the popular alternative Jinja2. Backends for other template languages may be available from third-parties. You can also write your own custom backend, see Custom template backend
Django defines a standard API for loading and rendering templates regardless of the backend. Loading consists of finding the template for a given identifier and preprocessing it, usually compiling it to an in-memory representation. Rendering means interpolating the template with context data and returning the resulting string.
The Django template language is Django’s own template system. Until Django 1.8 it was the only built-in option available. It’s a good template library even though it’s fairly opinionated and sports a few idiosyncrasies. If you don’t have a pressing reason to choose another backend, you should use the DTL, especially if you’re writing a pluggable application and you intend to distribute templates. Django’s contrib apps that include templates, like django.contrib.admin, use the DTL.
For historical reasons, both the generic support for template engines and the implementation of the Django template language live in the django.template namespace.
Warning
The template system isn’t safe against untrusted template authors. For example, a site shouldn’t allow its users to provide their own templates, since template authors can do things like perform XSS attacks and access properties of template variables that may contain sensitive information.
About this section
This is an overview of the Django template language’s syntax. For details see the language syntax reference.
A Django template is a text document or a Python string marked-up using the Django template language. Some constructs are recognized and interpreted by the template engine. The main ones are variables and tags.
A template is rendered with a context. Rendering replaces variables with their values, which are looked up in the context, and executes tags. Everything else is output as is.
The syntax of the Django template language involves four constructs.
A variable outputs a value from the context, which is a dict-like object mapping keys to values.
Variables are surrounded by {{ and }} like this:
With a context of {'first_name': 'John', 'last_name': 'Doe'}, this template renders to:
Dictionary lookup, attribute lookup and list-index lookups are implemented with a dot notation:
If a variable resolves to a callable, the template system will call it with no arguments and use its result instead of the callable.
Tags provide arbitrary logic in the rendering process.
This definition is deliberately vague. For example, a tag can output content, serve as a control structure e.g. an “if” statement or a “for” loop, grab content from a database, or even enable access to other template tags.
Tags are surrounded by {% and %} like this:
Most tags accept arguments:
Some tags require beginning and ending tags:
A reference of built-in tags is available as well as instructions for writing custom tags.
Filters transform the values of variables and tag arguments.
They look like this:
With a context of {'django': 'the web framework for perfectionists with
deadlines'}, this template renders to:
Some filters take an argument:
A reference of built-in filters is available as well as instructions for writing custom filters.
Comments look like this:
A {% comment %} tag provides multi-line comments.
About this section
This is an overview of the Django template language’s APIs. For details see the API reference.
django.template.Engine encapsulates an instance of the Django template system. The main reason for instantiating an Engine directly is to use the Django template language outside of a Django project.
django.template.backends.django.DjangoTemplates is a thin wrapper adapting django.template.Engine to Django’s template backend API.
django.template.Template represents a compiled template. Templates are obtained with Engine.get_template() or Engine.from_string().
Likewise django.template.backends.django.Template is a thin wrapper adapting django.template.Template to the common template API.
django.template.Context holds some metadata in addition to the context data. It is passed to Template.render() for rendering a template.
django.template.RequestContext is a subclass of Context that stores the current HttpRequest and runs template context processors.
The common API doesn’t have an equivalent concept. Context data is passed in a plain dict and the current HttpRequest is passed separately if needed.
Template loaders are responsible for locating templates, loading them, and returning Template objects.
Django provides several built-in template loaders and supports custom template loaders.
Context processors are functions that receive the current HttpRequest as an argument and return a dict of data to be added to the rendering context.
Their main use is to add common data shared by all templates to the context without repeating code in every view.
Django provides many built-in context processors, and you can implement your own additional context processors, too.
Templates engines are configured with the TEMPLATES setting. It’s a list of configurations, one for each engine. The default value is empty. The settings.py generated by the startproject command defines a more useful value:
BACKEND is a dotted Python path to a template engine class implementing Django’s template backend API. The built-in backends are django.template.backends.django.DjangoTemplates and django.template.backends.jinja2.Jinja2.
Since most engines load templates from files, the top-level configuration for each engine contains two common settings:
While uncommon, it’s possible to configure several instances of the same backend with different options. In that case you should define a unique NAME for each engine.
OPTIONS contains backend-specific settings.
The django.template.loader module defines two functions to load templates.
This function loads the template with the given name and returns a Template object.
The exact type of the return value depends on the backend that loaded the template. Each backend has its own Template class.
get_template() tries each template engine in order until one succeeds. If the template cannot be found, it raises TemplateDoesNotExist. If the template is found but contains invalid syntax, it raises TemplateSyntaxError.
How templates are searched and loaded depends on each engine’s backend and configuration.
If you want to restrict the search to a particular template engine, pass the engine’s NAME in the using argument.
select_template() is just like get_template(), except it takes a list of template names. It tries each name in order and returns the first template that exists.
If loading a template fails, the following two exceptions, defined in django.template, may be raised:
This exception is raised when a template cannot be found. It accepts the following optional arguments for populating the template postmortem on the debug page:
This exception is raised when a template was found but contains errors.
Template objects returned by get_template() and select_template() must provide a render() method with the following signature:
Renders this template with a given context.
If context is provided, it must be a dict. If it isn’t provided, the engine will render the template with an empty context.
If request is provided, it must be an HttpRequest. Then the engine must make it, as well as the CSRF token, available in the template. How this is achieved is up to each backend.
Here’s an example of the search algorithm. For this example the TEMPLATES setting is:
If you call get_template('story_detail.html'), here are the files Django will look for, in order:
If you call select_template(['story_253_detail.html', 'story_detail.html']), here’s what Django will look for:
When Django finds a template that exists, it stops looking.
Tip
You can use select_template() for flexible template loading. For example, if you’ve written a news story and want some stories to have custom templates, use something like select_template(['story_%s_detail.html' % story.id,
'story_detail.html']). That’ll allow you to use a custom template for an individual story, with a fallback template for stories that don’t have custom templates.
It’s possible – and preferable – to organize templates in subdirectories inside each directory containing templates. The convention is to make a subdirectory for each Django app, with subdirectories within those subdirectories as needed.
Do this for your own sanity. Storing all templates in the root level of a single directory gets messy.
To load a template that’s within a subdirectory, use a slash, like so:
Using the same TEMPLATES option as above, this will attempt to load the following templates:
In addition, to cut down on the repetitive nature of loading and rendering templates, Django provides a shortcut function which automates the process.
render_to_string() loads a template like get_template() and calls its render() method immediately. It takes the following arguments.
Usage example:
See also the render() shortcut which calls render_to_string() and feeds the result into an HttpResponse suitable for returning from a view.
Finally, you can use configured engines directly:
Template engines are available in django.template.engines:
The lookup key — 'django' in this example — is the engine’s NAME.
Set BACKEND to 'django.template.backends.django.DjangoTemplates' to configure a Django template engine.
When APP_DIRS is True, DjangoTemplates engines look for templates in the templates subdirectory of installed applications. This generic name was kept for backwards-compatibility.
DjangoTemplates engines accept the following OPTIONS:
'autoescape': a boolean that controls whether HTML autoescaping is enabled.
It defaults to True.
Warning
Only set it to False if you’re rendering non-HTML templates!
'context_processors': a list of dotted Python paths to callables that are used to populate the context when a template is rendered with a request. These callables take a request object as their argument and return a dict of items to be merged into the context.
It defaults to an empty list.
See RequestContext for more information.
'debug': a boolean that turns on/off template debug mode. If it is True, the fancy error page will display a detailed report for any exception raised during template rendering. This report contains the relevant snippet of the template with the appropriate line highlighted.
It defaults to the value of the DEBUG setting.
'loaders': a list of dotted Python paths to template loader classes. Each Loader class knows how to import templates from a particular source. Optionally, a tuple can be used instead of a string. The first item in the tuple should be the Loader class name, and subsequent items are passed to the Loader during initialization.
The default depends on the values of DIRS and APP_DIRS.
See Loader types for details.
'string_if_invalid': the output, as a string, that the template system should use for invalid (e.g. misspelled) variables.
It defaults to an empty string.
See How invalid variables are handled for details.
'file_charset': the charset used to read template files on disk.
It defaults to 'utf-8'.
'libraries': A dictionary of labels and dotted Python paths of template tag modules to register with the template engine. This can be used to add new libraries or provide alternate labels for existing ones. For example:
Libraries can be loaded by passing the corresponding dictionary key to the {% load %} tag.
'builtins': A list of dotted Python paths of template tag modules to add to built-ins. For example:
Tags and filters from built-in libraries can be used without first calling the {% load %} tag.
Requires Jinja2 to be installed:
Set BACKEND to 'django.template.backends.jinja2.Jinja2' to configure a Jinja2 engine.
When APP_DIRS is True, Jinja2 engines look for templates in the jinja2 subdirectory of installed applications.
The most important entry in OPTIONS is 'environment'. It’s a dotted Python path to a callable returning a Jinja2 environment. It defaults to 'jinja2.Environment'. Django invokes that callable and passes other options as keyword arguments. Furthermore, Django adds defaults that differ from Jinja2’s for a few options:
Jinja2 engines also accept the following OPTIONS:
'context_processors': a list of dotted Python paths to callables that are used to populate the context when a template is rendered with a request. These callables take a request object as their argument and return a dict of items to be merged into the context.
It defaults to an empty list.
Using context processors with Jinja2 templates is discouraged.
Context processors are useful with Django templates because Django templates don’t support calling functions with arguments. Since Jinja2 doesn’t have that limitation, it’s recommended to put the function that you would use as a context processor in the global variables available to the template using jinja2.Environment as described below. You can then call that function in the template:
Some Django templates context processors return a fixed value. For Jinja2 templates, this layer of indirection isn’t necessary since you can add constants directly in jinja2.Environment.
The original use case for adding context processors for Jinja2 involved:
Unless all of these conditions are met, passing a function to the template is more in line with the design of Jinja2.
The default configuration is purposefully kept to a minimum. If a template is rendered with a request (e.g. when using render()), the Jinja2 backend adds the globals request, csrf_input, and csrf_token to the context. Apart from that, this backend doesn’t create a Django-flavored environment. It doesn’t know about Django filters and tags. In order to use Django-specific APIs, you must configure them into the environment.
For example, you can create myproject/jinja2.py with this content:
and set the 'environment' option to 'myproject.jinja2.environment'.
Then you could use the following constructs in Jinja2 templates:
The concepts of tags and filters exist both in the Django template language and in Jinja2 but they’re used differently. Since Jinja2 supports passing arguments to callables in templates, many features that require a template tag or filter in Django templates can be achieved by calling a function in Jinja2 templates, as shown in the example above. Jinja2’s global namespace removes the need for template context processors. The Django template language doesn’t have an equivalent of Jinja2 tests.


It requires no arguments at time of construction. However, you can use keyword arguments to specify some default headers. For example, this will send a User-Agent HTTP header in each request:
The values from the extra keyword arguments passed to get(), post(), etc. have precedence over the defaults passed to the class constructor.
The enforce_csrf_checks argument can be used to test CSRF protection (see above).
The json_encoder argument allows setting a custom JSON encoder for the JSON serialization that’s described in post().
The raise_request_exception argument allows controlling whether or not exceptions raised during the request should also be raised in the test. Defaults to True.
Once you have a Client instance, you can call any of the following methods:
Makes a GET request on the provided path and returns a Response object, which is documented below.
The key-value pairs in the data dictionary are used to create a GET data payload. For example:
…will result in the evaluation of a GET request equivalent to:
The extra keyword arguments parameter can be used to specify headers to be sent in the request. For example:
…will send the HTTP header HTTP_ACCEPT to the details view, which is a good way to test code paths that use the django.http.HttpRequest.accepts() method.
CGI specification
The headers sent via **extra should follow CGI specification. For example, emulating a different “Host” header as sent in the HTTP request from the browser to the server should be passed as HTTP_HOST.
If you already have the GET arguments in URL-encoded form, you can use that encoding instead of using the data argument. For example, the previous GET request could also be posed as:
If you provide a URL with both an encoded GET data and a data argument, the data argument will take precedence.
If you set follow to True the client will follow any redirects and a redirect_chain attribute will be set in the response object containing tuples of the intermediate urls and status codes.
If you had a URL /redirect_me/ that redirected to /next/, that redirected to /final/, this is what you’d see:
If you set secure to True the client will emulate an HTTPS request.
Makes a POST request on the provided path and returns a Response object, which is documented below.
The key-value pairs in the data dictionary are used to submit POST data. For example:
…will result in the evaluation of a POST request to this URL:
…with this POST data:
If you provide content_type as application/json, the data is serialized using json.dumps() if it’s a dict, list, or tuple. Serialization is performed with DjangoJSONEncoder by default, and can be overridden by providing a json_encoder argument to Client. This serialization also happens for put(), patch(), and delete() requests.
If you provide any other content_type (e.g. text/xml for an XML payload), the contents of data are sent as-is in the POST request, using content_type in the HTTP Content-Type header.
If you don’t provide a value for content_type, the values in data will be transmitted with a content type of multipart/form-data. In this case, the key-value pairs in data will be encoded as a multipart message and used to create the POST data payload.
To submit multiple values for a given key – for example, to specify the selections for a <select multiple> – provide the values as a list or tuple for the required key. For example, this value of data would submit three selected values for the field named choices:
Submitting files is a special case. To POST a file, you need only provide the file field name as a key, and a file handle to the file you wish to upload as a value. For example:
(The name attachment here is not relevant; use whatever name your file-processing code expects.)
You may also provide any file-like object (e.g., StringIO or BytesIO) as a file handle. If you’re uploading to an ImageField, the object needs a name attribute that passes the validate_image_file_extension validator. For example:
Note that if you wish to use the same file handle for multiple post() calls then you will need to manually reset the file pointer between posts. The easiest way to do this is to manually close the file after it has been provided to post(), as demonstrated above.
You should also ensure that the file is opened in a way that allows the data to be read. If your file contains binary data such as an image, this means you will need to open the file in rb (read binary) mode.
The extra argument acts the same as for Client.get().
If the URL you request with a POST contains encoded parameters, these parameters will be made available in the request.GET data. For example, if you were to make the request:
… the view handling this request could interrogate request.POST to retrieve the username and password, and could interrogate request.GET to determine if the user was a visitor.
If you set follow to True the client will follow any redirects and a redirect_chain attribute will be set in the response object containing tuples of the intermediate urls and status codes.
If you set secure to True the client will emulate an HTTPS request.
Makes a HEAD request on the provided path and returns a Response object. This method works just like Client.get(), including the follow, secure and extra arguments, except it does not return a message body.
Makes an OPTIONS request on the provided path and returns a Response object. Useful for testing RESTful interfaces.
When data is provided, it is used as the request body, and a Content-Type header is set to content_type.
The follow, secure and extra arguments act the same as for Client.get().
Makes a PUT request on the provided path and returns a Response object. Useful for testing RESTful interfaces.
When data is provided, it is used as the request body, and a Content-Type header is set to content_type.
The follow, secure and extra arguments act the same as for Client.get().
Makes a PATCH request on the provided path and returns a Response object. Useful for testing RESTful interfaces.
The follow, secure and extra arguments act the same as for Client.get().
Makes a DELETE request on the provided path and returns a Response object. Useful for testing RESTful interfaces.
When data is provided, it is used as the request body, and a Content-Type header is set to content_type.
The follow, secure and extra arguments act the same as for Client.get().
Makes a TRACE request on the provided path and returns a Response object. Useful for simulating diagnostic probes.
Unlike the other request methods, data is not provided as a keyword parameter in order to comply with RFC 7231#section-4.3.8, which mandates that TRACE requests must not have a body.
The follow, secure, and extra arguments act the same as for Client.get().
If your site uses Django’s authentication system and you deal with logging in users, you can use the test client’s login() method to simulate the effect of a user logging into the site.
After you call this method, the test client will have all the cookies and session data required to pass any login-based tests that may form part of a view.
The format of the credentials argument depends on which authentication backend you’re using (which is configured by your AUTHENTICATION_BACKENDS setting). If you’re using the standard authentication backend provided by Django (ModelBackend), credentials should be the user’s username and password, provided as keyword arguments:
If you’re using a different authentication backend, this method may require different credentials. It requires whichever credentials are required by your backend’s authenticate() method.
login() returns True if it the credentials were accepted and login was successful.
Finally, you’ll need to remember to create user accounts before you can use this method. As we explained above, the test runner is executed using a test database, which contains no users by default. As a result, user accounts that are valid on your production site will not work under test conditions. You’ll need to create users as part of the test suite – either manually (using the Django model API) or with a test fixture. Remember that if you want your test user to have a password, you can’t set the user’s password by setting the password attribute directly – you must use the set_password() function to store a correctly hashed password. Alternatively, you can use the create_user() helper method to create a new user with a correctly hashed password.
If your site uses Django’s authentication system, you can use the force_login() method to simulate the effect of a user logging into the site. Use this method instead of login() when a test requires a user be logged in and the details of how a user logged in aren’t important.
Unlike login(), this method skips the authentication and verification steps: inactive users (is_active=False) are permitted to login and the user’s credentials don’t need to be provided.
The user will have its backend attribute set to the value of the backend argument (which should be a dotted Python path string), or to settings.AUTHENTICATION_BACKENDS[0] if a value isn’t provided. The authenticate() function called by login() normally annotates the user like this.
This method is faster than login() since the expensive password hashing algorithms are bypassed. Also, you can speed up login() by using a weaker hasher while testing.
If your site uses Django’s authentication system, the logout() method can be used to simulate the effect of a user logging out of your site.
After you call this method, the test client will have all the cookies and session data cleared to defaults. Subsequent requests will appear to come from an AnonymousUser.


A Python SimpleCookie object, containing the current values of all the client cookies. See the documentation of the http.cookies module for more.


Makes a DELETE request on the provided path and returns a Response object. Useful for testing RESTful interfaces.
When data is provided, it is used as the request body, and a Content-Type header is set to content_type.
The follow, secure and extra arguments act the same as for Client.get().


If your site uses Django’s authentication system, you can use the force_login() method to simulate the effect of a user logging into the site. Use this method instead of login() when a test requires a user be logged in and the details of how a user logged in aren’t important.
Unlike login(), this method skips the authentication and verification steps: inactive users (is_active=False) are permitted to login and the user’s credentials don’t need to be provided.
The user will have its backend attribute set to the value of the backend argument (which should be a dotted Python path string), or to settings.AUTHENTICATION_BACKENDS[0] if a value isn’t provided. The authenticate() function called by login() normally annotates the user like this.
This method is faster than login() since the expensive password hashing algorithms are bypassed. Also, you can speed up login() by using a weaker hasher while testing.


Makes a GET request on the provided path and returns a Response object, which is documented below.
The key-value pairs in the data dictionary are used to create a GET data payload. For example:
…will result in the evaluation of a GET request equivalent to:
The extra keyword arguments parameter can be used to specify headers to be sent in the request. For example:
…will send the HTTP header HTTP_ACCEPT to the details view, which is a good way to test code paths that use the django.http.HttpRequest.accepts() method.
CGI specification
The headers sent via **extra should follow CGI specification. For example, emulating a different “Host” header as sent in the HTTP request from the browser to the server should be passed as HTTP_HOST.
If you already have the GET arguments in URL-encoded form, you can use that encoding instead of using the data argument. For example, the previous GET request could also be posed as:
If you provide a URL with both an encoded GET data and a data argument, the data argument will take precedence.
If you set follow to True the client will follow any redirects and a redirect_chain attribute will be set in the response object containing tuples of the intermediate urls and status codes.
If you had a URL /redirect_me/ that redirected to /next/, that redirected to /final/, this is what you’d see:
If you set secure to True the client will emulate an HTTPS request.


Makes a HEAD request on the provided path and returns a Response object. This method works just like Client.get(), including the follow, secure and extra arguments, except it does not return a message body.


If your site uses Django’s authentication system and you deal with logging in users, you can use the test client’s login() method to simulate the effect of a user logging into the site.
After you call this method, the test client will have all the cookies and session data required to pass any login-based tests that may form part of a view.
The format of the credentials argument depends on which authentication backend you’re using (which is configured by your AUTHENTICATION_BACKENDS setting). If you’re using the standard authentication backend provided by Django (ModelBackend), credentials should be the user’s username and password, provided as keyword arguments:
If you’re using a different authentication backend, this method may require different credentials. It requires whichever credentials are required by your backend’s authenticate() method.
login() returns True if it the credentials were accepted and login was successful.
Finally, you’ll need to remember to create user accounts before you can use this method. As we explained above, the test runner is executed using a test database, which contains no users by default. As a result, user accounts that are valid on your production site will not work under test conditions. You’ll need to create users as part of the test suite – either manually (using the Django model API) or with a test fixture. Remember that if you want your test user to have a password, you can’t set the user’s password by setting the password attribute directly – you must use the set_password() function to store a correctly hashed password. Alternatively, you can use the create_user() helper method to create a new user with a correctly hashed password.


If your site uses Django’s authentication system, the logout() method can be used to simulate the effect of a user logging out of your site.
After you call this method, the test client will have all the cookies and session data cleared to defaults. Subsequent requests will appear to come from an AnonymousUser.


Makes an OPTIONS request on the provided path and returns a Response object. Useful for testing RESTful interfaces.
When data is provided, it is used as the request body, and a Content-Type header is set to content_type.
The follow, secure and extra arguments act the same as for Client.get().


Makes a PATCH request on the provided path and returns a Response object. Useful for testing RESTful interfaces.
The follow, secure and extra arguments act the same as for Client.get().


Makes a POST request on the provided path and returns a Response object, which is documented below.
The key-value pairs in the data dictionary are used to submit POST data. For example:
…will result in the evaluation of a POST request to this URL:
…with this POST data:
If you provide content_type as application/json, the data is serialized using json.dumps() if it’s a dict, list, or tuple. Serialization is performed with DjangoJSONEncoder by default, and can be overridden by providing a json_encoder argument to Client. This serialization also happens for put(), patch(), and delete() requests.
If you provide any other content_type (e.g. text/xml for an XML payload), the contents of data are sent as-is in the POST request, using content_type in the HTTP Content-Type header.
If you don’t provide a value for content_type, the values in data will be transmitted with a content type of multipart/form-data. In this case, the key-value pairs in data will be encoded as a multipart message and used to create the POST data payload.
To submit multiple values for a given key – for example, to specify the selections for a <select multiple> – provide the values as a list or tuple for the required key. For example, this value of data would submit three selected values for the field named choices:
Submitting files is a special case. To POST a file, you need only provide the file field name as a key, and a file handle to the file you wish to upload as a value. For example:
(The name attachment here is not relevant; use whatever name your file-processing code expects.)
You may also provide any file-like object (e.g., StringIO or BytesIO) as a file handle. If you’re uploading to an ImageField, the object needs a name attribute that passes the validate_image_file_extension validator. For example:
Note that if you wish to use the same file handle for multiple post() calls then you will need to manually reset the file pointer between posts. The easiest way to do this is to manually close the file after it has been provided to post(), as demonstrated above.
You should also ensure that the file is opened in a way that allows the data to be read. If your file contains binary data such as an image, this means you will need to open the file in rb (read binary) mode.
The extra argument acts the same as for Client.get().
If the URL you request with a POST contains encoded parameters, these parameters will be made available in the request.GET data. For example, if you were to make the request:
… the view handling this request could interrogate request.POST to retrieve the username and password, and could interrogate request.GET to determine if the user was a visitor.
If you set follow to True the client will follow any redirects and a redirect_chain attribute will be set in the response object containing tuples of the intermediate urls and status codes.
If you set secure to True the client will emulate an HTTPS request.


Makes a PUT request on the provided path and returns a Response object. Useful for testing RESTful interfaces.
When data is provided, it is used as the request body, and a Content-Type header is set to content_type.
The follow, secure and extra arguments act the same as for Client.get().


A dictionary-like object containing session information. See the session documentation for full details.
To modify the session and then save it, it must be stored in a variable first (because a new SessionStore is created every time this property is accessed):


Makes a TRACE request on the provided path and returns a Response object. Useful for simulating diagnostic probes.
Unlike the other request methods, data is not provided as a keyword parameter in order to comply with RFC 7231#section-4.3.8, which mandates that TRACE requests must not have a body.
The follow, secure, and extra arguments act the same as for Client.get().


The test client that was used to make the request that resulted in the response.
The body of the response, as a bytestring. This is the final page content as rendered by the view, or any error message.
The template Context instance that was used to render the template that produced the response content.
If the rendered page used multiple templates, then context will be a list of Context objects, in the order in which they were rendered.
Regardless of the number of templates used during rendering, you can retrieve context values using the [] operator. For example, the context variable name could be retrieved using:
Not using Django templates?
This attribute is only populated when using the DjangoTemplates backend. If you’re using another template engine, context_data may be a suitable alternative on responses with that attribute.
A tuple of three values that provides information about the unhandled exception, if any, that occurred during the view.
The values are (type, value, traceback), the same as returned by Python’s sys.exc_info(). Their meanings are:
If no exception occurred, then exc_info will be None.
The body of the response, parsed as JSON. Extra keyword arguments are passed to json.loads(). For example:
If the Content-Type header is not "application/json", then a ValueError will be raised when trying to parse the response.
The request data that stimulated the response.
The WSGIRequest instance generated by the test handler that generated the response.
The HTTP status of the response, as an integer. For a full list of defined codes, see the IANA status code registry.
A list of Template instances used to render the final content, in the order they were rendered. For each template in the list, use template.name to get the template’s file name, if the template was loaded from a file. (The name is a string such as 'admin/index.html'.)
Not using Django templates?
This attribute is only populated when using the DjangoTemplates backend. If you’re using another template engine, template_name may be a suitable alternative if you only need the name of the template used for rendering.
An instance of ResolverMatch for the response. You can use the func attribute, for example, to verify the view that served the response:
If the given URL is not found, accessing this attribute will raise a Resolver404 exception.


The test client that was used to make the request that resulted in the response.


The body of the response, as a bytestring. This is the final page content as rendered by the view, or any error message.


The template Context instance that was used to render the template that produced the response content.
If the rendered page used multiple templates, then context will be a list of Context objects, in the order in which they were rendered.
Regardless of the number of templates used during rendering, you can retrieve context values using the [] operator. For example, the context variable name could be retrieved using:
Not using Django templates?
This attribute is only populated when using the DjangoTemplates backend. If you’re using another template engine, context_data may be a suitable alternative on responses with that attribute.


A tuple of three values that provides information about the unhandled exception, if any, that occurred during the view.
The values are (type, value, traceback), the same as returned by Python’s sys.exc_info(). Their meanings are:
If no exception occurred, then exc_info will be None.


The body of the response, parsed as JSON. Extra keyword arguments are passed to json.loads(). For example:
If the Content-Type header is not "application/json", then a ValueError will be raised when trying to parse the response.


The request data that stimulated the response.


An instance of ResolverMatch for the response. You can use the func attribute, for example, to verify the view that served the response:
If the given URL is not found, accessing this attribute will raise a Resolver404 exception.


The HTTP status of the response, as an integer. For a full list of defined codes, see the IANA status code registry.


A list of Template instances used to render the final content, in the order they were rendered. For each template in the list, use template.name to get the template’s file name, if the template was loaded from a file. (The name is a string such as 'admin/index.html'.)
Not using Django templates?
This attribute is only populated when using the DjangoTemplates backend. If you’re using another template engine, template_name may be a suitable alternative if you only need the name of the template used for rendering.


The WSGIRequest instance generated by the test handler that generated the response.


DiscoverRunner will search for tests in any file matching pattern.
top_level can be used to specify the directory containing your top-level Python modules. Usually Django can figure this out automatically, so it’s not necessary to specify this option. If specified, it should generally be the directory containing your manage.py file.
verbosity determines the amount of notification and debug information that will be printed to the console; 0 is no output, 1 is normal output, and 2 is verbose output.
If interactive is True, the test suite has permission to ask the user for instructions when the test suite is executed. An example of this behavior would be asking for permission to delete an existing test database. If interactive is False, the test suite must be able to run without any manual intervention.
If failfast is True, the test suite will stop running after the first test failure is detected.
If keepdb is True, the test suite will use the existing database, or create one if necessary. If False, a new database will be created, prompting the user to remove the existing one, if present.
If reverse is True, test cases will be executed in the opposite order. This could be useful to debug tests that aren’t properly isolated and have side effects. Grouping by test class is preserved when using this option. This option can be used in conjunction with --shuffle to reverse the order for a particular random seed.
debug_mode specifies what the DEBUG setting should be set to prior to running tests.
parallel specifies the number of processes. If parallel is greater than 1, the test suite will run in parallel processes. If there are fewer test cases than configured processes, Django will reduce the number of processes accordingly. Each process gets its own database. This option requires the third-party tblib package to display tracebacks correctly.
tags can be used to specify a set of tags for filtering tests. May be combined with exclude_tags.
exclude_tags can be used to specify a set of tags for excluding tests. May be combined with tags.
If debug_sql is True, failing test cases will output SQL queries logged to the django.db.backends logger as well as the traceback. If verbosity is 2, then queries in all tests are output.
test_name_patterns can be used to specify a set of patterns for filtering test methods and classes by their names.
If pdb is True, a debugger (pdb or ipdb) will be spawned at each test error or failure.
If buffer is True, outputs from passing tests will be discarded.
If enable_faulthandler is True, faulthandler will be enabled.
If timing is True, test timings, including database setup and total run time, will be shown.
If shuffle is an integer, test cases will be shuffled in a random order prior to execution, using the integer as a random seed. If shuffle is None, the seed will be generated randomly. In both cases, the seed will be logged and set to self.shuffle_seed prior to running tests. This option can be used to help detect tests that aren’t properly isolated. Grouping by test class is preserved when using this option.
logger can be used to pass a Python Logger object. If provided, the logger will be used to log messages instead of printing to the console. The logger object will respect its logging level rather than the verbosity.
Django may, from time to time, extend the capabilities of the test runner by adding new arguments. The **kwargs declaration allows for this expansion. If you subclass DiscoverRunner or write your own test runner, ensure it accepts **kwargs.
Your test runner may also define additional command-line options. Create or override an add_arguments(cls, parser) class method and add custom arguments by calling parser.add_argument() inside the method, so that the test command will be able to use those arguments.
The enable_faulthandler and timing arguments were added.
The logger and shuffle arguments were added.


Constructs a test suite that matches the test labels provided.
test_labels is a list of strings describing the tests to be run. A test label can take one of four forms:
If test_labels has a value of None, the test runner will search for tests in all files below the current directory whose names match its pattern (see above).
Deprecated since version 4.0: extra_tests is a list of extra TestCase instances to add to the suite that is executed by the test runner. These extra tests are run in addition to those discovered in the modules listed in test_labels.
Returns a TestSuite instance ready to be run.


Returns the keyword arguments to instantiate the DiscoverRunner.test_runner with.


If a logger is set, logs the message at the given integer logging level (e.g. logging.DEBUG, logging.INFO, or logging.WARNING). Otherwise, the message is printed to the console, respecting the current verbosity. For example, no message will be printed if the verbosity is 0, INFO and above will be printed if the verbosity is at least 1, and DEBUG will be printed if it is at least 2. The level defaults to logging.INFO.


Runs the system checks on the test databases.


Runs the test suite.
Returns the result produced by the running the test suite.


Run the test suite.
test_labels allows you to specify which tests to run and supports several formats (see DiscoverRunner.build_suite() for a list of supported formats).
Deprecated since version 4.0: extra_tests is a list of extra TestCase instances to add to the suite that is executed by the test runner. These extra tests are run in addition to those discovered in the modules listed in test_labels.
This method should return the number of tests that failed.


Creates the test databases by calling setup_databases().


Sets up the test environment by calling setup_test_environment() and setting DEBUG to self.debug_mode (defaults to False).


Computes and returns a return code based on a test suite, and the result from that test suite.


Destroys the test databases, restoring pre-test conditions by calling teardown_databases().


This is the class that loads tests, whether from TestCases or modules or otherwise and bundles them into test suites for the runner to execute. By default it is set to unittest.defaultTestLoader. You can override this attribute if your tests are going to be loaded in unusual ways.


This is the class of the low-level test runner which is used to execute the individual tests and format the results. By default it is set to unittest.TextTestRunner. Despite the unfortunate similarity in naming conventions, this is not the same type of class as DiscoverRunner, which covers a broader set of responsibilities. You can override this attribute to modify the way tests are run and reported.


The class used to build the test suite. By default it is set to unittest.TestSuite. This can be overridden if you wish to implement different logic for collecting tests.


Asserts that a response produced the given status_code and that text appears in its content. If count is provided, text must occur exactly count times in the response.
Set html to True to handle text as HTML. The comparison with the response content will be based on HTML semantics instead of character-by-character equality. Whitespace is ignored in most cases, attribute ordering is not significant. See assertHTMLEqual() for more details.


Asserts that a form field behaves correctly with various inputs.
For example, the following code tests that an EmailField accepts a@a.com as a valid email address, but rejects aaa with a reasonable error message:


Asserts that a field on a form raises the provided list of errors when rendered on the form.
response must be a response instance returned by the test client.
form is the name the Form instance was given in the template context of the response.
field is the name of the field on the form to check. If field has a value of None, non-field errors (errors you can access via form.non_field_errors()) will be checked.
errors is an error string, or a list of error strings, that are expected as a result of form validation.


Asserts that the formset raises the provided list of errors when rendered.
response must be a response instance returned by the test client.
formset is the name the Formset instance was given in the template context of the response.
form_index is the number of the form within the Formset. If form_index has a value of None, non-form errors (errors you can access via formset.non_form_errors()) will be checked.
field is the name of the field on the form to check. If field has a value of None, non-field errors (errors you can access via form.non_field_errors()) will be checked.
errors is an error string, or a list of error strings, that are expected as a result of form validation.


Asserts that the strings html1 and html2 are equal. The comparison is based on HTML semantics. The comparison takes following things into account:
The following examples are valid tests and don’t raise any AssertionError:
html1 and html2 must contain HTML. An AssertionError will be raised if one of them cannot be parsed.
Output in case of error can be customized with the msg argument.
In older versions, any attribute (not only boolean attributes) without a value was considered equal to an attribute with the same name and value.


Asserts that the strings html1 and html2 are not equal. The comparison is based on HTML semantics. See assertHTMLEqual() for details.
html1 and html2 must contain HTML. An AssertionError will be raised if one of them cannot be parsed.
Output in case of error can be customized with the msg argument.


Asserts that the HTML fragment needle is contained in the haystack one.
If the count integer argument is specified, then additionally the number of needle occurrences will be strictly verified.
Whitespace in most cases is ignored, and attribute ordering is not significant. See assertHTMLEqual() for more details.


Asserts that the JSON fragments raw and expected_data are equal. Usual JSON non-significant whitespace rules apply as the heavyweight is delegated to the json library.
Output in case of error can be customized with the msg argument.


Asserts that the JSON fragments raw and expected_data are not equal. See assertJSONEqual() for further details.
Output in case of error can be customized with the msg argument.


Asserts that a response produced the given status_code and that text does not appear in its content.
Set html to True to handle text as HTML. The comparison with the response content will be based on HTML semantics instead of character-by-character equality. Whitespace is ignored in most cases, attribute ordering is not significant. See assertHTMLEqual() for more details.


Asserts that execution of callable raises expected_exception and that expected_message is found in the exception’s message. Any other outcome is reported as a failure. It’s a simpler version of unittest.TestCase.assertRaisesRegex() with the difference that expected_message isn’t treated as a regular expression.
If only the expected_exception and expected_message parameters are given, returns a context manager so that the code being tested can be written inline rather than as a function:


Asserts that the response returned a status_code redirect status, redirected to expected_url (including any GET data), and that the final page was received with target_status_code.
If your request used the follow argument, the expected_url and target_status_code will be the url and status code for the final point of the redirect chain.
If fetch_redirect_response is False, the final page won’t be loaded. Since the test client can’t fetch external URLs, this is particularly useful if expected_url isn’t part of your Django app.
Scheme is handled correctly when making comparisons between two URLs. If there isn’t any scheme specified in the location where we are redirected to, the original request’s scheme is used. If present, the scheme in expected_url is the one used to make the comparisons to.


Asserts that the template with the given name was not used in rendering the response.
You can use this as a context manager in the same way as assertTemplateUsed().


Asserts that the template with the given name was used in rendering the response.
response must be a response instance returned by the test client.
template_name should be a string such as 'admin/index.html'.
The count argument is an integer indicating the number of times the template should be rendered. Default is None, meaning that the template should be rendered one or more times.
You can use this as a context manager, like this:


Asserts that two URLs are the same, ignoring the order of query string parameters except for parameters with the same name. For example, /path/?x=1&y=2 is equal to /path/?y=2&x=1, but /path/?a=1&a=2 isn’t equal to /path/?a=2&a=1.


Analogous to SimpleTestCase.assertRaisesMessage() but for assertWarnsRegex() instead of assertRaisesRegex().


Asserts that the strings xml1 and xml2 are equal. The comparison is based on XML semantics. Similarly to assertHTMLEqual(), the comparison is made on parsed content, hence only semantic differences are considered, not syntax differences. When invalid XML is passed in any parameter, an AssertionError is always raised, even if both strings are identical.
XML declaration, document type, processing instructions, and comments are ignored. Only the root element and its children are compared.
Output in case of error can be customized with the msg argument.


Asserts that the strings xml1 and xml2 are not equal. The comparison is based on XML semantics. See assertXMLEqual() for details.
Output in case of error can be customized with the msg argument.


SimpleTestCase disallows database queries by default. This helps to avoid executing write queries which will affect other tests since each SimpleTestCase test isn’t run in a transaction. If you aren’t concerned about this problem, you can disable this behavior by setting the databases class attribute to '__all__' on your test class.


Asserts that when func is called with *args and **kwargs that num database queries are executed.
If a "using" key is present in kwargs it is used as the database alias for which to check the number of queries:
If you wish to call a function with a using parameter you can do it by wrapping the call with a lambda to add an extra parameter:
You can also use this as a context manager:


Asserts that a queryset qs matches a particular iterable of values values.
If transform is provided, values is compared to a list produced by applying transform to each member of qs.
By default, the comparison is also ordering dependent. If qs doesn’t provide an implicit ordering, you can set the ordered parameter to False, which turns the comparison into a collections.Counter comparison. If the order is undefined (if the given qs isn’t ordered and the comparison is against more than one ordered value), a ValueError is raised.
Output in case of error can be customized with the msg argument.
The default value of transform argument was changed to None.
Support for direct comparison between querysets was added.
Deprecated since version 3.2: If transform is not provided and values is a list of strings, it’s compared to a list produced by applying repr() to each member of qs. This behavior is deprecated and will be removed in Django 4.1. If you need it, explicitly set transform to repr.


Warning
This attribute is a private API. It may be changed or removed without a deprecation period in the future, for instance to accommodate changes in application loading.
It’s used to optimize Django’s own test suite, which contains hundreds of models but no relations between models in different applications.
By default, available_apps is set to None. After each test, Django calls flush to reset the database state. This empties all tables and emits the post_migrate signal, which recreates one content type and four permissions for each model. This operation gets expensive proportionally to the number of models.
Setting available_apps to a list of applications instructs Django to behave as if only the models from these applications were available. The behavior of TransactionTestCase changes as follows:
Since the database isn’t fully flushed, if a test creates instances of models not included in available_apps, they will leak and they may cause unrelated tests to fail. Be careful with tests that use sessions; the default session engine stores them in the database.
Since post_migrate isn’t emitted after flushing the database, its state after a TransactionTestCase isn’t the same as after a TestCase: it’s missing the rows created by listeners to post_migrate. Considering the order in which tests are executed, this isn’t an issue, provided either all TransactionTestCase in a given test suite declare available_apps, or none of them.
available_apps is mandatory in Django’s own test suite.


Setting reset_sequences = True on a TransactionTestCase will make sure sequences are always reset before the test run:
Unless you are explicitly testing primary keys sequence numbers, it is recommended that you do not hard code primary key values in tests.
Using reset_sequences = True will slow down the test, since the primary key reset is a relatively expensive database operation.


Creates the test databases.
Returns a data structure that provides enough detail to undo the changes that have been made. This data will be provided to the teardown_databases() function at the conclusion of testing.
The aliases argument determines which DATABASES aliases test databases should be set up for. If it’s not provided, it defaults to all of DATABASES aliases.
The serialized_aliases argument determines what subset of aliases test databases should have their state serialized to allow usage of the serialized_rollback feature. If it’s not provided, it defaults to aliases.
The time_keeper kwarg was added, and all kwargs were made keyword-only.
The serialized_aliases kwarg was added.


Performs global pre-test setup, such as installing instrumentation for the template rendering system and setting up the dummy email outbox.
If debug isn’t None, the DEBUG setting is updated to its value.


Destroys the test databases, restoring pre-test conditions.
old_config is a data structure defining the changes in the database configuration that need to be reversed. It’s the return value of the setup_databases() method.


Performs global post-test teardown, such as removing instrumentation from the template system and restoring normal email services.