Django Utils

This document covers all stable modules in django.utils. Most of themodules in django.utils are designed for internal use and only thefollowing parts can be considered stable and thus backwards compatible as perthe internal release deprecation policy.

django.utils.cache

This module contains helper functions for controlling HTTP caching. It does soby managing the Vary header of responses. It includes functions to patchthe header of response objects directly and decorators that change functions todo that header-patching themselves.

For information on the Vary header, see RFC 7231#section-7.1.4.

Essentially, the Vary HTTP header defines which headers a cache should takeinto account when building its cache key. Requests with the same path butdifferent header content for headers named in Vary need to get differentcache keys to prevent delivery of wrong content.

For example, internationalization middleware wouldneed to distinguish caches by the Accept-language header.

  • patchcache_control(_response, **kwargs)[源代码]
  • This function patches the Cache-Control header by adding all keywordarguments to it. The transformation is as follows:

    • All keyword parameter names are turned to lowercase, and underscoresare converted to hyphens.
    • If the value of a parameter is True (exactly True, not just atrue value), only the parameter name is added to the header.
    • All other parameters are added with their value, after applyingstr() to it.
  • getmax_age(_response)[源代码]
  • 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).

  • patchresponse_headers(_response, cache_timeout=None)[源代码]

  • Adds some useful headers to the given HttpResponse object:

    • Expires
    • Cache-Control
      Each header is only added if it isn't already set.

cache_timeout is in seconds. The CACHE_MIDDLEWARE_SECONDSsetting is used by default.

  • addnever_cache_headers(_response)[源代码]
  • Adds a Cache-Control: max-age=0, no-cache, no-store, must-revalidateheader to a response to indicate that a page should never be cached.

  • patchvary_headers(_response, newheaders)[源代码]

  • Adds (or updates) the Vary header in the given HttpResponse object.newheaders is a list of header names that should be in Vary.Existing headers in Vary aren't removed.

  • getcache_key(_request, key_prefix=None)[源代码]

  • Returns a cache key based on the request path. It can be used in therequest phase because it pulls the list of headers to take into accountfrom the global path registry and uses those to build a cache key tocheck against.

If there is no headerlist stored, the page needs to be rebuilt, so thisfunction returns None.

  • learncache_key(_request, response, cache_timeout=None, key_prefix=None)[源代码]
  • Learns what headers to take into account for some request path from theresponse object. It stores those headers in a global path registry so thatlater access to that path will know what headers to take into accountwithout building the response object itself. The headers are named inthe Vary header of the response, but we want to prevent responsegeneration.

The list of headers to use for cache key generation is stored in the samecache as the pages themselves. If the cache ages some data out of thecache, this just means that we have to build the response once to get atthe Vary header and so at the list of headers to use for the cache key.

django.utils.dateparse

The functions defined in this module share the following properties:

  • They accept strings in ISO 8601 date/time formats (or some closealternatives) and return objects from the corresponding classes in Python'sdatetime module.
  • They raise ValueError if their input is well formatted but isn't avalid date or time.
  • They return None if it isn't well formatted at all.
  • They accept up to picosecond resolution in input, but they truncate it tomicroseconds, since that's what Python supports.
  • parsedate(_value)[源代码]
  • Parses a string and returns a datetime.date.

  • parsetime(_value)[源代码]

  • Parses a string and returns a datetime.time.

UTC offsets aren't supported; if value describes one, the result isNone.

UTC offsets are supported; if value describes one, the result'stzinfo attribute is a datetime.timezone instance.

Changed in Django 2.2:
In older versions, the tzinfo attribute is aFixedOffset instance.

Expects data in the format "DD HH:MM:SS.uuuuuu" or as specified by ISO8601 (e.g. P4DT1H15M20S which is equivalent to 4 1:15:20) orPostgreSQL's day-time interval format (e.g. 3 days 04:05:06).

django.utils.decorators

  • methoddecorator(_decorator, name='')[源代码]
  • Converts a function decorator into a method decorator. It can be used todecorate methods or classes; in the latter case, name is the nameof the method to be decorated and is required.

