doc_content
stringlengths
1
386k
doc_id
stringlengths
5
188
class Sitemap A Sitemap class can define the following methods/attributes: items Required. A method that returns a sequence or QuerySet of objects. The framework doesn’t care what type of objects they are; all that matters is that these objects get passed to the location(), lastmod(), changefreq() and priority() methods. location Optional. Either a method or attribute. If it’s a method, it should return the absolute path for a given object as returned by items(). If it’s an attribute, its value should be a string representing an absolute path to use for every object returned by items(). In both cases, “absolute path” means a URL that doesn’t include the protocol or domain. Examples: Good: '/foo/bar/' Bad: 'example.com/foo/bar/' Bad: 'https://example.com/foo/bar/' If location isn’t provided, the framework will call the get_absolute_url() method on each object as returned by items(). To specify a protocol other than 'http', use protocol. lastmod Optional. Either a method or attribute. If it’s a method, it should take one argument – an object as returned by items() – and return that object’s last-modified date/time as a datetime. If it’s an attribute, its value should be a datetime representing the last-modified date/time for every object returned by items(). If all items in a sitemap have a lastmod, the sitemap generated by views.sitemap() will have a Last-Modified header equal to the latest lastmod. You can activate the ConditionalGetMiddleware to make Django respond appropriately to requests with an If-Modified-Since header which will prevent sending the sitemap if it hasn’t changed. paginator Optional. This property returns a Paginator for items(). If you generate sitemaps in a batch you may want to override this as a cached property in order to avoid multiple items() calls. changefreq Optional. Either a method or attribute. If it’s a method, it should take one argument – an object as returned by items() – and return that object’s change frequency as a string. If it’s an attribute, its value should be a string representing the change frequency of every object returned by items(). Possible values for changefreq, whether you use a method or attribute, are: 'always' 'hourly' 'daily' 'weekly' 'monthly' 'yearly' 'never' priority Optional. Either a method or attribute. If it’s a method, it should take one argument – an object as returned by items() – and return that object’s priority as either a string or float. If it’s an attribute, its value should be either a string or float representing the priority of every object returned by items(). Example values for priority: 0.4, 1.0. The default priority of a page is 0.5. See the sitemaps.org documentation for more. protocol 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. limit Optional. This attribute defines the maximum number of URLs included on each page of the sitemap. Its value should not exceed the default value of 50000, which is the upper limit allowed in the Sitemaps protocol. i18n Optional. A boolean attribute that defines if the URLs of this sitemap should be generated using all of your LANGUAGES. The default is False. languages New in Django 3.2. Optional. A sequence of language codes to use for generating alternate links when i18n is enabled. Defaults to LANGUAGES. alternates New in Django 3.2. Optional. A boolean attribute. When used in conjunction with i18n generated URLs will each have a list of alternate links pointing to other language versions using the hreflang attribute. The default is False. x_default New in Django 3.2. 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.
django.ref.contrib.sitemaps#django.contrib.sitemaps.Sitemap
alternates New in Django 3.2. Optional. A boolean attribute. When used in conjunction with i18n generated URLs will each have a list of alternate links pointing to other language versions using the hreflang attribute. The default is False.
django.ref.contrib.sitemaps#django.contrib.sitemaps.Sitemap.alternates
changefreq Optional. Either a method or attribute. If it’s a method, it should take one argument – an object as returned by items() – and return that object’s change frequency as a string. If it’s an attribute, its value should be a string representing the change frequency of every object returned by items(). Possible values for changefreq, whether you use a method or attribute, are: 'always' 'hourly' 'daily' 'weekly' 'monthly' 'yearly' 'never'
django.ref.contrib.sitemaps#django.contrib.sitemaps.Sitemap.changefreq
i18n Optional. A boolean attribute that defines if the URLs of this sitemap should be generated using all of your LANGUAGES. The default is False.
django.ref.contrib.sitemaps#django.contrib.sitemaps.Sitemap.i18n
items Required. A method that returns a sequence or QuerySet of objects. The framework doesn’t care what type of objects they are; all that matters is that these objects get passed to the location(), lastmod(), changefreq() and priority() methods.
django.ref.contrib.sitemaps#django.contrib.sitemaps.Sitemap.items
languages New in Django 3.2. Optional. A sequence of language codes to use for generating alternate links when i18n is enabled. Defaults to LANGUAGES.
django.ref.contrib.sitemaps#django.contrib.sitemaps.Sitemap.languages
lastmod Optional. Either a method or attribute. If it’s a method, it should take one argument – an object as returned by items() – and return that object’s last-modified date/time as a datetime. If it’s an attribute, its value should be a datetime representing the last-modified date/time for every object returned by items(). If all items in a sitemap have a lastmod, the sitemap generated by views.sitemap() will have a Last-Modified header equal to the latest lastmod. You can activate the ConditionalGetMiddleware to make Django respond appropriately to requests with an If-Modified-Since header which will prevent sending the sitemap if it hasn’t changed.
django.ref.contrib.sitemaps#django.contrib.sitemaps.Sitemap.lastmod
limit Optional. This attribute defines the maximum number of URLs included on each page of the sitemap. Its value should not exceed the default value of 50000, which is the upper limit allowed in the Sitemaps protocol.
django.ref.contrib.sitemaps#django.contrib.sitemaps.Sitemap.limit
location Optional. Either a method or attribute. If it’s a method, it should return the absolute path for a given object as returned by items(). If it’s an attribute, its value should be a string representing an absolute path to use for every object returned by items(). In both cases, “absolute path” means a URL that doesn’t include the protocol or domain. Examples: Good: '/foo/bar/' Bad: 'example.com/foo/bar/' Bad: 'https://example.com/foo/bar/' If location isn’t provided, the framework will call the get_absolute_url() method on each object as returned by items(). To specify a protocol other than 'http', use protocol.
django.ref.contrib.sitemaps#django.contrib.sitemaps.Sitemap.location
paginator Optional. This property returns a Paginator for items(). If you generate sitemaps in a batch you may want to override this as a cached property in order to avoid multiple items() calls.
django.ref.contrib.sitemaps#django.contrib.sitemaps.Sitemap.paginator
priority Optional. Either a method or attribute. If it’s a method, it should take one argument – an object as returned by items() – and return that object’s priority as either a string or float. If it’s an attribute, its value should be either a string or float representing the priority of every object returned by items(). Example values for priority: 0.4, 1.0. The default priority of a page is 0.5. See the sitemaps.org documentation for more.
django.ref.contrib.sitemaps#django.contrib.sitemaps.Sitemap.priority
protocol 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.
django.ref.contrib.sitemaps#django.contrib.sitemaps.Sitemap.protocol
x_default New in Django 3.2. 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.
django.ref.contrib.sitemaps#django.contrib.sitemaps.Sitemap.x_default
views.index(request, sitemaps, template_name='sitemap_index.xml', content_type='application/xml', sitemap_url_name='django.contrib.sitemaps.views.sitemap')
django.ref.contrib.sitemaps#django.contrib.sitemaps.views.index
views.sitemap(request, sitemaps, section=None, template_name='sitemap.xml', content_type='application/xml')
django.ref.contrib.sitemaps#django.contrib.sitemaps.views.sitemap
class managers.CurrentSiteManager
django.ref.contrib.sites#django.contrib.sites.managers.CurrentSiteManager
class CurrentSiteMiddleware
django.ref.middleware#django.contrib.sites.middleware.CurrentSiteMiddleware
class models.Site A model for storing the domain and name attributes of a website. domain The fully qualified domain name associated with the website. For example, www.example.com. name A human-readable “verbose” name for the website.
django.ref.contrib.sites#django.contrib.sites.models.Site
domain The fully qualified domain name associated with the website. For example, www.example.com.
django.ref.contrib.sites#django.contrib.sites.models.Site.domain
name A human-readable “verbose” name for the website.
django.ref.contrib.sites#django.contrib.sites.models.Site.name
class requests.RequestSite 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. __init__(request) Sets the name and domain attributes to the value of get_host().
django.ref.contrib.sites#django.contrib.sites.requests.RequestSite
__init__(request) Sets the name and domain attributes to the value of get_host().
django.ref.contrib.sites#django.contrib.sites.requests.RequestSite.__init__
shortcuts.get_current_site(request) 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.
django.ref.contrib.sites#django.contrib.sites.shortcuts.get_current_site
class storage.ManifestFilesMixin
django.ref.contrib.staticfiles#django.contrib.staticfiles.storage.ManifestFilesMixin
class storage.ManifestStaticFilesStorage
django.ref.contrib.staticfiles#django.contrib.staticfiles.storage.ManifestStaticFilesStorage
storage.ManifestStaticFilesStorage.file_hash(name, content=None)
django.ref.contrib.staticfiles#django.contrib.staticfiles.storage.ManifestStaticFilesStorage.file_hash
storage.ManifestStaticFilesStorage.manifest_strict
django.ref.contrib.staticfiles#django.contrib.staticfiles.storage.ManifestStaticFilesStorage.manifest_strict
storage.ManifestStaticFilesStorage.max_post_process_passes
django.ref.contrib.staticfiles#django.contrib.staticfiles.storage.ManifestStaticFilesStorage.max_post_process_passes
class storage.StaticFilesStorage
django.ref.contrib.staticfiles#django.contrib.staticfiles.storage.StaticFilesStorage
storage.StaticFilesStorage.post_process(paths, **options)
django.ref.contrib.staticfiles#django.contrib.staticfiles.storage.StaticFilesStorage.post_process
class testing.StaticLiveServerTestCase
django.ref.contrib.staticfiles#django.contrib.staticfiles.testing.StaticLiveServerTestCase
urls.staticfiles_urlpatterns()
django.ref.contrib.staticfiles#django.contrib.staticfiles.urls.staticfiles_urlpatterns
views.serve(request, path)
django.ref.contrib.staticfiles#django.contrib.staticfiles.views.serve
Feed.get_context_data(**kwargs) 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: from mysite.models import Article from django.contrib.syndication.views import Feed class ArticlesFeed(Feed): title = "My articles" description_template = "feeds/articles.html" def items(self): return Article.objects.order_by('-pub_date')[:5] def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['foo'] = 'bar' return context
django.ref.contrib.syndication#django.contrib.syndication.Feed.get_context_data
class views.Feed
django.ref.contrib.syndication#django.contrib.syndication.views.Feed
Tablespaces 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. Declaring tablespaces for tables 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. Declaring tablespaces for indexes 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. An example class TablespaceExample(models.Model): name = models.CharField(max_length=30, db_index=True, db_tablespace="indexes") data = models.CharField(max_length=255, db_index=True) shortcut = models.CharField(max_length=7) edges = models.ManyToManyField(to="self", db_tablespace="indexes") class Meta: db_tablespace = "tables" indexes = [models.Index(fields=['shortcut'], db_tablespace='other_indexes')] 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. Database support 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.
django.topics.db.tablespaces
Template.render(context=None, request=None) 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.
django.topics.templates#django.template.backends.base.Template.render
class DjangoTemplates
django.topics.templates#django.template.backends.django.DjangoTemplates
class Jinja2
django.topics.templates#django.template.backends.jinja2.Jinja2
class Origin(name, template_name=None, loader=None) name 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>. template_name 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. loader 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.
django.ref.templates.api#django.template.base.Origin
loader 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.
django.ref.templates.api#django.template.base.Origin.loader
name 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>.
django.ref.templates.api#django.template.base.Origin.name
template_name 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.
django.ref.templates.api#django.template.base.Origin.template_name
class Context(dict_=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.
django.ref.templates.api#django.template.Context
Context.flatten()
django.ref.templates.api#django.template.Context.flatten
Context.get(key, otherwise=None) Returns the value for key if key is in the context, else returns otherwise.
django.ref.templates.api#django.template.Context.get
Context.pop()
django.ref.templates.api#django.template.Context.pop
Context.push()
django.ref.templates.api#django.template.Context.push
Context.setdefault(key, default=None) If key is in the context, returns its value. Otherwise inserts key with a value of default and returns default.
django.ref.templates.api#django.template.Context.setdefault
Context.update(other_dict)
django.ref.templates.api#django.template.Context.update
debug()
django.ref.templates.api#django.template.context_processors.debug
i18n()
django.ref.templates.api#django.template.context_processors.i18n
static()
django.ref.templates.api#django.template.context_processors.static
tz()
django.ref.templates.api#django.template.context_processors.tz
django.template.defaultfilters.stringfilter()
django.howto.custom-template-tags#django.template.defaultfilters.stringfilter
class Engine(dirs=None, app_dirs=False, context_processors=None, debug=False, loaders=None, string_if_invalid='', file_charset='utf-8', libraries=None, builtins=None, autoescape=True) 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: 'django.template.loaders.filesystem.Loader' 'django.template.loaders.app_directories.Loader' if and only if app_dirs is True. 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: Engine( libraries={ 'myapp_tags': 'path.to.myapp.tags', 'admin.urls': 'django.contrib.admin.templatetags.admin_urls', }, ) 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: Engine( builtins=['myapp.builtins'], ) Tags and filters from built-in libraries can be used without first calling the {% load %} tag.
django.ref.templates.api#django.template.Engine
Engine.from_string(template_code) Compiles the given template code and returns a Template object.
django.ref.templates.api#django.template.Engine.from_string
Engine.get_template(template_name) Loads a template with the given name, compiles it and returns a Template object.
django.ref.templates.api#django.template.Engine.get_template
Engine.select_template(template_name_list) Like get_template(), except it takes a list of names and returns the first template that was found.
django.ref.templates.api#django.template.Engine.select_template
django.template.Library.filter()
django.howto.custom-template-tags#django.template.Library.filter
django.template.Library.inclusion_tag()
django.howto.custom-template-tags#django.template.Library.inclusion_tag
django.template.Library.simple_tag()
django.howto.custom-template-tags#django.template.Library.simple_tag
engines Template engines are available in django.template.engines: from django.template import engines django_engine = engines['django'] template = django_engine.from_string("Hello {{ name }}!") The lookup key — 'django' in this example — is the engine’s NAME.
django.topics.templates#django.template.loader.engines
get_template(template_name, using=None) 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.
django.topics.templates#django.template.loader.get_template
render_to_string(template_name, context=None, request=None, using=None) render_to_string() loads a template like get_template() and calls its render() method immediately. It takes the following arguments. template_name The name of the template to load and render. If it’s a list of template names, Django uses select_template() instead of get_template() to find the template. context A dict to be used as the template’s context for rendering. request An optional HttpRequest that will be available during the template’s rendering process. using An optional template engine NAME. The search for the template will be restricted to that engine. Usage example: from django.template.loader import render_to_string rendered = render_to_string('my_template.html', {'foo': 'bar'})
django.topics.templates#django.template.loader.render_to_string
select_template(template_name_list, using=None) 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.
django.topics.templates#django.template.loader.select_template
class app_directories.Loader 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: INSTALLED_APPS = ['myproject.polls', 'myproject.music'] …then get_template('foo.html') will look for foo.html in these directories, in this order: /path/to/myproject/polls/templates/ /path/to/myproject/music/templates/ … 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: TEMPLATES = [{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, }]
django.ref.templates.api#django.template.loaders.app_directories.Loader
class Loader Loads templates from a given source, such as the filesystem or a database. get_template_sources(template_name) 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. get_contents(origin) 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. get_template(template_name, skip=None) 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.
django.ref.templates.api#django.template.loaders.base.Loader
get_contents(origin) 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.
django.ref.templates.api#django.template.loaders.base.Loader.get_contents
get_template(template_name, skip=None) 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.
django.ref.templates.api#django.template.loaders.base.Loader.get_template
get_template_sources(template_name) 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.
django.ref.templates.api#django.template.loaders.base.Loader.get_template_sources
class cached.Loader 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: TEMPLATES = [{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'], 'OPTIONS': { 'loaders': [ ('django.template.loaders.cached.Loader', [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', 'path.to.custom.Loader', ]), ], }, }] 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.
django.ref.templates.api#django.template.loaders.cached.Loader
class filesystem.Loader 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: TEMPLATES = [{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'], }] You can also override 'DIRS' and specify specific directories for a particular filesystem loader: TEMPLATES = [{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'OPTIONS': { 'loaders': [ ( 'django.template.loaders.filesystem.Loader', [BASE_DIR / 'templates'], ), ], }, }]
django.ref.templates.api#django.template.loaders.filesystem.Loader
class locmem.Loader Loads templates from a Python dictionary. This is useful for testing. This loader takes a dictionary of templates as its first argument: TEMPLATES = [{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'OPTIONS': { 'loaders': [ ('django.template.loaders.locmem.Loader', { 'index.html': 'content here', }), ], }, }] This loader is disabled by default.
django.ref.templates.api#django.template.loaders.locmem.Loader
class RequestContext(request, dict_=None, processors=None)
django.ref.templates.api#django.template.RequestContext
class SimpleTemplateResponse
django.ref.template-response#django.template.response.SimpleTemplateResponse
SimpleTemplateResponse.__init__(template, context=None, content_type=None, status=None, charset=None, using=None, headers=None) Instantiates a SimpleTemplateResponse object with the given template, context, content type, HTTP status, and charset. template A backend-dependent template object (such as those returned by get_template()), the name of a template, or a list of template names. context A dict of values to add to the template context. By default, this is an empty dictionary. content_type The value included in the HTTP Content-Type header, including the MIME type specification and the character set encoding. If content_type is specified, then its value is used. Otherwise, 'text/html' is used. status The HTTP status code for the response. charset The charset in which the response will be encoded. If not given it will be extracted from content_type, and if that is unsuccessful, the DEFAULT_CHARSET setting will be used. using The NAME of a template engine to use for loading the template. headers A dict of HTTP headers to add to the response. Changed in Django 3.2: The headers parameter was added.
django.ref.template-response#django.template.response.SimpleTemplateResponse.__init__
SimpleTemplateResponse.add_post_render_callback() 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.)
django.ref.template-response#django.template.response.SimpleTemplateResponse.add_post_render_callback
SimpleTemplateResponse.context_data The context data to be used when rendering the template. It must be a dict. Example: {'foo': 123}
django.ref.template-response#django.template.response.SimpleTemplateResponse.context_data
SimpleTemplateResponse.is_rendered A boolean indicating whether the response content has been rendered.
django.ref.template-response#django.template.response.SimpleTemplateResponse.is_rendered
SimpleTemplateResponse.render() 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.
django.ref.template-response#django.template.response.SimpleTemplateResponse.render
SimpleTemplateResponse.rendered_content The current rendered value of the response content, using the current template and context data.
django.ref.template-response#django.template.response.SimpleTemplateResponse.rendered_content
SimpleTemplateResponse.resolve_context(context) 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.
django.ref.template-response#django.template.response.SimpleTemplateResponse.resolve_context
SimpleTemplateResponse.resolve_template(template) 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.
django.ref.template-response#django.template.response.SimpleTemplateResponse.resolve_template
SimpleTemplateResponse.template_name 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']
django.ref.template-response#django.template.response.SimpleTemplateResponse.template_name
class TemplateResponse TemplateResponse is a subclass of SimpleTemplateResponse that knows about the current HttpRequest.
django.ref.template-response#django.template.response.TemplateResponse
TemplateResponse.__init__(request, template, context=None, content_type=None, status=None, charset=None, using=None, headers=None) Instantiates a TemplateResponse object with the given request, template, context, content type, HTTP status, and charset. request An HttpRequest instance. template A backend-dependent template object (such as those returned by get_template()), the name of a template, or a list of template names. context A dict of values to add to the template context. By default, this is an empty dictionary. content_type The value included in the HTTP Content-Type header, including the MIME type specification and the character set encoding. If content_type is specified, then its value is used. Otherwise, 'text/html' is used. status The HTTP status code for the response. charset The charset in which the response will be encoded. If not given it will be extracted from content_type, and if that is unsuccessful, the DEFAULT_CHARSET setting will be used. using The NAME of a template engine to use for loading the template. headers A dict of HTTP headers to add to the response. Changed in Django 3.2: The headers parameter was added.
django.ref.template-response#django.template.response.TemplateResponse.__init__
class Template This class lives at django.template.Template. The constructor takes one argument — the raw template code: from django.template import Template template = Template("My name is {{ my_name }}.")
django.ref.templates.api#django.template.Template
Template.render(context) Call the Template object’s render() method with a Context to “fill” the template: >>> from django.template import Context, Template >>> template = Template("My name is {{ my_name }}.") >>> context = Context({"my_name": "Adrian"}) >>> template.render(context) "My name is Adrian." >>> context = Context({"my_name": "Dolores"}) >>> template.render(context) "My name is Dolores."
django.ref.templates.api#django.template.Template.render
Templates 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. The Django template language Templates Variables Filters Tags Comments Template inheritance Automatic HTML escaping Accessing method calls Custom tag and filter libraries Built-in template tags and filters Built-in tag reference Built-in filter reference Internationalization tags and filters Other tags and filters libraries The Django template language: for Python programmers Overview Configuring an engine Loading a template Rendering a context Playing with Context objects Loading templates Custom loaders Template origin 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.
django.ref.templates.index
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. The Django template language Syntax 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. Variables 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: My first name is {{ first_name }}. My last name is {{ last_name }}. With a context of {'first_name': 'John', 'last_name': 'Doe'}, this template renders to: My first name is John. My last name is Doe. Dictionary lookup, attribute lookup and list-index lookups are implemented with a dot notation: {{ my_dict.key }} {{ my_object.attribute }} {{ my_list.0 }} 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 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: {% csrf_token %} Most tags accept arguments: {% cycle 'odd' 'even' %} Some tags require beginning and ending tags: {% if user.is_authenticated %}Hello, {{ user.username }}.{% endif %} A reference of built-in tags is available as well as instructions for writing custom tags. Filters Filters transform the values of variables and tag arguments. They look like this: {{ django|title }} With a context of {'django': 'the web framework for perfectionists with deadlines'}, this template renders to: The Web Framework For Perfectionists With Deadlines Some filters take an argument: {{ my_date|date:"Y-m-d" }} A reference of built-in filters is available as well as instructions for writing custom filters. Comments Comments look like this: {# this won't be rendered #} A {% comment %} tag provides multi-line comments. Components About this section This is an overview of the Django template language’s APIs. For details see the API reference. Engine 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. Template 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. Context 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. Loaders 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 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. Support for template engines Configuration 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: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { # ... some options here ... }, }, ] 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: DIRS defines a list of directories where the engine should look for template source files, in search order. APP_DIRS tells whether the engine should look for templates inside installed applications. Each backend defines a conventional name for the subdirectory inside applications where its templates should be stored. 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. Usage The django.template.loader module defines two functions to load templates. get_template(template_name, using=None) 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(template_name_list, using=None) 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: exception TemplateDoesNotExist(msg, tried=None, backend=None, chain=None) 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: backend The template backend instance from which the exception originated. tried A list of sources that were tried when finding the template. This is formatted as a list of tuples containing (origin, status), where origin is an origin-like object and status is a string with the reason the template wasn’t found. chain A list of intermediate TemplateDoesNotExist exceptions raised when trying to load a template. This is used by functions, such as get_template(), that try to load a given template from multiple engines. exception TemplateSyntaxError(msg) 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: Template.render(context=None, request=None) 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: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ '/home/html/example.com', '/home/html/default', ], }, { 'BACKEND': 'django.template.backends.jinja2.Jinja2', 'DIRS': [ '/home/html/jinja2', ], }, ] If you call get_template('story_detail.html'), here are the files Django will look for, in order: /home/html/example.com/story_detail.html ('django' engine) /home/html/default/story_detail.html ('django' engine) /home/html/jinja2/story_detail.html ('jinja2' engine) If you call select_template(['story_253_detail.html', 'story_detail.html']), here’s what Django will look for: /home/html/example.com/story_253_detail.html ('django' engine) /home/html/default/story_253_detail.html ('django' engine) /home/html/jinja2/story_253_detail.html ('jinja2' engine) /home/html/example.com/story_detail.html ('django' engine) /home/html/default/story_detail.html ('django' engine) /home/html/jinja2/story_detail.html ('jinja2' engine) 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: get_template('news/story_detail.html') Using the same TEMPLATES option as above, this will attempt to load the following templates: /home/html/example.com/news/story_detail.html ('django' engine) /home/html/default/news/story_detail.html ('django' engine) /home/html/jinja2/news/story_detail.html ('jinja2' engine) 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(template_name, context=None, request=None, using=None) render_to_string() loads a template like get_template() and calls its render() method immediately. It takes the following arguments. template_name The name of the template to load and render. If it’s a list of template names, Django uses select_template() instead of get_template() to find the template. context A dict to be used as the template’s context for rendering. request An optional HttpRequest that will be available during the template’s rendering process. using An optional template engine NAME. The search for the template will be restricted to that engine. Usage example: from django.template.loader import render_to_string rendered = render_to_string('my_template.html', {'foo': 'bar'}) 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: engines Template engines are available in django.template.engines: from django.template import engines django_engine = engines['django'] template = django_engine.from_string("Hello {{ name }}!") The lookup key — 'django' in this example — is the engine’s NAME. Built-in backends class DjangoTemplates 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: OPTIONS={ 'libraries': { 'myapp_tags': 'path.to.myapp.tags', 'admin.urls': 'django.contrib.admin.templatetags.admin_urls', }, } 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: OPTIONS={ 'builtins': ['myapp.builtins'], } Tags and filters from built-in libraries can be used without first calling the {% load %} tag. class Jinja2 Requires Jinja2 to be installed: $ python -m pip install Jinja2 ...\> py -m pip install Jinja2 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: 'autoescape': True 'loader': a loader configured for DIRS and APP_DIRS 'auto_reload': settings.DEBUG 'undefined': DebugUndefined if settings.DEBUG else Undefined 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: {{ function(request) }} 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: Making an expensive computation that depends on the request. Needing the result in every template. Using the result multiple times in each template. 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: from django.templatetags.static import static from django.urls import reverse from jinja2 import Environment def environment(**options): env = Environment(**options) env.globals.update({ 'static': static, 'url': reverse, }) return env and set the 'environment' option to 'myproject.jinja2.environment'. Then you could use the following constructs in Jinja2 templates: <img src="{{ static('path/to/company-logo.png') }}" alt="Company Logo"> <a href="{{ url('admin:index') }}">Administration</a> 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.
django.topics.templates
class Client(enforce_csrf_checks=False, json_encoder=DjangoJSONEncoder, **defaults) 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: >>> c = Client(HTTP_USER_AGENT='Mozilla/5.0') 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: get(path, data=None, follow=False, secure=False, **extra) 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: >>> c = Client() >>> c.get('/customers/details/', {'name': 'fred', 'age': 7}) …will result in the evaluation of a GET request equivalent to: /customers/details/?name=fred&age=7 The extra keyword arguments parameter can be used to specify headers to be sent in the request. For example: >>> c = Client() >>> c.get('/customers/details/', {'name': 'fred', 'age': 7}, ... HTTP_ACCEPT='application/json') …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: >>> c = Client() >>> c.get('/customers/details/?name=fred&age=7') 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: >>> response = c.get('/redirect_me/', follow=True) >>> response.redirect_chain [('http://testserver/next/', 302), ('http://testserver/final/', 302)] If you set secure to True the client will emulate an HTTPS request. post(path, data=None, content_type=MULTIPART_CONTENT, follow=False, secure=False, **extra) 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: >>> c = Client() >>> c.post('/login/', {'name': 'fred', 'passwd': 'secret'}) …will result in the evaluation of a POST request to this URL: /login/ …with this POST data: name=fred&passwd=secret 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: {'choices': ('a', 'b', 'd')} 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: >>> c = Client() >>> with open('wishlist.doc', 'rb') as fp: ... c.post('/customers/wishes/', {'name': 'fred', 'attachment': fp}) (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: >>> from io import BytesIO >>> img = BytesIO(b'mybinarydata') >>> img.name = 'myimage.jpg' 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: >>> c.post('/login/?visitor=true', {'name': 'fred', 'passwd': 'secret'}) … 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. head(path, data=None, follow=False, secure=False, **extra) 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. options(path, data='', content_type='application/octet-stream', follow=False, secure=False, **extra) 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(). put(path, data='', content_type='application/octet-stream', follow=False, secure=False, **extra) 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(). patch(path, data='', content_type='application/octet-stream', follow=False, secure=False, **extra) 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(). delete(path, data='', content_type='application/octet-stream', follow=False, secure=False, **extra) 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(). trace(path, follow=False, secure=False, **extra) 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(). login(**credentials) 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: >>> c = Client() >>> c.login(username='fred', password='secret') # Now you can access a view that's only available to logged-in users. 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. force_login(user, backend=None) 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. logout() 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.
django.topics.testing.tools#django.test.Client
Client.cookies A Python SimpleCookie object, containing the current values of all the client cookies. See the documentation of the http.cookies module for more.
django.topics.testing.tools#django.test.Client.cookies
delete(path, data='', content_type='application/octet-stream', follow=False, secure=False, **extra) 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().
django.topics.testing.tools#django.test.Client.delete
force_login(user, backend=None) 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.
django.topics.testing.tools#django.test.Client.force_login
get(path, data=None, follow=False, secure=False, **extra) 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: >>> c = Client() >>> c.get('/customers/details/', {'name': 'fred', 'age': 7}) …will result in the evaluation of a GET request equivalent to: /customers/details/?name=fred&age=7 The extra keyword arguments parameter can be used to specify headers to be sent in the request. For example: >>> c = Client() >>> c.get('/customers/details/', {'name': 'fred', 'age': 7}, ... HTTP_ACCEPT='application/json') …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: >>> c = Client() >>> c.get('/customers/details/?name=fred&age=7') 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: >>> response = c.get('/redirect_me/', follow=True) >>> response.redirect_chain [('http://testserver/next/', 302), ('http://testserver/final/', 302)] If you set secure to True the client will emulate an HTTPS request.
django.topics.testing.tools#django.test.Client.get
head(path, data=None, follow=False, secure=False, **extra) 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.
django.topics.testing.tools#django.test.Client.head
login(**credentials) 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: >>> c = Client() >>> c.login(username='fred', password='secret') # Now you can access a view that's only available to logged-in users. 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.
django.topics.testing.tools#django.test.Client.login
logout() 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.
django.topics.testing.tools#django.test.Client.logout
options(path, data='', content_type='application/octet-stream', follow=False, secure=False, **extra) 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().
django.topics.testing.tools#django.test.Client.options