In order to make a Django project translatable, you have to add a minimal number of hooks to your Python code and templates. These hooks are called translation strings. They tell Django: “This text should be translated into the end user’s language, if a translation for this text is available in that language.” It’s your responsibility to mark translatable strings; the system can only translate strings it knows about.
Django then provides utilities to extract the translation strings into a message file. This file is a convenient way for translators to provide the equivalent of the translation strings in the target language. Once the translators have filled in the message file, it must be compiled. This process relies on the GNU gettext toolset.
Once this is done, Django takes care of translating web apps on the fly in each available language, according to users’ language preferences.
Django’s internationalization hooks are on by default, and that means there’s a bit of i18n-related overhead in certain places of the framework. If you don’t use internationalization, you should take the two seconds to set USE_I18N = False in your settings file. Then Django will make some optimizations so as not to load the internationalization machinery.
Note
Make sure you’ve activated translation for your project (the fastest way is to check if MIDDLEWARE includes django.middleware.locale.LocaleMiddleware). If you haven’t yet, see How Django discovers language preference.
Specify a translation string by using the function gettext(). It’s convention to import this as a shorter alias, _, to save typing.
Note
Python’s standard library gettext module installs _() into the global namespace, as an alias for gettext(). In Django, we have chosen not to follow this practice, for a couple of reasons:
What functions may be aliased as _?
Because of how xgettext (used by makemessages) works, only functions that take a single string argument can be imported as _:
In this example, the text "Welcome to my site." is marked as a translation string:
You could code this without using the alias. This example is identical to the previous one:
Translation works on computed values. This example is identical to the previous two:
Translation works on variables. Again, here’s an identical example:
(The caveat with using variables or computed values, as in the previous two examples, is that Django’s translation-string-detecting utility, django-admin makemessages, won’t be able to find these strings. More on makemessages later.)
The strings you pass to _() or gettext() can take placeholders, specified with Python’s standard named-string interpolation syntax. Example:
This technique lets language-specific translations reorder the placeholder text. For example, an English translation may be "Today is November 26.", while a Spanish translation may be "Hoy es 26 de noviembre." – with the month and the day placeholders swapped.
For this reason, you should use named-string interpolation (e.g., %(day)s) instead of positional interpolation (e.g., %s or %d) whenever you have more than a single parameter. If you used positional interpolation, translations wouldn’t be able to reorder placeholder text.
Since string extraction is done by the xgettext command, only syntaxes supported by gettext are supported by Django. In particular, Python f-strings are not yet supported by xgettext, and JavaScript template strings need gettext 0.21+.
If you would like to give translators hints about a translatable string, you can add a comment prefixed with the Translators keyword on the line preceding the string, e.g.:
The comment will then appear in the resulting .po file associated with the translatable construct located below it and should also be displayed by most translation tools.
Note
Just for completeness, this is the corresponding fragment of the resulting .po file:
This also works in templates. See Comments for translators in templates for more details.
Use the function django.utils.translation.gettext_noop() to mark a string as a translation string without translating it. The string is later translated from a variable.
Use this if you have constant strings that should be stored in the source language because they are exchanged over systems or users – such as strings in a database – but should be translated at the last possible point in time, such as when the string is presented to the user.
Use the function django.utils.translation.ngettext() to specify pluralized messages.
ngettext() takes three arguments: the singular translation string, the plural translation string and the number of objects.
This function is useful when you need your Django application to be localizable to languages where the number and complexity of plural forms is greater than the two forms used in English (‘object’ for the singular and ‘objects’ for all the cases where count is different from one, irrespective of its value.)
For example:
In this example the number of objects is passed to the translation languages as the count variable.
Note that pluralization is complicated and works differently in each language. Comparing count to 1 isn’t always the correct rule. This code looks sophisticated, but will produce incorrect results for some languages:
Don’t try to implement your own singular-or-plural logic; it won’t be correct. In a case like this, consider something like the following:
Note
When using ngettext(), make sure you use a single name for every extrapolated variable included in the literal. In the examples above, note how we used the name Python variable in both translation strings. This example, besides being incorrect in some languages as noted above, would fail:
You would get an error when running django-admin
compilemessages:
Sometimes words have several meanings, such as "May" in English, which refers to a month name and to a verb. To enable translators to translate these words correctly in different contexts, you can use the django.utils.translation.pgettext() function, or the django.utils.translation.npgettext() function if the string needs pluralization. Both take a context string as the first variable.
In the resulting .po file, the string will then appear as often as there are different contextual markers for the same string (the context will appear on the msgctxt line), allowing the translator to give a different translation for each of them.
For example:
or:
will appear in the .po file as:
Contextual markers are also supported by the translate and blocktranslate template tags.
Use the lazy versions of translation functions in django.utils.translation (easily recognizable by the lazy suffix in their names) to translate strings lazily – when the value is accessed rather than when they’re called.
These functions store a lazy reference to the string – not the actual translation. The translation itself will be done when the string is used in a string context, such as in template rendering.
This is essential when calls to these functions are located in code paths that are executed at module load time.
This is something that can easily happen when defining models, forms and model forms, because Django implements these such that their fields are actually class-level attributes. For that reason, make sure to use lazy translations in the following cases:
For example, to translate the help text of the name field in the following model, do the following:
You can mark names of ForeignKey, ManyToManyField or OneToOneField relationship as translatable by using their verbose_name options:
Just like you would do in verbose_name you should provide a lowercase verbose name text for the relation as Django will automatically titlecase it when required.
It is recommended to always provide explicit verbose_name and verbose_name_plural options rather than relying on the fallback English-centric and somewhat naïve determination of verbose names Django performs by looking at the model’s class name:
For model methods, you can provide translations to Django and the admin site with the description argument to the display() decorator:
The result of a gettext_lazy() call can be used wherever you would use a string (a str object) in other Django code, but it may not work with arbitrary Python code. For example, the following won’t work because the requests library doesn’t handle gettext_lazy objects:
You can avoid such problems by casting gettext_lazy() objects to text strings before passing them to non-Django code:
If you don’t like the long gettext_lazy name, you can alias it as _ (underscore), like so:
Using gettext_lazy() and ngettext_lazy() to mark strings in models and utility functions is a common operation. When you’re working with these objects elsewhere in your code, you should ensure that you don’t accidentally convert them to strings, because they should be converted as late as possible (so that the correct locale is in effect). This necessitates the use of the helper function described next.
When using lazy translation for a plural string (n[p]gettext_lazy), you generally don’t know the number argument at the time of the string definition. Therefore, you are authorized to pass a key name instead of an integer as the number argument. Then number will be looked up in the dictionary under that key during string interpolation. Here’s example:
If the string contains exactly one unnamed placeholder, you can interpolate directly with the number argument:
Python’s str.format() method will not work when either the format_string or any of the arguments to str.format() contains lazy translation objects. Instead, you can use django.utils.text.format_lazy(), which creates a lazy object that runs the str.format() method only when the result is included in a string. For example:
In this case, the lazy translations in result will only be converted to strings when result itself is used in a string (usually at template rendering time).
For any other case where you would like to delay the translation, but have to pass the translatable string as argument to another function, you can wrap this function inside a lazy call yourself. For example:
And then later:
The get_language_info() function provides detailed information about languages:
The name, name_local, and name_translated attributes of the dictionary contain the name of the language in English, in the language itself, and in your current active language respectively. The bidi attribute is True only for bi-directional languages.
The source of the language information is the django.conf.locale module. Similar access to this information is available for template code. See below.
Translations in Django templates uses two template tags and a slightly different syntax than in Python code. To give your template access to these tags, put {% load i18n %} toward the top of your template. As with all template tags, this tag needs to be loaded in all templates which use translations, even those templates that extend from other templates which have already loaded the i18n tag.
Warning
Translated strings will not be escaped when rendered in a template. This allows you to include HTML in translations, for example for emphasis, but potentially dangerous characters (e.g. ") will also be rendered unchanged.
The {% translate %} template tag translates either a constant string (enclosed in single or double quotes) or variable content:
If the noop option is present, variable lookup still takes place but the translation is skipped. This is useful when “stubbing out” content that will require translation in the future:
Internally, inline translations use an gettext() call.
In case a template var (myvar above) is passed to the tag, the tag will first resolve such variable to a string at run-time and then look up that string in the message catalogs.
It’s not possible to mix a template variable inside a string within {% translate %}. If your translations require strings with variables (placeholders), use {% blocktranslate %} instead.
If you’d like to retrieve a translated string without displaying it, you can use the following syntax:
In practice you’ll use this to get a string you can use in multiple places in a template or so you can use the output as an argument for other template tags or filters:
{% translate %} also supports contextual markers using the context keyword:
Contrarily to the translate tag, the blocktranslate tag allows you to mark complex sentences consisting of literals and variable content for translation by making use of placeholders:
To translate a template expression – say, accessing object attributes or using template filters – you need to bind the expression to a local variable for use within the translation block. Examples:
You can use multiple expressions inside a single blocktranslate tag:
Note
The previous more verbose format is still supported: {% blocktranslate with book|title as book_t and author|title as author_t %}
Other block tags (for example {% for %} or {% if %}) are not allowed inside a blocktranslate tag.
If resolving one of the block arguments fails, blocktranslate will fall back to the default language by deactivating the currently active language temporarily with the deactivate_all() function.
This tag also provides for pluralization. To use it:
An example:
A more complex example:
When you use both the pluralization feature and bind values to local variables in addition to the counter value, keep in mind that the blocktranslate construct is internally converted to an ngettext call. This means the same notes regarding ngettext variables apply.
Reverse URL lookups cannot be carried out within the blocktranslate and should be retrieved (and stored) beforehand:
If you’d like to retrieve a translated string without displaying it, you can use the following syntax:
In practice you’ll use this to get a string you can use in multiple places in a template or so you can use the output as an argument for other template tags or filters.
{% blocktranslate %} also supports contextual markers using the context keyword:
Another feature {% blocktranslate %} supports is the trimmed option. This option will remove newline characters from the beginning and the end of the content of the {% blocktranslate %} tag, replace any whitespace at the beginning and end of a line and merge all lines into one using a space character to separate them. This is quite useful for indenting the content of a {% blocktranslate %} tag without having the indentation characters end up in the corresponding entry in the PO file, which makes the translation process easier.
For instance, the following {% blocktranslate %} tag:
will result in the entry "First sentence. Second paragraph." in the PO file, compared to "\n  First sentence.\n  Second paragraph.\n", if the trimmed option had not been specified.
You can translate string literals passed as arguments to tags and filters by using the familiar _() syntax:
In this case, both the tag and the filter will see the translated string, so they don’t need to be aware of translations.
Note
In this example, the translation infrastructure will be passed the string "yes,no", not the individual strings "yes" and "no". The translated string will need to contain the comma so that the filter parsing code knows how to split up the arguments. For example, a German translator might translate the string "yes,no" as "ja,nein" (keeping the comma intact).
Just like with Python code, these notes for translators can be specified using comments, either with the comment tag:
or with the {# … #} one-line comment constructs:
Note
Just for completeness, these are the corresponding fragments of the resulting .po file:
If you want to select a language within a template, you can use the language template tag:
While the first occurrence of “Welcome to our page” uses the current language, the second will always be in English.
These tags also require a {% load i18n %}.
{% get_available_languages as LANGUAGES %} returns a list of tuples in which the first element is the language code and the second is the language name (translated into the currently active locale).
{% get_current_language as LANGUAGE_CODE %} returns the current user’s preferred language as a string. Example: en-us. See How Django discovers language preference.
{% get_current_language_bidi as LANGUAGE_BIDI %} returns the current locale’s direction. If True, it’s a right-to-left language, e.g. Hebrew, Arabic. If False it’s a left-to-right language, e.g. English, French, German, etc.
If you enable the django.template.context_processors.i18n context processor, then each RequestContext will have access to LANGUAGES, LANGUAGE_CODE, and LANGUAGE_BIDI as defined above.
You can also retrieve information about any of the available languages using provided template tags and filters. To get information about a single language, use the {% get_language_info %} tag:
You can then access the information:
You can also use the {% get_language_info_list %} template tag to retrieve information for a list of languages (e.g. active languages as specified in LANGUAGES). See the section about the set_language redirect view for an example of how to display a language selector using {% get_language_info_list %}.
In addition to LANGUAGES style list of tuples, {% get_language_info_list %} supports lists of language codes. If you do this in your view:
you can iterate over those languages in the template:
There are also some filters available for convenience:
Adding translations to JavaScript poses some problems:
Django provides an integrated solution for these problems: It passes the translations into JavaScript, so you can call gettext, etc., from within JavaScript.
The main solution to these problems is the following JavaScriptCatalog view, which generates a JavaScript code library with functions that mimic the gettext interface, plus an array of translation strings.
A view that produces a JavaScript code library with functions that mimic the gettext interface, plus an array of translation strings.
Attributes
Translation domain containing strings to add in the view output. Defaults to 'djangojs'.
A list of application names among installed applications. Those apps should contain a locale directory. All those catalogs plus all catalogs found in LOCALE_PATHS (which are always included) are merged into one catalog. Defaults to None, which means that all available translations from all INSTALLED_APPS are provided in the JavaScript output.
Example with default values:
Example with custom packages:
If your root URLconf uses i18n_patterns(), JavaScriptCatalog must also be wrapped by i18n_patterns() for the catalog to be correctly generated.
Example with i18n_patterns():
The precedence of translations is such that the packages appearing later in the packages argument have higher precedence than the ones appearing at the beginning. This is important in the case of clashing translations for the same literal.
If you use more than one JavaScriptCatalog view on a site and some of them define the same strings, the strings in the catalog that was loaded last take precedence.
To use the catalog, pull in the dynamically generated script like this:
This uses reverse URL lookup to find the URL of the JavaScript catalog view. When the catalog is loaded, your JavaScript code can use the following methods:
The gettext function behaves similarly to the standard gettext interface within your Python code:
The ngettext function provides an interface to pluralize words and phrases:
The interpolate function supports dynamically populating a format string. The interpolation syntax is borrowed from Python, so the interpolate function supports both positional and named interpolation:
Positional interpolation: obj contains a JavaScript Array object whose elements values are then sequentially interpolated in their corresponding fmt placeholders in the same order they appear. For example:
Named interpolation: This mode is selected by passing the optional boolean named parameter as true. obj contains a JavaScript object or associative array. For example:
You shouldn’t go over the top with string interpolation, though: this is still JavaScript, so the code has to make repeated regular-expression substitutions. This isn’t as fast as string interpolation in Python, so keep it to those cases where you really need it (for example, in conjunction with ngettext to produce proper pluralizations).
The get_format function has access to the configured i18n formatting settings and can retrieve the format string for a given setting name:
It has access to the following settings:
This is useful for maintaining formatting consistency with the Python-rendered values.
This emulates the gettext function but does nothing, returning whatever is passed to it:
This is useful for stubbing out portions of the code that will need translation in the future.
The pgettext function behaves like the Python variant (pgettext()), providing a contextually translated word:
The npgettext function also behaves like the Python variant (npgettext()), providing a pluralized contextually translated word:
The pluralidx function works in a similar way to the pluralize template filter, determining if a given count should use a plural form of a word or not:
In the simplest case, if no custom pluralization is needed, this returns false for the integer 1 and true for all other numbers.
However, pluralization is not this simple in all languages. If the language does not support pluralization, an empty value is provided.
Additionally, if there are complex rules around pluralization, the catalog view will render a conditional expression. This will evaluate to either a true (should pluralize) or false (should not pluralize) value.
In order to use another client-side library to handle translations, you may want to take advantage of the JSONCatalog view. It’s similar to JavaScriptCatalog but returns a JSON response.
See the documentation for JavaScriptCatalog to learn about possible values and use of the domain and packages attributes.
The response format is as follows:
The various JavaScript/JSON i18n views generate the catalog from .mo files on every request. Since its output is constant, at least for a given version of a site, it’s a good candidate for caching.
Server-side caching will reduce CPU load. It’s easily implemented with the cache_page() decorator. To trigger cache invalidation when your translations change, provide a version-dependent key prefix, as shown in the example below, or map the view at a version-dependent URL:
Client-side caching will save bandwidth and make your site load faster. If you’re using ETags (ConditionalGetMiddleware), you’re already covered. Otherwise, you can apply conditional decorators. In the following example, the cache is invalidated whenever you restart your application server:
You can even pre-generate the JavaScript catalog as part of your deployment procedure and serve it as a static file. This radical technique is implemented in django-statici18n.
Django provides two mechanisms to internationalize URL patterns:
Warning
Using either one of these features requires that an active language be set for each request; in other words, you need to have django.middleware.locale.LocaleMiddleware in your MIDDLEWARE setting.
This function can be used in a root URLconf and Django will automatically prepend the current active language code to all URL patterns defined within i18n_patterns().
Setting prefix_default_language to False removes the prefix from the default language (LANGUAGE_CODE). This can be useful when adding translations to existing site so that the current URLs won’t change.
Example URL patterns:
After defining these URL patterns, Django will automatically add the language prefix to the URL patterns that were added by the i18n_patterns function. Example:
With prefix_default_language=False and LANGUAGE_CODE='en', the URLs will be:
Warning
i18n_patterns() is only allowed in a root URLconf. Using it within an included URLconf will throw an ImproperlyConfigured exception.
Warning
Ensure that you don’t have non-prefixed URL patterns that might collide with an automatically-added language prefix.
URL patterns can also be marked translatable using the gettext_lazy() function. Example:
After you’ve created the translations, the reverse() function will return the URL in the active language. Example:
Warning
In most cases, it’s best to use translated URLs only within a language code prefixed block of patterns (using i18n_patterns()), to avoid the possibility that a carelessly translated URL causes a collision with a non-translated URL pattern.
If localized URLs get reversed in templates they always use the current language. To link to a URL in another language use the language template tag. It enables the given language in the enclosed template section:
The language tag expects the language code as the only argument.
Once the string literals of an application have been tagged for later translation, the translation themselves need to be written (or obtained). Here’s how that works.
The first step is to create a message file for a new language. A message file is a plain-text file, representing a single language, that contains all available translation strings and how they should be represented in the given language. Message files have a .po file extension.
Django comes with a tool, django-admin makemessages, that automates the creation and upkeep of these files.
Gettext utilities
The makemessages command (and compilemessages discussed later) use commands from the GNU gettext toolset: xgettext, msgfmt, msgmerge and msguniq.
The minimum version of the gettext utilities supported is 0.15.
To create or update a message file, run this command:
…where de is the locale name for the message file you want to create. For example, pt_BR for Brazilian Portuguese, de_AT for Austrian German or id for Indonesian.
The script should be run from one of two places:
The script runs over your project source tree or your application source tree and pulls out all strings marked for translation (see How Django discovers translations and be sure LOCALE_PATHS is configured correctly). It creates (or updates) a message file in the directory locale/LANG/LC_MESSAGES. In the de example, the file will be locale/de/LC_MESSAGES/django.po.
When you run makemessages from the root directory of your project, the extracted strings will be automatically distributed to the proper message files. That is, a string extracted from a file of an app containing a locale directory will go in a message file under that directory. A string extracted from a file of an app without any locale directory will either go in a message file under the directory listed first in LOCALE_PATHS or will generate an error if LOCALE_PATHS is empty.
By default django-admin makemessages examines every file that has the .html, .txt or .py file extension. If you want to override that default, use the --extension or -e option to specify the file extensions to examine:
Separate multiple extensions with commas and/or use -e or --extension multiple times:
Warning
When creating message files from JavaScript source code you need to use the special djangojs domain, not -e js.
Using Jinja2 templates?
makemessages doesn’t understand the syntax of Jinja2 templates. To extract strings from a project containing Jinja2 templates, use Message Extracting from Babel instead.
Here’s an example babel.cfg configuration file:
Make sure you list all extensions you’re using! Otherwise Babel won’t recognize the tags defined by these extensions and will ignore Jinja2 templates containing them entirely.
Babel provides similar features to makemessages, can replace it in general, and doesn’t depend on gettext. For more information, read its documentation about working with message catalogs.
No gettext?
If you don’t have the gettext utilities installed, makemessages will create empty files. If that’s the case, either install the gettext utilities or copy the English message file (locale/en/LC_MESSAGES/django.po) if available and use it as a starting point, which is an empty translation file.
Working on Windows?
If you’re using Windows and need to install the GNU gettext utilities so makemessages works, see gettext on Windows for more information.
Each .po file contains a small bit of metadata, such as the translation maintainer’s contact information, but the bulk of the file is a list of messages – mappings between translation strings and the actual translated text for the particular language.
For example, if your Django app contained a translation string for the text "Welcome to my site.", like so:
…then django-admin makemessages will have created a .po file containing the following snippet – a message:
A quick explanation:
Long messages are a special case. There, the first string directly after the msgstr (or msgid) is an empty string. Then the content itself will be written over the next few lines as one string per line. Those strings are directly concatenated. Don’t forget trailing spaces within the strings; otherwise, they’ll be tacked together without whitespace!
Mind your charset
Due to the way the gettext tools work internally and because we want to allow non-ASCII source strings in Django’s core and your applications, you must use UTF-8 as the encoding for your PO files (the default when PO files are created). This means that everybody will be using the same encoding, which is important when Django processes the PO files.
Fuzzy entries
makemessages sometimes generates translation entries marked as fuzzy, e.g. when translations are inferred from previously translated strings. By default, fuzzy entries are not processed by compilemessages.
To reexamine all source code and templates for new translation strings and update all message files for all languages, run this:
After you create your message file – and each time you make changes to it – you’ll need to compile it into a more efficient form, for use by gettext. Do this with the django-admin compilemessages utility.
This tool runs over all available .po files and creates .mo files, which are binary files optimized for use by gettext. In the same directory from which you ran django-admin makemessages, run django-admin compilemessages like this:
That’s it. Your translations are ready for use.
Working on Windows?
If you’re using Windows and need to install the GNU gettext utilities so django-admin compilemessages works see gettext on Windows for more information.
.po files: Encoding and BOM usage.
Django only supports .po files encoded in UTF-8 and without any BOM (Byte Order Mark) so if your text editor adds such marks to the beginning of files by default then you will need to reconfigure it.
In some cases, such as strings with a percent sign followed by a space and a string conversion type (e.g. _("10% interest")), gettext() incorrectly flags strings with python-format.
If you try to compile message files with incorrectly flagged strings, you’ll get an error message like number of format specifications in 'msgid' and
'msgstr' does not match or 'msgstr' is not a valid Python format string,
unlike 'msgid'.
To workaround this, you can escape percent signs by adding a second percent sign:
Or you can use no-python-format so that all percent signs are treated as literals:
You create and update the message files the same way as the other Django message files – with the django-admin makemessages tool. The only difference is you need to explicitly specify what in gettext parlance is known as a domain in this case the djangojs domain, by providing a -d
djangojs parameter, like this:
This would create or update the message file for JavaScript for German. After updating message files, run django-admin compilemessages the same way as you do with normal Django message files.
This is only needed for people who either want to extract message IDs or compile message files (.po). Translation work itself involves editing existing files of this type, but if you want to create your own message files, or want to test or compile a changed message file, download a precompiled binary installer.
You may also use gettext binaries you have obtained elsewhere, so long as the xgettext --version command works properly. Do not attempt to use Django translation utilities with a gettext package if the command xgettext
--version entered at a Windows command prompt causes a popup window saying “xgettext.exe has generated errors and will be closed by Windows”.
If you want to pass additional parameters to xgettext, you need to create a custom makemessages command and override its xgettext_options attribute:
If you need more flexibility, you could also add a new argument to your custom makemessages command:
As a convenience, Django comes with a view, django.views.i18n.set_language(), that sets a user’s language preference and redirects to a given URL or, by default, back to the previous page.
Activate this view by adding the following line to your URLconf:
(Note that this example makes the view available at /i18n/setlang/.)
Warning
Make sure that you don’t include the above URL within i18n_patterns() - it needs to be language-independent itself to work correctly.
The view expects to be called via the POST method, with a language parameter set in request. If session support is enabled, the view saves the language choice in the user’s session. It also saves the language choice in a cookie that is named django_language by default. (The name can be changed through the LANGUAGE_COOKIE_NAME setting.)
After setting the language choice, Django looks for a next parameter in the POST or GET data. If that is found and Django considers it to be a safe URL (i.e. it doesn’t point to a different host and uses a safe scheme), a redirect to that URL will be performed. Otherwise, Django may fall back to redirecting the user to the URL from the Referer header or, if it is not set, to /, depending on the nature of the request:
Here’s example HTML template code:
In this example, Django looks up the URL of the page to which the user will be redirected in the redirect_to context variable.
You may want to set the active language for the current session explicitly. Perhaps a user’s language preference is retrieved from another system, for example. You’ve already been introduced to django.utils.translation.activate(). That applies to the current thread only. To persist the language for the entire session in a cookie, set the LANGUAGE_COOKIE_NAME cookie on the response:
You would typically want to use both: django.utils.translation.activate() changes the language for this thread, and setting the cookie makes this preference persist in future requests.
While Django provides a rich set of i18n tools for use in views and templates, it does not restrict the usage to Django-specific code. The Django translation mechanisms can be used to translate arbitrary texts to any language that is supported by Django (as long as an appropriate translation catalog exists, of course). You can load a translation catalog, activate it and translate text to language of your choice, but remember to switch back to original language, as activating a translation catalog is done on per-thread basis and such change will affect code running in the same thread.
For example:
Calling this function with the value 'de' will give you "Willkommen", regardless of LANGUAGE_CODE and language set by middleware.
Functions of particular interest are django.utils.translation.get_language() which returns the language used in the current thread, django.utils.translation.activate() which activates a translation catalog for the current thread, and django.utils.translation.check_for_language() which checks if the given language is supported by Django.
To help write more concise code, there is also a context manager django.utils.translation.override() that stores the current language on enter and restores it on exit. With it, the above example becomes:
A number of settings can be used to adjust language cookie options:
Django’s translation machinery uses the standard gettext module that comes with Python. If you know gettext, you might note these specialties in the way Django does translation:
Once you’ve prepared your translations – or, if you want to use the translations that come with Django – you’ll need to activate translation for your app.
Behind the scenes, Django has a very flexible model of deciding which language should be used – installation-wide, for a particular user, or both.
To set an installation-wide language preference, set LANGUAGE_CODE. Django uses this language as the default translation – the final attempt if no better matching translation is found through one of the methods employed by the locale middleware (see below).
If all you want is to run Django with your native language all you need to do is set LANGUAGE_CODE and make sure the corresponding message files and their compiled versions (.mo) exist.
If you want to let each individual user specify which language they prefer, then you also need to use the LocaleMiddleware. LocaleMiddleware enables language selection based on data from the request. It customizes content for each user.
To use LocaleMiddleware, add 'django.middleware.locale.LocaleMiddleware' to your MIDDLEWARE setting. Because middleware order matters, follow these guidelines:
For example, your MIDDLEWARE might look like this:
(For more on middleware, see the middleware documentation.)
LocaleMiddleware tries to determine the user’s language preference by following this algorithm:
Failing that, it looks for a cookie.
The name of the cookie used is set by the LANGUAGE_COOKIE_NAME setting. (The default name is django_language.)
Notes:
Only languages listed in the LANGUAGES setting can be selected. If you want to restrict the language selection to a subset of provided languages (because your application doesn’t provide all those languages), set LANGUAGES to a list of languages. For example:
This example restricts languages that are available for automatic selection to German and English (and any sublanguage, like de-ch or en-us).
If you define a custom LANGUAGES setting, as explained in the previous bullet, you can mark the language names as translation strings – but use gettext_lazy() instead of gettext() to avoid a circular import.
Here’s a sample settings file:
Once LocaleMiddleware determines the user’s preference, it makes this preference available as request.LANGUAGE_CODE for each HttpRequest. Feel free to read this value in your view code. Here’s an example:
Note that, with static (middleware-less) translation, the language is in settings.LANGUAGE_CODE, while with dynamic (middleware) translation, it’s in request.LANGUAGE_CODE.
At runtime, Django builds an in-memory unified catalog of literals-translations. To achieve this it looks for translations by following this algorithm regarding the order in which it examines the different file paths to load the compiled message files (.mo) and the precedence of multiple translations for the same literal:
See also
The translations for literals included in JavaScript assets are looked up following a similar but not identical algorithm. See JavaScriptCatalog for more details.
You can also put custom format files in the LOCALE_PATHS directories if you also set FORMAT_MODULE_PATH.
In all cases the name of the directory containing the translation is expected to be named using locale name notation. E.g. de, pt_BR, es_AR, etc. Untranslated strings for territorial language variants use the translations of the generic language. For example, untranslated pt_BR strings use pt translations.
This way, you can write applications that include their own translations, and you can override base translations in your project. Or, you can build a big project out of several apps and put all translations into one big common message file specific to the project you are composing. The choice is yours.
All message file repositories are structured the same way. They are:
To create message files, you use the django-admin makemessages tool. And you use django-admin compilemessages to produce the binary .mo files that are used by gettext.
You can also run django-admin compilemessages
--settings=path.to.settings to make the compiler process all the directories in your LOCALE_PATHS setting.
Django makes the general assumption that the original strings in a translatable project are written in English. You can choose another language, but you must be aware of certain limitations:


A function that takes a full Python import path to another URLconf module that should be “included” in this place. Optionally, the application namespace and instance namespace where the entries will be included into can also be specified.
Usually, the application namespace should be specified by the included module. If an application namespace is set, the namespace argument can be used to set a different instance namespace.
include() also accepts as an argument either an iterable that returns URL patterns or a 2-tuple containing such iterable plus the names of the application namespaces.


The view function that would be used to serve the URL
The arguments that would be passed to the view function, as parsed from the URL.
The keyword arguments that would be passed to the view function, as parsed from the URL.
The name of the URL pattern that matches the URL.
The route of the matching URL pattern.
For example, if path('users/<id>/', ...) is the matching pattern, route will contain 'users/<id>/'.
The list of URL patterns tried before the URL either matched one or exhausted available patterns.
The application namespace for the URL pattern that matches the URL.
The list of individual namespace components in the full application namespace for the URL pattern that matches the URL. For example, if the app_name is 'foo:bar', then app_names will be ['foo', 'bar'].
The instance namespace for the URL pattern that matches the URL.
The list of individual namespace components in the full instance namespace for the URL pattern that matches the URL. i.e., if the namespace is foo:bar, then namespaces will be ['foo', 'bar'].
The name of the view that matches the URL, including the namespace if there is one.


The application namespace for the URL pattern that matches the URL.


The list of individual namespace components in the full application namespace for the URL pattern that matches the URL. For example, if the app_name is 'foo:bar', then app_names will be ['foo', 'bar'].


The arguments that would be passed to the view function, as parsed from the URL.


The view function that would be used to serve the URL


The keyword arguments that would be passed to the view function, as parsed from the URL.


The instance namespace for the URL pattern that matches the URL.


The list of individual namespace components in the full instance namespace for the URL pattern that matches the URL. i.e., if the namespace is foo:bar, then namespaces will be ['foo', 'bar'].


The route of the matching URL pattern.
For example, if path('users/<id>/', ...) is the matching pattern, route will contain 'users/<id>/'.


The list of URL patterns tried before the URL either matched one or exhausted available patterns.


The name of the URL pattern that matches the URL.


The name of the view that matches the URL, including the namespace if there is one.


Adds a Cache-Control: max-age=0, no-cache, no-store, must-revalidate,
private header to a response to indicate that a page should never be cached.


Returns a cache key based on the request path. It can be used in the request phase because it pulls the list of headers to take into account from the global path registry and uses those to build a cache key to check against.
If there is no headerlist stored, the page needs to be rebuilt, so this function returns None.


Returns the max-age from the response Cache-Control header as an integer (or None if it wasn’t found or wasn’t an integer).


Learns what headers to take into account for some request path from the response object. It stores those headers in a global path registry so that later access to that path will know what headers to take into account without building the response object itself. The headers are named in the Vary header of the response, but we want to prevent response generation.
The list of headers to use for cache key generation is stored in the same cache as the pages themselves. If the cache ages some data out of the cache, this means that we have to build the response once to get at the Vary header and so at the list of headers to use for the cache key.


This function patches the Cache-Control header by adding all keyword arguments to it. The transformation is as follows:


Adds some useful headers to the given HttpResponse object:
Each header is only added if it isn’t already set.
cache_timeout is in seconds. The CACHE_MIDDLEWARE_SECONDS setting is used by default.


Adds (or updates) the Vary header in the given HttpResponse object. newheaders is a list of header names that should be in Vary. If headers contains an asterisk, then Vary header will consist of a single asterisk '*', according to RFC 7231#section-7.1.4. Otherwise, existing headers in Vary aren’t removed.


Parses a string and returns a datetime.date.


Parses a string and returns a datetime.datetime.
UTC offsets are supported; if value describes one, the result’s tzinfo attribute is a datetime.timezone instance.


Parses a string and returns a datetime.timedelta.
Expects data in the format "DD HH:MM:SS.uuuuuu", "DD HH:MM:SS,uuuuuu", or as specified by ISO 8601 (e.g. P4DT1H15M20S which is equivalent to 4 1:15:20) or PostgreSQL’s day-time interval format (e.g. 3 days 04:05:06).


Parses a string and returns a datetime.time.
UTC offsets aren’t supported; if value describes one, the result is None.


Marks a middleware as asynchronous-only. Django will wrap it in an asynchronous event loop when it is called from the WSGI request path.


Given a middleware class, returns a view decorator. This lets you use middleware functionality on a per-view basis. The middleware is created with no params passed.
It assumes middleware that’s compatible with the old style of Django 1.9 and earlier (having methods like process_request(), process_exception(), and process_response()).


Like decorator_from_middleware, but returns a function that accepts the arguments to be passed to the middleware_class. For example, the cache_page() decorator is created from the CacheMiddleware like this:


Converts a function decorator into a method decorator. It can be used to decorate methods or classes; in the latter case, name is the name of the method to be decorated and is required.
decorator may also be a list or tuple of functions. They are wrapped in reverse order so that the call order is the order in which the functions appear in the list/tuple.
See decorating class based views for example usage.


Marks a middleware as sync and async compatible, this allows to avoid converting requests. You must implement detection of the current request type to use this decorator. See asynchronous middleware documentation for details.


Marks a middleware as synchronous-only. (The default in Django, but this allows you to future-proof if the default ever changes in a future release.)


Escapes the unsafe characters from the path portion of a Uniform Resource Identifier (URI).


Convert a file system path to a URI portion that is suitable for inclusion in a URL. The path is assumed to be either UTF-8 bytes, string, or a Path.
This method will encode certain characters that would normally be recognized as special characters for URIs. Note that this method does not encode the ‘ character, as it is a valid character within URIs. See encodeURIComponent() JavaScript function for more details.
Returns an ASCII string containing the encoded result.


Similar to smart_bytes, except that lazy instances are resolved to bytestrings, rather than kept as lazy objects.
If strings_only is True, don’t convert (some) non-string-like objects.


Similar to smart_str(), except that lazy instances are resolved to strings, rather than kept as lazy objects.
If strings_only is True, don’t convert (some) non-string-like objects.


Convert an Internationalized Resource Identifier (IRI) portion to a URI portion that is suitable for inclusion in a URL.
This is the algorithm from section 3.1 of RFC 3987#section-3.1, slightly simplified since the input is assumed to be a string rather than an arbitrary byte stream.
Takes an IRI (string or UTF-8 bytes) and returns a string containing the encoded result.


Determine if the object instance is of a protected type.
Objects of protected types are preserved as-is when passed to force_str(strings_only=True).


Returns a bytestring version of arbitrary object s, encoded as specified in encoding.
If strings_only is True, don’t convert (some) non-string-like objects.


Returns a str object representing arbitrary object s. Treats bytestrings using the encoding codec.
If strings_only is True, don’t convert (some) non-string-like objects.


Converts a Uniform Resource Identifier into an Internationalized Resource Identifier.
This is an algorithm from section 3.2 of RFC 3987#section-3.2.
Takes a URI in ASCII bytes and returns a string containing the encoded result.


Creates a TagURI.
See https://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id


Base class for all syndication feeds. Subclasses should provide write().
Initialize the feed with the given dictionary of metadata, which applies to the entire feed.
Any extra keyword arguments you pass to __init__ will be stored in self.feed.
All parameters should be strings, except categories, which should be a sequence of strings.
Adds an item to the feed. All args are expected to be strings except pubdate and updateddate, which are datetime.datetime objects, and enclosures, which is a list of Enclosure instances.
Return extra attributes to place on the root (i.e. feed/channel) element. Called from write().
Add elements in the root (i.e. feed/channel) element. Called from write().
Return extra attributes to place on each item (i.e. item/entry) element.
Add elements on each item (i.e. item/entry) element.
Outputs the feed in the given encoding to outfile, which is a file-like object. Subclasses should override this.
Returns the feed in the given encoding as a string.
Returns the latest pubdate or updateddate for all items in the feed. If no items have either of these attributes this returns the current UTC date/time.


Initialize the feed with the given dictionary of metadata, which applies to the entire feed.
Any extra keyword arguments you pass to __init__ will be stored in self.feed.
All parameters should be strings, except categories, which should be a sequence of strings.


Adds an item to the feed. All args are expected to be strings except pubdate and updateddate, which are datetime.datetime objects, and enclosures, which is a list of Enclosure instances.


Add elements on each item (i.e. item/entry) element.


Add elements in the root (i.e. feed/channel) element. Called from write().


Return extra attributes to place on each item (i.e. item/entry) element.


Returns the latest pubdate or updateddate for all items in the feed. If no items have either of these attributes this returns the current UTC date/time.


Return extra attributes to place on the root (i.e. feed/channel) element. Called from write().


Outputs the feed in the given encoding to outfile, which is a file-like object. Subclasses should override this.


Returns the feed in the given encoding as a string.


The @cached_property decorator caches the result of a method with a single self argument as a property. The cached result will persist as long as the instance does, so if the instance is passed around and the function subsequently invoked, the cached result will be returned.
Consider a typical case, where a view might need to call a model’s method to perform some computation, before placing the model instance into the context, where the template might invoke the method once more:
And in the template you would have:
Here, friends() will be called twice. Since the instance person in the view and the template are the same, decorating the friends() method with @cached_property can avoid that:
Note that as the method is now a property, in Python code it will need to be accessed appropriately:
The cached value can be treated like an ordinary attribute of the instance:
Because of the way the descriptor protocol works, using del (or delattr) on a cached_property that hasn’t been accessed raises AttributeError.
As well as offering potential performance advantages, @cached_property can ensure that an attribute’s value does not change unexpectedly over the life of an instance. This could occur with a method whose computation is based on datetime.now(), or if a change were saved to the database by some other process in the brief interval between subsequent invocations of a method on the same instance.
You can make cached properties of methods. For example, if you had an expensive get_friends() method and wanted to allow calling it without retrieving the cached value, you could write:
While person.get_friends() will recompute the friends on each call, the value of the cached property will persist until you delete it as described above:


Similar to @classmethod, the @classproperty decorator converts the result of a method with a single cls argument into a property that can be accessed directly from the class.


Django offers many utility functions (particularly in django.utils) that take a string as their first argument and do something to that string. These functions are used by template filters as well as directly in other code.
If you write your own similar functions and deal with translations, you’ll face the problem of what to do when the first argument is a lazy translation object. You don’t want to convert it to a string immediately, because you might be using this function outside of a view (and hence the current thread’s locale setting will not be correct).
For cases like this, use the django.utils.functional.keep_lazy() decorator. It modifies the function so that if it’s called with a lazy translation as one of its arguments, the function evaluation is delayed until it needs to be converted to a string.
For example:
The keep_lazy() decorator takes a number of extra arguments (*args) specifying the type(s) that the original function can return. A common use case is to have functions that return text. For these, you can pass the str type to keep_lazy (or use the keep_lazy_text() decorator described in the next section).
Using this decorator means you can write your function and assume that the input is a proper string, then add support for lazy translation objects at the end.


A shortcut for keep_lazy(str)(func).
If you have a function that returns text and you want to be able to take lazy arguments while delaying their evaluation, you can use this decorator:


Similar to escape(), except that it doesn’t operate on pre-escaped strings, so it will not double escape.


Returns the given text with ampersands, quotes and angle brackets encoded for use in HTML. The input is first coerced to a string and the output has mark_safe() applied.


This is similar to str.format(), except that it is appropriate for building up HTML fragments. All args and kwargs are passed through conditional_escape() before being passed to str.format().
For the case of building up small HTML fragments, this function is to be preferred over string interpolation using % or str.format() directly, because it applies escaping to all arguments - just like the template system applies escaping by default.
So, instead of writing:
You should instead use:
This has the advantage that you don’t need to apply escape() to each argument and risk a bug and an XSS vulnerability if you forget one.
Note that although this function uses str.format() to do the interpolation, some of the formatting options provided by str.format() (e.g. number formatting) will not work, since all arguments are passed through conditional_escape() which (ultimately) calls force_str() on the values.


A wrapper of format_html(), for the common case of a group of arguments that need to be formatted using the same format string, and then joined using sep. sep is also passed through conditional_escape().
args_generator should be an iterator that returns the sequence of args that will be passed to format_html(). For example:


The __html__() method on a class helps non-Django templates detect classes whose output doesn’t require HTML escaping.
This decorator defines the __html__() method on the decorated class by wrapping __str__() in mark_safe(). Ensure the __str__() method does indeed return text that doesn’t require HTML escaping.


Tries to remove anything that looks like an HTML tag from the string, that is anything contained within <>.
Absolutely NO guarantee is provided about the resulting string being HTML safe. So NEVER mark safe the result of a strip_tag call without escaping it first, for example with escape().
For example:
If value is "Joel <button>is</button> a slug" the return value will be "Joel is a slug".
If you are looking for a more robust solution, take a look at the bleach Python library.


Converts a base 36 string to an integer.


Formats the time to match the RFC 1123#section-5.2.14 date format as specified by HTTP RFC 7231#section-7.1.1.1.
Accepts a floating point number expressed in seconds since the epoch in UTC–such as that outputted by time.time(). If set to None, defaults to the current time.
Outputs a string in the format Wdy, DD Mon YYYY HH:MM:SS GMT.


Converts a positive integer to a base 36 string.


A version of Python’s urllib.parse.urlencode() function that can operate on MultiValueDict and non-string values.


Decodes a base64 encoded string, adding back any trailing equal signs that might have been stripped.


Encodes a bytestring to a base64 string for use in URLs, stripping any trailing equal signs.


This handler sends an email to the site ADMINS for each log message it receives.
If the log record contains a request attribute, the full details of the request will be included in the email. The email subject will include the phrase “internal IP” if the client’s IP address is in the INTERNAL_IPS setting; if not, it will include “EXTERNAL IP”.
If the log record contains stack trace information, that stack trace will be included in the email.
The include_html argument of AdminEmailHandler is used to control whether the traceback email includes an HTML attachment containing the full content of the debug web page that would have been produced if DEBUG were True. To set this value in your configuration, include it in the handler definition for django.utils.log.AdminEmailHandler, like this:
Be aware of the security implications of logging when using the AdminEmailHandler.
By setting the email_backend argument of AdminEmailHandler, the email backend that is being used by the handler can be overridden, like this:
By default, an instance of the email backend specified in EMAIL_BACKEND will be used.
The reporter_class argument of AdminEmailHandler allows providing an django.views.debug.ExceptionReporter subclass to customize the traceback text sent in the email body. You provide a string import path to the class you wish to use, like this:
Sends emails to admin users. To customize this behavior, you can subclass the AdminEmailHandler class and override this method.


Sends emails to admin users. To customize this behavior, you can subclass the AdminEmailHandler class and override this method.


This filter accepts a callback function (which should accept a single argument, the record to be logged), and calls it for each record that passes through the filter. Handling of that record will not proceed if the callback returns False.
For instance, to filter out UnreadablePostError (raised when a user cancels an upload) from the admin emails, you would create a filter function:
and then add it to your logging config:


This filter will only pass on records when settings.DEBUG is False.
This filter is used as follows in the default LOGGING configuration to ensure that the AdminEmailHandler only sends error emails to admins when DEBUG is False:


This filter is similar to RequireDebugFalse, except that records are passed only when DEBUG is True.


Imports a dotted module path and returns the attribute/class designated by the last name in the path. Raises ImportError if the import failed. For example:
is equivalent to:


Explicitly mark a string as safe for (HTML) output purposes. The returned object can be used everywhere a string is appropriate.
Can be called multiple times on a single string.
Can also be used as a decorator.
For building up fragments of HTML, you should normally be using django.utils.html.format_html() instead.
String marked safe will become unsafe again if modified. For example:


A str subclass that has been specifically marked as “safe” (requires no further escaping) for HTML output purposes.


A version of str.format() for when format_string, args, and/or kwargs contain lazy objects. The first argument is the string to be formatted. For example:
This example allows translators to translate part of the URL. If “person” is translated to “persona”, the regular expression will match persona/(?P<pk>\d+)/$, e.g. persona/5/.


Converts a string to a URL slug by:
For example:
If you want to allow Unicode characters, pass allow_unicode=True. For example:
In older versions, leading and trailing dashes and underscores are not removed.


Sets the current time zone. The timezone argument must be an instance of a tzinfo subclass or a time zone name.


Returns a tzinfo instance that represents the current time zone.


Returns the name of the current time zone.


Returns a tzinfo instance that represents the default time zone.


Returns the name of the default time zone.


Returns a tzinfo instance that represents a time zone with a fixed offset from UTC.
offset is a datetime.timedelta or an integer number of minutes. Use positive values for time zones east of UTC and negative values for west of UTC.


Returns True if value is aware, False if it is naive. This function assumes that value is a datetime.


Returns True if value is naive, False if it is aware. This function assumes that value is a datetime.


Uses localtime() to convert an aware datetime to a date() in a different time zone, by default the current time zone.
When value is omitted, it defaults to now().
This function doesn’t work on naive datetimes.


Converts an aware datetime to a different time zone, by default the current time zone.
When value is omitted, it defaults to now().
This function doesn’t work on naive datetimes; use make_aware() instead.


Returns an aware datetime that represents the same point in time as value in timezone, value being a naive datetime. If timezone is set to None, it defaults to the current time zone.
Deprecated since version 4.0: When using pytz, the pytz.AmbiguousTimeError exception is raised if you try to make value aware during a DST transition where the same time occurs twice (when reverting from DST). Setting is_dst to True or False will avoid the exception by choosing if the time is pre-transition or post-transition respectively.
When using pytz, the pytz.NonExistentTimeError exception is raised if you try to make value aware during a DST transition such that the time never occurred. For example, if the 2:00 hour is skipped during a DST transition, trying to make 2:30 aware in that time zone will raise an exception. To avoid that you can use is_dst to specify how make_aware() should interpret such a nonexistent time. If is_dst=True then the above time would be interpreted as 2:30 DST time (equivalent to 1:30 local time). Conversely, if is_dst=False the time would be interpreted as 2:30 standard time (equivalent to 3:30 local time).
The is_dst parameter has no effect when using non-pytz timezone implementations.
The is_dst parameter is deprecated and will be removed in Django 5.0.


Returns a naive datetime that represents in timezone the same point in time as value, value being an aware datetime. If timezone is set to None, it defaults to the current time zone.


Returns a datetime that represents the current point in time. Exactly what’s returned depends on the value of USE_TZ:


This is a Python context manager that sets the current time zone on entry with activate(), and restores the previously active time zone on exit. If the timezone argument is None, the current time zone is unset on entry with deactivate() instead.
override is also usable as a function decorator.


Fetches the translation object for a given language and activates it as the current translation object for the current thread.


Checks whether there is a global language file for the given language code (e.g. ‘fr’, ‘pt_BR’). This is used to decide whether a user-provided language is available.


Deactivates the currently active translation object so that further _ calls will resolve against the default translation object, again.


Makes the active translation object a NullTranslations() instance. This is useful when we want delayed translations to appear as the original string for some reason.


Returns the currently selected language code. Returns None if translations are temporarily deactivated (by deactivate_all() or when None is passed to override()).


Returns selected language’s BiDi layout:


Analyzes the request to find what language the user wants the system to show. Only languages listed in settings.LANGUAGES are taken into account. If the user requests a sublanguage where we have a main language, we send out the main language.
If check_path is True, the function first checks the requested URL for whether its path begins with a language code listed in the LANGUAGES setting.


Returns lang_code if it’s in the LANGUAGES setting, possibly selecting a more generic variant. For example, 'es' is returned if lang_code is 'es-ar' and 'es' is in LANGUAGES but 'es-ar' isn’t.
If strict is False (the default), a country-specific variant may be returned when neither the language code nor its generic variant is found. For example, if only 'es-co' is in LANGUAGES, that’s returned for lang_codes like 'es' and 'es-ar'. Those matches aren’t returned if strict=True.
Raises LookupError if nothing is found.


Translates message and returns it as a string.


Marks strings for translation but doesn’t translate them now. This can be used to store strings in global variables that should stay in the base language (because they might be used externally) and will be translated later.


Translates singular and plural and returns the appropriate string based on number.


Translates singular and plural and returns the appropriate string based on number and the context.


Same as the non-lazy versions above, but using lazy execution.
See lazy translations documentation.


A Python context manager that uses django.utils.translation.activate() to fetch the translation object for a given language, activates it as the translation object for the current thread and reactivates the previous active language on exit. Optionally, it can deactivate the temporary translation on exit with django.utils.translation.deactivate() if the deactivate argument is True. If you pass None as the language argument, a NullTranslations() instance is activated within the context.
override is also usable as a function decorator.


Translates message given the context and returns it as a string.
For more information, see Contextual markers.


Turns a Django template into something that is understood by xgettext. It does so by translating the Django translation tags into standard gettext function invocations.


Turns a language name (en-us) into a locale name (en_US).


These validators are available from the django.contrib.postgres.validators module.
Validates that the given keys are contained in the value. If strict is True, then it also checks that there are no other keys present.
The messages passed should be a dict containing the keys missing_keys and/or extra_keys.
Note
Note that this checks only for the existence of a given key, not that the value of a key is non-empty.
Validates that the upper bound of the range is not greater than limit_value.
Validates that the lower bound of the range is not less than the limit_value.


A validator is a callable that takes a value and raises a ValidationError if it doesn’t meet some criteria. Validators can be useful for re-using validation logic between different types of fields.
For example, here’s a validator that only allows even numbers:
You can add this to a model field via the field’s validators argument:
Because values are converted to Python before validators are run, you can even use the same validator with forms:
You can also use a class with a __call__() method for more complex or configurable validators. RegexValidator, for example, uses this technique. If a class-based validator is used in the validators model field option, you should make sure it is serializable by the migration framework by adding deconstruct() and __eq__() methods.
See the form validation for more information on how validators are run in forms, and Validating objects for how they’re run in models. Note that validators will not be run automatically when you save a model, but if you are using a ModelForm, it will run your validators on any fields that are included in your form. See the ModelForm documentation for information on how model validation interacts with forms.
The django.core.validators module contains a collection of callable validators for use with model and form fields. They’re used internally but are available for use with your own fields, too. They can be used in addition to, or in lieu of custom field.clean() methods.
A RegexValidator searches the provided value for a given regular expression with re.search(). By default, raises a ValidationError with message and code if a match is not found. Its behavior can be inverted by setting inverse_match to True, in which case the ValidationError is raised when a match is found.
The regular expression pattern to search for within the provided value, using re.search(). This may be a string or a pre-compiled regular expression created with re.compile(). Defaults to the empty string, which will be found in every possible value.
The error message used by ValidationError if validation fails. Defaults to "Enter a valid value".
The error code used by ValidationError if validation fails. Defaults to "invalid".
The match mode for regex. Defaults to False.
The regex flags used when compiling the regular expression string regex. If regex is a pre-compiled regular expression, and flags is overridden, TypeError is raised. Defaults to 0.
The error message used by ValidationError if validation fails. Defaults to "Enter a valid email address".
The error code used by ValidationError if validation fails. Defaults to "invalid".
Allowlist of email domains. By default, a regular expression (the domain_regex attribute) is used to validate whatever appears after the @ sign. However, if that string appears in the allowlist, this validation is bypassed. If not provided, the default allowlist is ['localhost']. Other domains that don’t contain a dot won’t pass validation, so you’d need to add them to the allowlist as necessary.
Deprecated since version 3.2: The whitelist parameter is deprecated. Use allowlist instead. The undocumented domain_whitelist attribute is deprecated. Use domain_allowlist instead.
A RegexValidator subclass that ensures a value looks like a URL, and raises an error code of 'invalid' if it doesn’t.
Loopback addresses and reserved IP spaces are considered valid. Literal IPv6 addresses (RFC 3986#section-3.2.2) and Unicode domains are both supported.
In addition to the optional arguments of its parent RegexValidator class, URLValidator accepts an extra optional attribute:
URL/URI scheme list to validate against. If not provided, the default list is ['http', 'https', 'ftp', 'ftps']. As a reference, the IANA website provides a full list of valid URI schemes.
An EmailValidator instance without any customizations.
A RegexValidator instance that ensures a value consists of only letters, numbers, underscores or hyphens.
A RegexValidator instance that ensures a value consists of only Unicode letters, numbers, underscores, or hyphens.
A RegexValidator instance that ensures a value looks like an IPv4 address.
Uses django.utils.ipv6 to check the validity of an IPv6 address.
Uses both validate_ipv4_address and validate_ipv6_address to ensure a value is either a valid IPv4 or IPv6 address.
A RegexValidator instance that ensures a value is a comma-separated list of integers.
Returns a RegexValidator instance that ensures a string consists of integers separated by sep. It allows negative integers when allow_negative is True.
Raises a ValidationError with a code of 'max_value' if value is greater than limit_value, which may be a callable.
Raises a ValidationError with a code of 'min_value' if value is less than limit_value, which may be a callable.
Raises a ValidationError with a code of 'max_length' if the length of value is greater than limit_value, which may be a callable.
Raises a ValidationError with a code of 'min_length' if the length of value is less than limit_value, which may be a callable.
Raises ValidationError with the following codes:
Raises a ValidationError with a code of 'invalid_extension' if the extension of value.name (value is a File) isn’t found in allowed_extensions. The extension is compared case-insensitively with allowed_extensions.
Warning
Don’t rely on validation of the file extension to determine a file’s type. Files can be renamed to have any extension no matter what data they contain.
Uses Pillow to ensure that value.name (value is a File) has a valid image extension.
Raises a ValidationError if str(value) contains one or more nulls characters ('\x00').
The error message used by ValidationError if validation fails. Defaults to "Null characters are not allowed.".
The error code used by ValidationError if validation fails. Defaults to "null_characters_not_allowed".


Property that returns a pathlib.Path representing the absolute filesystem path to a template for rendering the HTML representation of the exception. Defaults to the Django provided template.
Property that returns a pathlib.Path representing the absolute filesystem path to a template for rendering the plain-text representation of the exception. Defaults to the Django provided template.
Return a dictionary containing traceback information.
This is the main extension point for customizing exception reports, for example:
Return HTML version of exception report.
Used for HTML version of debug 500 HTTP error page.
Return plain text version of exception report.
Used for plain text version of debug 500 HTTP error page and email reports.


Return a dictionary containing traceback information.
This is the main extension point for customizing exception reports, for example:


Return HTML version of exception report.
Used for HTML version of debug 500 HTTP error page.


Return plain text version of exception report.
Used for plain text version of debug 500 HTTP error page and email reports.


Property that returns a pathlib.Path representing the absolute filesystem path to a template for rendering the HTML representation of the exception. Defaults to the Django provided template.


Property that returns a pathlib.Path representing the absolute filesystem path to a template for rendering the plain-text representation of the exception. Defaults to the Django provided template.


The string value to replace sensitive value with. By default it replaces the values of sensitive variables with stars (**********).
A compiled regular expression object used to match settings and request.META values considered as sensitive. By default equivalent to:
Returns True to activate the filtering in get_post_parameters() and get_traceback_frame_variables(). By default the filter is active if DEBUG is False. Note that sensitive request.META values are always filtered along with sensitive setting values, as described in the DEBUG documentation.
Returns the filtered dictionary of POST parameters. Sensitive values are replaced with cleansed_substitute.
Returns the filtered dictionary of local variables for the given traceback frame. Sensitive values are replaced with cleansed_substitute.


The string value to replace sensitive value with. By default it replaces the values of sensitive variables with stars (**********).


Returns the filtered dictionary of POST parameters. Sensitive values are replaced with cleansed_substitute.


Returns the filtered dictionary of local variables for the given traceback frame. Sensitive values are replaced with cleansed_substitute.


A compiled regular expression object used to match settings and request.META values considered as sensitive. By default equivalent to:


Returns True to activate the filtering in get_post_parameters() and get_traceback_frame_variables(). By default the filter is active if DEBUG is False. Note that sensitive request.META values are always filtered along with sensitive setting values, as described in the DEBUG documentation.


This decorator patches the response’s Cache-Control header by adding all of the keyword arguments to it. See patch_cache_control() for the details of the transformation.


This decorator adds a Cache-Control: max-age=0, no-cache, no-store,
must-revalidate, private header to a response to indicate that a page should never be cached.


This decorator allows individual views to be excluded from APPEND_SLASH URL normalization.


This decorator marks a view as being exempt from the protection ensured by the middleware. Example:


Decorator that provides the protection of CsrfViewMiddleware to a view.
Usage:
If you are using class-based views, you can refer to Decorating class-based views.


This decorator forces a view to send the CSRF cookie.


Normally the csrf_token template tag will not work if CsrfViewMiddleware.process_view or an equivalent like csrf_protect has not run. The view decorator requires_csrf_token can be used to ensure the template tag does work. This decorator works similarly to csrf_protect, but never rejects an incoming request.
Example:


If one of your views receives an HttpRequest object with POST parameters susceptible to contain sensitive information, you may prevent the values of those parameters from being included in the error reports using the sensitive_post_parameters decorator:
In the above example, the values for the pass_word and credit_card_number POST parameters will be hidden and replaced with stars (**********) in the request’s representation inside the error reports, whereas the value of the name parameter will be disclosed.
To systematically hide all POST parameters of a request in error reports, do not provide any argument to the sensitive_post_parameters decorator:
All POST parameters are systematically filtered out of error reports for certain django.contrib.auth.views views (login, password_reset_confirm, password_change, and add_view and user_change_password in the auth admin) to prevent the leaking of sensitive information such as user passwords.


If a function (either a view or any regular callback) in your code uses local variables susceptible to contain sensitive information, you may prevent the values of those variables from being included in error reports using the sensitive_variables decorator:
In the above example, the values for the user, pw and cc variables will be hidden and replaced with stars (**********) in the error reports, whereas the value of the name variable will be disclosed.
To systematically hide all local variables of a function from error logs, do not provide any argument to the sensitive_variables decorator:
When using multiple decorators
If the variable you want to hide is also a function argument (e.g. ‘user’ in the following example), and if the decorated function has multiple decorators, then make sure to place @sensitive_variables at the top of the decorator chain. This way it will also hide the function argument as it gets passed through the other decorators:


This decorator compresses content if the browser allows gzip compression. It sets the Vary header accordingly, so that caches will base their storage on the Accept-Encoding header.


These decorators can be used to generate ETag and Last-Modified headers; see conditional view processing.


Decorator to require that a view only accepts the GET method.


Decorator to require that a view only accepts particular request methods. Usage:
Note that request methods should be in uppercase.


Decorator to require that a view only accepts the POST method.


Decorator to require that a view only accepts the GET and HEAD methods. These methods are commonly considered “safe” because they should not have the significance of taking an action other than retrieving the requested resource.
Note
Web servers should automatically strip the content of responses to HEAD requests while leaving the headers unchanged, so you may handle HEAD requests exactly like GET requests in your views. Since some software, such as link checkers, rely on HEAD requests, you might prefer using require_safe instead of require_GET.


The Vary header defines which request headers a cache mechanism should take into account when building its cache key.
See using vary headers.


Attributes
A dictionary to include in the context. This is a convenient way of specifying some context in as_view(). Example usage:
Methods
Returns a dictionary representing the template context. The keyword arguments provided will make up the returned context. Example usage:
The template context of all class-based generic views include a view variable that points to the View instance.
Use alters_data where appropriate
Note that having the view instance in the template context may expose potentially hazardous methods to template authors. To prevent methods like this from being called in the template, set alters_data=True on those methods. For more information, read the documentation on rendering a template context.


A dictionary to include in the context. This is a convenient way of specifying some context in as_view(). Example usage:


Returns a dictionary representing the template context. The keyword arguments provided will make up the returned context. Example usage:
The template context of all class-based generic views include a view variable that points to the View instance.
Use alters_data where appropriate
Note that having the view instance in the template context may expose potentially hazardous methods to template authors. To prevent methods like this from being called in the template, set alters_data=True on those methods. For more information, read the documentation on rendering a template context.


Redirects to a given URL.
The given URL may contain dictionary-style string formatting, which will be interpolated against the parameters captured in the URL. Because keyword interpolation is always done (even if no arguments are passed in), any "%" characters in the URL must be written as "%%" so that Python will convert them to a single percent sign on output.
If the given URL is None, Django will return an HttpResponseGone (410).
Ancestors (MRO)
This view inherits methods and attributes from the following view:
Method Flowchart
Example views.py:
Example urls.py:
Attributes
The URL to redirect to, as a string. Or None to raise a 410 (Gone) HTTP error.
The name of the URL pattern to redirect to. Reversing will be done using the same args and kwargs as are passed in for this view.
Whether the redirect should be permanent. The only difference here is the HTTP status code returned. If True, then the redirect will use status code 301. If False, then the redirect will use status code 302. By default, permanent is False.
Whether to pass along the GET query string to the new location. If True, then the query string is appended to the URL. If False, then the query string is discarded. By default, query_string is False.
Methods
Constructs the target URL for redirection.
The args and kwargs arguments are positional and/or keyword arguments captured from the URL pattern, respectively.
The default implementation uses url as a starting string and performs expansion of % named parameters in that string using the named groups captured in the URL.
If url is not set, get_redirect_url() tries to reverse the pattern_name using what was captured in the URL (both named and unnamed groups are used).
If requested by query_string, it will also append the query string to the generated URL. Subclasses may implement any behavior they wish, as long as the method returns a redirect-ready URL string.


Constructs the target URL for redirection.
The args and kwargs arguments are positional and/or keyword arguments captured from the URL pattern, respectively.
The default implementation uses url as a starting string and performs expansion of % named parameters in that string using the named groups captured in the URL.
If url is not set, get_redirect_url() tries to reverse the pattern_name using what was captured in the URL (both named and unnamed groups are used).
If requested by query_string, it will also append the query string to the generated URL. Subclasses may implement any behavior they wish, as long as the method returns a redirect-ready URL string.


The name of the URL pattern to redirect to. Reversing will be done using the same args and kwargs as are passed in for this view.


Whether the redirect should be permanent. The only difference here is the HTTP status code returned. If True, then the redirect will use status code 301. If False, then the redirect will use status code 302. By default, permanent is False.


Whether to pass along the GET query string to the new location. If True, then the query string is appended to the URL. If False, then the query string is discarded. By default, query_string is False.


The URL to redirect to, as a string. Or None to raise a 410 (Gone) HTTP error.


Provides a mechanism to construct a TemplateResponse, given suitable context. The template to use is configurable and can be further customized by subclasses.
Attributes
The full name of a template to use as defined by a string. Not defining a template_name will raise a django.core.exceptions.ImproperlyConfigured exception.
The NAME of a template engine to use for loading the template. template_engine is passed as the using keyword argument to response_class. Default is None, which tells Django to search for the template in all configured engines.
The response class to be returned by render_to_response method. Default is TemplateResponse. The template and context of TemplateResponse instances can be altered later (e.g. in template response middleware).
If you need custom template loading or custom context object instantiation, create a TemplateResponse subclass and assign it to response_class.
The content type to use for the response. content_type is passed as a keyword argument to response_class. Default is None – meaning that Django uses 'text/html'.
Methods
Returns a self.response_class instance.
If any keyword arguments are provided, they will be passed to the constructor of the response class.
Calls get_template_names() to obtain the list of template names that will be searched looking for an existent template.
Returns a list of template names to search for when rendering the template. The first template that is found will be used.
The default implementation will return a list containing template_name (if it is specified).


The content type to use for the response. content_type is passed as a keyword argument to response_class. Default is None – meaning that Django uses 'text/html'.


Returns a list of template names to search for when rendering the template. The first template that is found will be used.
The default implementation will return a list containing template_name (if it is specified).


Returns a self.response_class instance.
If any keyword arguments are provided, they will be passed to the constructor of the response class.
Calls get_template_names() to obtain the list of template names that will be searched looking for an existent template.


The response class to be returned by render_to_response method. Default is TemplateResponse. The template and context of TemplateResponse instances can be altered later (e.g. in template response middleware).
If you need custom template loading or custom context object instantiation, create a TemplateResponse subclass and assign it to response_class.


The NAME of a template engine to use for loading the template. template_engine is passed as the using keyword argument to response_class. Default is None, which tells Django to search for the template in all configured engines.


The full name of a template to use as defined by a string. Not defining a template_name will raise a django.core.exceptions.ImproperlyConfigured exception.


Renders a given template, with the context containing parameters captured in the URL.
Ancestors (MRO)
This view inherits methods and attributes from the following views:
Method Flowchart
Example views.py:
Example urls.py:
Context


The master class-based base view. All other class-based views inherit from this base class. It isn’t strictly a generic view and thus can also be imported from django.views.
Method Flowchart
Example views.py:
Example urls.py:
Attributes
The list of HTTP method names that this view will accept.
Default:
Methods
Returns a callable view that takes a request and returns a response:
The returned view has view_class and view_initkwargs attributes.
When the view is called during the request/response cycle, the setup() method assigns the HttpRequest to the view’s request attribute, and any positional and/or keyword arguments captured from the URL pattern to the args and kwargs attributes, respectively. Then dispatch() is called.
Performs key view initialization prior to dispatch().
If overriding this method, you must call super().
The view part of the view – the method that accepts a request argument plus arguments, and returns an HTTP response.
The default implementation will inspect the HTTP method and attempt to delegate to a method that matches the HTTP method; a GET will be delegated to get(), a POST to post(), and so on.
By default, a HEAD request will be delegated to get(). If you need to handle HEAD requests in a different way than GET, you can override the head() method. See Supporting other HTTP methods for an example.
If the view was called with an HTTP method it doesn’t support, this method is called instead.
The default implementation returns HttpResponseNotAllowed with a list of allowed methods in plain text.
Handles responding to requests for the OPTIONS HTTP verb. Returns a response with the Allow header containing a list of the view’s allowed HTTP method names.


The view part of the view – the method that accepts a request argument plus arguments, and returns an HTTP response.
The default implementation will inspect the HTTP method and attempt to delegate to a method that matches the HTTP method; a GET will be delegated to get(), a POST to post(), and so on.
By default, a HEAD request will be delegated to get(). If you need to handle HEAD requests in a different way than GET, you can override the head() method. See Supporting other HTTP methods for an example.


The list of HTTP method names that this view will accept.
Default:


If the view was called with an HTTP method it doesn’t support, this method is called instead.
The default implementation returns HttpResponseNotAllowed with a list of allowed methods in plain text.


Handles responding to requests for the OPTIONS HTTP verb. Returns a response with the Allow header containing a list of the view’s allowed HTTP method names.


Performs key view initialization prior to dispatch().
If overriding this method, you must call super().


A top-level index page showing the “latest” objects, by date. Objects with a date in the future are not included unless you set allow_future to True.
Ancestors (MRO)
Context
In addition to the context provided by django.views.generic.list.MultipleObjectMixin (via django.views.generic.dates.BaseDateListView), the template’s context will be:
Notes
Example myapp/urls.py:
Example myapp/article_archive.html:
This will output all articles.


A base class that provides common behavior for all date-based views. There won’t normally be a reason to instantiate BaseDateListView; instantiate one of the subclasses instead.
While this view (and its subclasses) are executing, self.object_list will contain the list of objects that the view is operating upon, and self.date_list will contain the list of dates for which data is available.
Mixins
Methods and Attributes
A boolean specifying whether to display the page if no objects are available. If this is True and no objects are available, the view will display an empty page instead of raising a 404.
This is identical to django.views.generic.list.MultipleObjectMixin.allow_empty, except for the default value, which is False.
Optional A string defining the aggregation period for date_list. It must be one of 'year' (default), 'month', or 'day'.
Returns a 3-tuple containing (date_list, object_list, extra_context).
date_list is the list of dates for which data is available. object_list is the list of objects. extra_context is a dictionary of context data that will be added to any context data provided by the MultipleObjectMixin.
Returns a queryset, filtered using the query arguments defined by lookup. Enforces any restrictions on the queryset, such as allow_empty and allow_future.
Returns the aggregation period for date_list. Returns date_list_period by default.
Returns the list of dates of type date_type for which queryset contains entries. For example, get_date_list(qs, 'year') will return the list of years for which qs has entries. If date_type isn’t provided, the result of get_date_list_period() is used. date_type and ordering are passed to QuerySet.dates().


A boolean specifying whether to display the page if no objects are available. If this is True and no objects are available, the view will display an empty page instead of raising a 404.
This is identical to django.views.generic.list.MultipleObjectMixin.allow_empty, except for the default value, which is False.


Optional A string defining the aggregation period for date_list. It must be one of 'year' (default), 'month', or 'day'.


Returns the list of dates of type date_type for which queryset contains entries. For example, get_date_list(qs, 'year') will return the list of years for which qs has entries. If date_type isn’t provided, the result of get_date_list_period() is used. date_type and ordering are passed to QuerySet.dates().


Returns the aggregation period for date_list. Returns date_list_period by default.


Returns a 3-tuple containing (date_list, object_list, extra_context).
date_list is the list of dates for which data is available. object_list is the list of objects. extra_context is a dictionary of context data that will be added to any context data provided by the MultipleObjectMixin.


Returns a queryset, filtered using the query arguments defined by lookup. Enforces any restrictions on the queryset, such as allow_empty and allow_future.


A page representing an individual object. If the object has a date value in the future, the view will throw a 404 error by default, unless you set allow_future to True.
Ancestors (MRO)
Context
Notes
Example myapp/urls.py:
Example myapp/article_detail.html:


A mixin class providing common behavior for all date-based views.
Methods and Attributes
The name of the DateField or DateTimeField in the QuerySet’s model that the date-based archive should use to determine the list of objects to display on the page.
When time zone support is enabled and date_field is a DateTimeField, dates are assumed to be in the current time zone. Otherwise, the queryset could include objects from the previous or the next day in the end user’s time zone.
Warning
In this situation, if you have implemented per-user time zone selection, the same URL may show a different set of objects, depending on the end user’s time zone. To avoid this, you should use a DateField as the date_field attribute.
A boolean specifying whether to include “future” objects on this page, where “future” means objects in which the field specified in date_field is greater than the current date/time. By default, this is False.
Returns the name of the field that contains the date data that this view will operate on. Returns date_field by default.
Determine whether to include “future” objects on this page, where “future” means objects in which the field specified in date_field is greater than the current date/time. Returns allow_future by default.


A boolean specifying whether to include “future” objects on this page, where “future” means objects in which the field specified in date_field is greater than the current date/time. By default, this is False.


The name of the DateField or DateTimeField in the QuerySet’s model that the date-based archive should use to determine the list of objects to display on the page.
When time zone support is enabled and date_field is a DateTimeField, dates are assumed to be in the current time zone. Otherwise, the queryset could include objects from the previous or the next day in the end user’s time zone.
Warning
In this situation, if you have implemented per-user time zone selection, the same URL may show a different set of objects, depending on the end user’s time zone. To avoid this, you should use a DateField as the date_field attribute.


Determine whether to include “future” objects on this page, where “future” means objects in which the field specified in date_field is greater than the current date/time. Returns allow_future by default.


Returns the name of the field that contains the date data that this view will operate on. Returns date_field by default.


A day archive page showing all objects in a given day. Days in the future throw a 404 error, regardless of whether any objects exist for future days, unless you set allow_future to True.
Ancestors (MRO)
Context
In addition to the context provided by MultipleObjectMixin (via BaseDateListView), the template’s context will be:
Notes
Example myapp/views.py:
Example myapp/urls.py:
Example myapp/article_archive_day.html:


A mixin that can be used to retrieve and provide parsing information for a day component of a date.
Methods and Attributes
The strftime() format to use when parsing the day. By default, this is '%d'.
Optional The value for the day, as a string. By default, set to None, which means the day will be determined using other means.
Returns the strftime() format to use when parsing the day. Returns day_format by default.
Returns the day for which this view will display data, as a string. Tries the following sources, in order:
Raises a 404 if no valid day specification can be found.
Returns a date object containing the next valid day after the date provided. This function can also return None or raise an Http404 exception, depending on the values of allow_empty and allow_future.
Returns a date object containing the previous valid day. This function can also return None or raise an Http404 exception, depending on the values of allow_empty and allow_future.