decorator may also be a list or tuple of functions. They are wrappedin reverse order so that the call order is the order in which the functionsappear in the list/tuple.

See decorating class based views forexample usage.

  • decoratorfrom_middleware(_middleware_class)[源代码]
  • Given a middleware class, returns a view decorator. This lets you usemiddleware functionality on a per-view basis. The middleware is createdwith no params passed.

It assumes middleware that's compatible with the old style of Django 1.9and earlier (having methods like process_request(),process_exception(), and process_response()).

  • decoratorfrom_middleware_with_args(_middleware_class)[源代码]
  • Like decorator_from_middleware, but returns a functionthat accepts the arguments to be passed to the middleware_class.For example, the cache_page()decorator is created from the CacheMiddleware like this:
  1. cache_page = decorator_from_middleware_with_args(CacheMiddleware)
  2.  
  3. @cache_page(3600)
  4. def my_view(request):
  5. pass

django.utils.encoding

  • python_2_unicode_compatible()[源代码]
  • A decorator that defines unicode and str methods underPython 2. Under Python 3 it does nothing.

To support Python 2 and 3 with a single code base, define a strmethod returning text (use six.text_type() if you're doing somecasting) and apply this decorator to the class.

  • smarttext(_s, encoding='utf-8', strings_only=False, errors='strict')[源代码]
  • Returns a str object representing arbitrary object s. Treatsbytestrings using the encoding codec.

If strings_only is True, don't convert (some) non-string-likeobjects.

  • isprotected_type(_obj)[源代码]
  • Determine if the object instance is of a protected type.

Objects of protected types are preserved as-is when passed toforce_text(strings_only=True).

  • forcetext(_s, encoding='utf-8', strings_only=False, errors='strict')[源代码]
  • Similar to smart_text, except that lazy instances are resolved tostrings, rather than kept as lazy objects.

If strings_only is True, don't convert (some) non-string-likeobjects.

  • smartbytes(_s, encoding='utf-8', strings_only=False, errors='strict')[源代码]
  • Returns a bytestring version of arbitrary object s, encoded asspecified in encoding.

If strings_only is True, don't convert (some) non-string-likeobjects.

  • forcebytes(_s, encoding='utf-8', strings_only=False, errors='strict')[源代码]
  • Similar to smart_bytes, except that lazy instances are resolved tobytestrings, rather than kept as lazy objects.

If strings_only is True, don't convert (some) non-string-likeobjects.

  • smartstr(_s, encoding='utf-8', strings_only=False, errors='strict')
  • Alias of smart_text(). This function returns a str or a lazystring.

For instance, this is suitable for writing to sys.stdout.

Alias of smart_bytes() on Python 2 (in older versions of Django thatsupport it).

  • forcestr(_s, encoding='utf-8', strings_only=False, errors='strict')
  • Alias of force_text(). This function always returns a str.

Alias of force_bytes() on Python 2 (in older versions of Django thatsupport it).

  • irito_uri(_iri)[源代码]
  • Convert an Internationalized Resource Identifier (IRI) portion to a URIportion that is suitable for inclusion in a URL.

This is the algorithm from section 3.1 of RFC 3987#section-3.1, slightlysimplified since the input is assumed to be a string rather than anarbitrary byte stream.

Takes an IRI (string or UTF-8 bytes) and returns a string containing theencoded result.

  • urito_iri(_uri)[源代码]
  • Converts a Uniform Resource Identifier into an Internationalized ResourceIdentifier.

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

  • filepathto_uri(_path)[源代码]
  • Convert a file system path to a URI portion that is suitable for inclusionin a URL. The path is assumed to be either UTF-8 bytes or string.

This method will encode certain characters that would normally berecognized as special characters for URIs. Note that this method does notencode the ' character, as it is a valid character within URIs. SeeencodeURIComponent() JavaScript function for more details.

Returns an ASCII string containing the encoded result.

  • escapeuri_path(_path)[源代码]
  • Escapes the unsafe characters from the path portion of a Uniform ResourceIdentifier (URI).

django.utils.feedgenerator

Sample usage:

  1. >>> from django.utils import feedgenerator
  2. >>> feed = feedgenerator.Rss201rev2Feed(
  3. ... title="Poynter E-Media Tidbits",
  4. ... link="http://www.poynter.org/column.asp?id=31",
  5. ... description="A group Weblog by the sharpest minds in online media/journalism/publishing.",
  6. ... language="en",
  7. ... )
  8. >>> feed.add_item(
  9. ... title="Hello",
  10. ... link="http://www.holovaty.com/test/",
  11. ... description="Testing.",
  12. ... )
  13. >>> with open('test.rss', 'w') as fp:
  14. ... feed.write(fp, 'utf-8')

For simplifying the selection of a generator use feedgenerator.DefaultFeedwhich is currently Rss201rev2Feed

For definitions of the different versions of RSS, see:https://web.archive.org/web/20110718035220/http://diveintomark.org/archives/2004/02/04/incompatible-rss

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

SyndicationFeed

  • class SyndicationFeed[源代码]
  • Base class for all syndication feeds. Subclasses should provide write().

    • init(title, link, description, language=None, author_email=None, author_name=None, author_link=None, subtitle=None, categories=None, feed_url=None, feed_copyright=None, feed_guid=None, ttl=None, **kwargs)[源代码]
    • Initialize the feed with the given dictionary of metadata, which appliesto the entire feed.

Any extra keyword arguments you pass to init will be stored inself.feed.

All parameters should be strings, except categories, which shouldbe a sequence of strings.

  • additem(_title, link, description, author_email=None, author_name=None, author_link=None, pubdate=None, comments=None, unique_id=None, categories=(), item_copyright=None, ttl=None, updateddate=None, enclosures=None, **kwargs)[源代码]
  • Adds an item to the feed. All args are expected to be strings exceptpubdate and updateddate, which are datetime.datetimeobjects, and enclosures, which is a list of Enclosure instances.

  • num_items()[源代码]

  • root_attributes()[源代码]
  • Return extra attributes to place on the root (i.e. feed/channel)element. Called from write().

  • addroot_elements(_handler)[源代码]

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

  • itemattributes(_item)[源代码]

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

  • additem_elements(_handler, item)[源代码]

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

  • write(outfile, encoding)[源代码]

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

  • writeString(encoding)[源代码]

  • Returns the feed in the given encoding as a string.

  • latest_post_date()[源代码]

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

Enclosure

RssFeed

Rss201rev2Feed

RssUserland091Feed

Atom1Feed

django.utils.functional

  • class cachedproperty(_func, name=None)[源代码]
  • The @cached_property decorator caches the result of a method with asingle self argument as a property. The cached result will persistas long as the instance does, so if the instance is passed around and thefunction subsequently invoked, the cached result will be returned.

Consider a typical case, where a view might need to call a model's methodto perform some computation, before placing the model instance into thecontext, where the template might invoke the method once more:

  1. # the model
  2. class Person(models.Model):
  3.  
  4. def friends(self):
  5. # expensive computation
  6. ...
  7. return friends
  8.  
  9. # in the view:
  10. if person.friends():
  11. ...

And in the template you would have:

  1. {% for friend in person.friends %}

Here, friends() will be called twice. Since the instance person inthe view and the template are the same, decorating the friends() methodwith @cached_property can avoid that:

  1. from django.utils.functional import cached_property
  2.  
  3. class Person(models.Model):
  4.  
  5. @cached_property
  6. def friends(self):
  7. ...

Note that as the method is now a property, in Python code it will need tobe accessed appropriately:

  1. # in the view:
  2. if person.friends:
  3. ...

The cached value can be treated like an ordinary attribute of the instance:

  1. # clear it, requiring re-computation next time it's called
  2. del person.friends # or delattr(person, "friends")
  3.  
  4. # set a value manually, that will persist on the instance until cleared
  5. person.friends = ["Huckleberry Finn", "Tom Sawyer"]

Because of the way the descriptor protocol works, using del (or delattr) on acached_property that hasn't been accessed raises AttributeError.

As well as offering potential performance advantages, @cached_propertycan ensure that an attribute's value does not change unexpectedly over thelife of an instance. This could occur with a method whose computation isbased on datetime.now(), or simply if a change were saved to thedatabase by some other process in the brief interval between subsequentinvocations of a method on the same instance.

You can make cached properties of methods. For example, if you had anexpensive get_friends() method and wanted to allow calling it withoutretrieving the cached value, you could write:

  1. friends = cached_property(get_friends, name='friends')

You only need the name argument for Python < 3.6 support.

Changed in Django 2.2:
Older versions of Django require the name argument for all versionsof Python.

While person.get_friends() will recompute the friends on each call, thevalue of the cached property will persist until you delete it as describedabove:

  1. x = person.friends # calls first time
  2. y = person.get_friends() # calls again
  3. z = person.friends # does not call
  4. x is z # is True

警告

On Python < 3.6, cached_property doesn't work properly with amangled name unless it's passed a name of the form_Class__attribute:

  1. __friends = cached_property(get_friends, name='_Person__friends')
  • keeplazy(_func, *resultclasses)[源代码]
  • 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 othercode.

If you write your own similar functions and deal with translations, you'llface the problem of what to do when the first argument is a lazytranslation 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 thecurrent thread's locale setting will not be correct).

For cases like this, use the django.utils.functional.keeplazy()decorator. It modifies the function so that _if it's called with a lazytranslation as one of its arguments, the function evaluation is delayeduntil it needs to be converted to a string.

For example:

  1. from django.utils.functional import keep_lazy, keep_lazy_text
  2.  
  3. def fancy_utility_function(s, ...):
  4. # Do some conversion on string 's'
  5. ...
  6. fancy_utility_function = keep_lazy(str)(fancy_utility_function)
  7.  
  8. # Or more succinctly:
  9. @keep_lazy(str)
  10. def fancy_utility_function(s, ...):
  11. ...

The keep_lazy() decorator takes a number of extra arguments (*args)specifying the type(s) that the original function can return. A commonuse case is to have functions that return text. For these, you can justpass the str type to keep_lazy (or even simpler, use thekeep_lazy_text() decorator described in the next section).

Using this decorator means you can write your function and assume that theinput is a proper string, then add support for lazy translation objects atthe end.

  • keeplazy_text(_func)[源代码]
  • A shortcut for keep_lazy(str)(func).

If you have a function that returns text and you want to be able to takelazy arguments while delaying their evaluation, simply use this decorator:

  1. from django.utils.functional import keep_lazy, keep_lazy_text
  2.  
  3. # Our previous example was:
  4. @keep_lazy(str)
  5. def fancy_utility_function(s, ...):
  6. ...
  7.  
  8. # Which can be rewritten as:
  9. @keep_lazy_text
  10. def fancy_utility_function(s, ...):
  11. ...

django.utils.html

Usually you should build up HTML using Django's templates to make use of itsautoescape mechanism, using the utilities in django.utils.safestringwhere appropriate. This module provides some additional low level utilities forescaping HTML.

  • escape(text)[源代码]
  • Returns the given text with ampersands, quotes and angle brackets encodedfor use in HTML. The input is first coerced to a string and the output hasmark_safe() applied.

  • conditionalescape(_text)[源代码]

  • Similar to escape(), except that it doesn't operate on pre-escapedstrings, so it will not double escape.

  • formathtml(_format_string, *args, **kwargs)[源代码]

  • This is similar to str.format(), except that it is appropriate forbuilding up HTML fragments. All args and kwargs are passed throughconditional_escape() before being passed to str.format().

For the case of building up small HTML fragments, this function is to bepreferred over string interpolation using % or str.format()directly, because it applies escaping to all arguments - just like thetemplate system applies escaping by default.

So, instead of writing:

  1. mark_safe("%s <b>%s</b> %s" % (
  2. some_html,
  3. escape(some_text),
  4. escape(some_other_text),
  5. ))

You should instead use:

  1. format_html("{} <b>{}</b> {}",
  2. mark_safe(some_html),
  3. some_text,
  4. some_other_text,
  5. )

This has the advantage that you don't need to apply escape() to eachargument and risk a bug and an XSS vulnerability if you forget one.

Note that although this function uses str.format() to do theinterpolation, some of the formatting options provided by str.format()(e.g. number formatting) will not work, since all arguments are passedthrough conditional_escape() which (ultimately) callsforce_text() on the values.

  • formathtml_join(_sep, format_string, args_generator)[源代码]
  • A wrapper of format_html(), for the common case of a group ofarguments that need to be formatted using the same format string, and thenjoined using sep. sep is also passed throughconditional_escape().

args_generator should be an iterator that returns the sequence ofargs that will be passed to format_html(). For example:

  1. format_html_join(
  2. '\n', "<li>{} {}</li>",
  3. ((u.first_name, u.last_name) for u in users)
  4. )
  • striptags(_value)[源代码]
  • Tries to remove anything that looks like an HTML tag from the string, thatis anything contained within <>.

Absolutely NO guarantee is provided about the resulting string beingHTML safe. So NEVER mark safe the result of a strip_tag call withoutescaping it first, for example with escape().

For example:

  1. strip_tags(value)

If value is "<b>Joel</b> <button>is</button> a <span>slug</span>"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.

  • html_safe()[源代码]
  • The html() method on a class helps non-Django templates detectclasses whose output doesn't require HTML escaping.

This decorator defines the html() method on the decorated classby wrapping str() in mark_safe().Ensure the str() method does indeed return text that doesn'trequire HTML escaping.

django.utils.http

2.1 版后已移除: Use http_date() instead, which follows the latest RFC.

Formats the time to ensure compatibility with Netscape's cookie standard.

Accepts a floating point number expressed in seconds since the epoch inUTC—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.

Accepts a floating point number expressed in seconds since the epoch inUTC—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.

  • base36to_int(_s)[源代码]
  • Converts a base 36 string to an integer.

  • intto_base36(_i)[源代码]

  • Converts a positive integer to a base 36 string.

  • urlsafebase64_encode(_s)[源代码]

  • Encodes a bytestring to a base64 string for use in URLs, stripping anytrailing equal signs.

Changed in Django 2.2:
In older versions, it returns a bytestring instead of a string.

  • urlsafebase64_decode(_s)[源代码]
  • Decodes a base64 encoded string, adding back any trailing equal signs thatmight have been stripped.

Changed in Django 2.2:
In older versions, s may be a bytestring.

django.utils.module_loading

Functions for working with Python modules.

  • importstring(_dotted_path)[源代码]
  • Imports a dotted module path and returns the attribute/class designated bythe last name in the path. Raises ImportError if the import failed. Forexample:
  1. from django.utils.module_loading import import_string
  2. ValidationError = import_string('django.core.exceptions.ValidationError')

is equivalent to:

  1. from django.core.exceptions import ValidationError

django.utils.safestring

Functions and classes for working with "safe strings": strings that can bedisplayed safely without further escaping in HTML. Marking something as a "safestring" means that the producer of the string has already turned charactersthat should not be interpreted by the HTML engine (e.g. '<') into theappropriate entities.

  • class SafeString
  • A str subclass that has been specifically marked as "safe"(requires no further escaping) for HTML output purposes. Alias ofSafeText.

  • class SafeText[源代码]

  • A str subclass that has been specifically marked as "safe" for HTMLoutput purposes.

  • marksafe(_s)[源代码]

  • Explicitly mark a string as safe for (HTML) output purposes. The returnedobject 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 usingdjango.utils.html.format_html() instead.

String marked safe will become unsafe again if modified. For example:

  1. >>> mystr = '<b>Hello World</b> '
  2. >>> mystr = mark_safe(mystr)
  3. >>> type(mystr)
  4. <class 'django.utils.safestring.SafeText'>
  5.  
  6. >>> mystr = mystr.strip() # removing whitespace
  7. >>> type(mystr)
  8. <type 'str'>

django.utils.text

  • formatlazy(_format_string, *args, **kwargs)
  • A version of str.format() for when format_string, args,and/or kwargs contain lazy objects. The first argument is the string tobe formatted. For example:
  1. from django.utils.text import format_lazy
  2. from django.utils.translation import pgettext_lazy
  3.  
  4. urlpatterns = [
  5. path(format_lazy('{person}/<int:pk>/', person=pgettext_lazy('URL', 'person')),
  6. PersonDetailView.as_view()),
  7. ]

This example allows translators to translate part of the URL. If "person"is translated to "persona", the regular expression will matchpersona/(?P<pk>\d+)/$, e.g. persona/5/.

  • slugify(value, allow_unicode=False)[源代码]
  • Converts a string to a URL slug by:

    • Converting to ASCII if allow_unicode is False (the default).
    • Removing characters that aren't alphanumerics, underscores, hyphens, orwhitespace.
    • Removing leading and trailing whitespace.
    • Converting to lowercase.
    • Replacing any whitespace or repeated dashes with single dashes.
      For example:
  1. >>> slugify(' Joel is a slug ')
  2. 'joel-is-a-slug'

If you want to allow Unicode characters, pass allow_unicode=True. Forexample:

  1. >>> slugify('你好 World', allow_unicode=True)
  2. '你好-world'

django.utils.timezone

  • utc
  • tzinfo instance that represents UTC.

  • class FixedOffset(offset=None, name=None)[源代码]

  • A tzinfo subclass modeling a fixed offset from UTC.offset is an integer number of minutes east of UTC.

2.2 版后已移除: Use datetime.timezone instead.

  • getfixed_timezone(_offset)[源代码]
  • Returns a tzinfo instance that represents a time zonewith a fixed offset from UTC.

offset is a datetime.timedelta or an integer number ofminutes. Use positive values for time zones east of UTC and negativevalues for west of UTC.

override is also usable as a function decorator.

When value is omitted, it defaults to now().

This function doesn't work on naive datetimes; use make_aware()instead.

When value is omitted, it defaults to now().

This function doesn't work on naive datetimes.

  • now()[源代码]
  • Returns a datetime that represents thecurrent point in time. Exactly what's returned depends on the value ofUSE_TZ:

    • If USE_TZ is False, this will be anaive datetime (i.e. a datetimewithout an associated timezone) that represents the current timein the system's local timezone.
    • If USE_TZ is True, this will be anaware datetime representing thecurrent time in UTC. Note that now() will always returntimes in UTC regardless of the value of TIME_ZONE;you can use localtime() to get the time in the current time zone.
  • isaware(_value)[源代码]
  • Returns True if value is aware, False if it is naive. Thisfunction assumes that value is a datetime.

  • isnaive(_value)[源代码]

  • Returns True if value is naive, False if it is aware. Thisfunction assumes that value is a datetime.

  • makeaware(_value, timezone=None, is_dst=None)[源代码]

  • Returns an aware datetime that represents the samepoint in time as value in timezone, value being a naivedatetime. If timezone is set to None, itdefaults to the current time zone.

The pytz.AmbiguousTimeError exception is raised if you try to makevalue aware during a DST transition where the same time occurs twice(when reverting from DST). Setting is_dst to True or False willavoid the exception by choosing if the time is pre-transition orpost-transition respectively.

The pytz.NonExistentTimeError exception is raised if you try to makevalue aware during a DST transition such that the time never occurred(when entering into DST). Setting is_dst to True or False willavoid the exception by moving the hour backwards or forwards by 1respectively. For example, is_dst=True would change a nonexistenttime of 2:30 to 1:30 and is_dst=False would change the time to 3:30.

  • makenaive(_value, timezone=None)[源代码]
  • Returns a naive datetime that represents intimezone the same point in time as value, value being anaware datetime. If timezone is set to None, itdefaults to the current time zone.

django.utils.translation

For a complete discussion on the usage of the following see thetranslation documentation.

The u prefix on the functions below comes from a difference in Python 2between unicode and bytestrings. If your code doesn't support Python 2, use thefunctions without the u.

  • gettext(message)[源代码]
  • ugettext(message)
  • Translates message and returns it as a string.

  • pgettext(context, message)[源代码]

  • Translates message given the context and returns it as a string.

For more information, see Contextual markers.

  • gettextlazy(_message)
  • ugettextlazy(_message)
  • pgettextlazy(_context, message)
  • Same as the non-lazy versions above, but using lazy execution.

See lazy translations documentation.

  • gettextnoop(_message)[源代码]
  • ugettextnoop(_message)
  • Marks strings for translation but doesn't translate them now. This can beused to store strings in global variables that should stay in the baselanguage (because they might be used externally) and will be translatedlater.

  • ngettext(singular, plural, number)[源代码]

  • ungettext(singular, plural, number)
  • Translates singular and plural and returns the appropriate stringbased on number.

  • npgettext(context, singular, plural, number)[源代码]

  • Translates singular and plural and returns the appropriate stringbased on number and the context.

  • ngettextlazy(_singular, plural, number)[源代码]

  • ungettextlazy(_singular, plural, number)
  • npgettextlazy(_context, singular, plural, number)[源代码]
  • Same as the non-lazy versions above, but using lazy execution.

See lazy translations documentation.

  • activate(language)[源代码]
  • Fetches the translation object for a given language and activates it asthe current translation object for the current thread.

  • deactivate()[源代码]

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

  • deactivate_all()[源代码]

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

  • override(language, deactivate=False)[源代码]

  • A Python context manager that usesdjango.utils.translation.activate() to fetch the translation objectfor a given language, activates it as the translation object for thecurrent thread and reactivates the previous active language on exit.Optionally, it can simply deactivate the temporary translation on exit withdjango.utils.translation.deactivate() if the deactivate argumentis True. If you pass None as the language argument, aNullTranslations() instance is activated within the context.

override is also usable as a function decorator.

  • checkfor_language(_lang_code)[源代码]
  • Checks whether there is a global language file for the given languagecode (e.g. 'fr', 'pt_BR'). This is used to decide whether a user-providedlanguage is available.

  • get_language()[源代码]

  • Returns the currently selected language code. Returns None iftranslations are temporarily deactivated (by deactivate_all() orwhen None is passed to override()).

  • get_language_bidi()[源代码]

  • Returns selected language's BiDi layout:

    • False = left-to-right layout
    • True = right-to-left layout
  • getlanguage_from_request(_request, check_path=False)[源代码]
  • Analyzes the request to find what language the user wants the system toshow. Only languages listed in settings.LANGUAGES are taken into account.If the user requests a sublanguage where we have a main language, we sendout the main language.

If check_path is True, the function first checks the requested URLfor whether its path begins with a language code listed in theLANGUAGES setting.

  • getsupported_language_variant(_lang_code, strict=False)[源代码]
  • New in Django 2.1:

Returns lang_code if it's in the LANGUAGES setting, possiblyselecting a more generic variant. For example, 'es' is returned iflang_code is 'es-ar' and 'es' is in LANGUAGES but'es-ar' isn't.

If strict is False (the default), a country-specific variant maybe returned when neither the language code nor its generic variant is found.For example, if only 'es-co' is in LANGUAGES, that'sreturned for lang_codes like 'es' and 'es-ar'. Those matchesaren't returned if strict=True.

Raises LookupError if nothing is found.

  • tolocale(_language)[源代码]
  • Turns a language name (en-us) into a locale name (en_US).

  • templatize(src)[源代码]

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

  • LANGUAGE_SESSION_KEY

  • Session key under which the active language for the current session isstored.