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
(exactlyTrue
, not just atrue value), only the parameter name is added to the header. - All other parameters are added with their value, after applying
str()
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_SECONDS
setting is used by default.
addnever_cache_headers
(_response)[源代码]Adds a
Cache-Control: max-age=0, no-cache, no-store, must-revalidate
header to a response to indicate that a page should never be cached.patchvary_headers
(_response, newheaders)[源代码]Adds (or updates) the
Vary
header in the givenHttpResponse
object.newheaders
is a list of header names that should be inVary
.Existing headers inVary
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's
datetime
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
.
parsedatetime
(_value)[源代码]- Parses a string and returns a
datetime.datetime
.
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.
parseduration
(_value)[源代码]- Parses a string and returns a
datetime.timedelta
.
Expects data in the format "DD HHSS.uuuuuu"
or as specified by ISO8601 (e.g. P4DT1H15M20S
which is equivalent to 4 120
) 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, thecache_page()
decorator is created from theCacheMiddleware
like this:
- cache_page = decorator_from_middleware_with_args(CacheMiddleware)
- @cache_page(3600)
- def my_view(request):
- pass
django.utils.encoding
python_2_unicode_compatible
()[源代码]- A decorator that defines
unicode
andstr
methods underPython 2. Under Python 3 it does nothing.
To support Python 2 and 3 with a single code base, define a str
method 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 objects
. Treatsbytestrings using theencoding
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 inencoding
.
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 astr
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 astr
.
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:
- >>> from django.utils import feedgenerator
- >>> feed = feedgenerator.Rss201rev2Feed(
- ... title="Poynter E-Media Tidbits",
- ... link="http://www.poynter.org/column.asp?id=31",
- ... description="A group Weblog by the sharpest minds in online media/journalism/publishing.",
- ... language="en",
- ... )
- >>> feed.add_item(
- ... title="Hello",
- ... link="http://www.holovaty.com/test/",
- ... description="Testing.",
- ... )
- >>> with open('test.rss', 'w') as fp:
- ... feed.write(fp, 'utf-8')
For simplifying the selection of a generator use feedgenerator.DefaultFeed
which 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
gettag_uri
(_url, date)[源代码]- Creates a TagURI.
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 except
pubdate
andupdateddate
, which aredatetime.datetime
objects, andenclosures
, which is a list ofEnclosure
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
orupdateddate
for all items in thefeed. If no items have either of these attributes this returns thecurrent UTC date/time.
Enclosure
- class
Enclosure
[源代码] - Represents an RSS enclosure
RssFeed
- class
RssFeed
(SyndicationFeed)[源代码]
Rss201rev2Feed
- class
Rss201rev2Feed
(RssFeed)[源代码] - Spec: https://cyber.harvard.edu/rss/rss.html
RssUserland091Feed
- class
RssUserland091Feed
(RssFeed)[源代码] - Spec: http://backend.userland.com/rss091
Atom1Feed
- class
Atom1Feed
(SyndicationFeed)[源代码] - Spec: https://tools.ietf.org/html/rfc4287
django.utils.functional
- class
cachedproperty
(_func, name=None)[源代码] - The
@cached_property
decorator caches the result of a method with asingleself
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:
- # the model
- class Person(models.Model):
- def friends(self):
- # expensive computation
- ...
- return friends
- # in the view:
- if person.friends():
- ...
And in the template you would have:
- {% 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:
- from django.utils.functional import cached_property
- class Person(models.Model):
- @cached_property
- def friends(self):
- ...
Note that as the method is now a property, in Python code it will need tobe accessed appropriately:
- # in the view:
- if person.friends:
- ...
The cached value can be treated like an ordinary attribute of the instance:
- # clear it, requiring re-computation next time it's called
- del person.friends # or delattr(person, "friends")
- # set a value manually, that will persist on the instance until cleared
- 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_property
can 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:
- 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:
- x = person.friends # calls first time
- y = person.get_friends() # calls again
- z = person.friends # does not call
- 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
:
- __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:
- from django.utils.functional import keep_lazy, keep_lazy_text
- def fancy_utility_function(s, ...):
- # Do some conversion on string 's'
- ...
- fancy_utility_function = keep_lazy(str)(fancy_utility_function)
- # Or more succinctly:
- @keep_lazy(str)
- def fancy_utility_function(s, ...):
- ...
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:
- from django.utils.functional import keep_lazy, keep_lazy_text
- # Our previous example was:
- @keep_lazy(str)
- def fancy_utility_function(s, ...):
- ...
- # Which can be rewritten as:
- @keep_lazy_text
- def fancy_utility_function(s, ...):
- ...
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.safestring
where 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 has
mark_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 tostr.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:
- mark_safe("%s <b>%s</b> %s" % (
- some_html,
- escape(some_text),
- escape(some_other_text),
- ))
You should instead use:
- format_html("{} <b>{}</b> {}",
- mark_safe(some_html),
- some_text,
- some_other_text,
- )
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 usingsep
.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:
- format_html_join(
- '\n', "<li>{} {}</li>",
- ((u.first_name, u.last_name) for u in users)
- )
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:
- 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
urlencode
(query, doseq=False)[源代码]A version of Python's
urllib.parse.urlencode()
function that canoperate onMultiValueDict
and non-string values.cookiedate
(_epoch_seconds=None)[源代码]
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 HHSS GMT
.
httpdate
(_epoch_seconds=None)[源代码]- Formats the time to match the RFC 1123 date format as specified by HTTPRFC 7231#section-7.1.1.1.
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 HHSS 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:
- from django.utils.module_loading import import_string
- ValidationError = import_string('django.core.exceptions.ValidationError')
is equivalent to:
- 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:
- >>> mystr = '<b>Hello World</b> '
- >>> mystr = mark_safe(mystr)
- >>> type(mystr)
- <class 'django.utils.safestring.SafeText'>
- >>> mystr = mystr.strip() # removing whitespace
- >>> type(mystr)
- <type 'str'>
django.utils.text
formatlazy
(_format_string, *args, **kwargs)- A version of
str.format()
for whenformat_string
,args
,and/orkwargs
contain lazy objects. The first argument is the string tobe formatted. For example:
- from django.utils.text import format_lazy
- from django.utils.translation import pgettext_lazy
- urlpatterns = [
- path(format_lazy('{person}/<int:pk>/', person=pgettext_lazy('URL', 'person')),
- PersonDetailView.as_view()),
- ]
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
isFalse
(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:
- Converting to ASCII if
- >>> slugify(' Joel is a slug ')
- 'joel-is-a-slug'
If you want to allow Unicode characters, pass allow_unicode=True
. Forexample:
- >>> slugify('你好 World', allow_unicode=True)
- '你好-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.
get_default_timezone
()[源代码]Returns a
tzinfo
instance that represents thedefault time zone.get_default_timezone_name
()[源代码]Returns the name of the default time zone.
get_current_timezone
()[源代码]Returns a
tzinfo
instance that represents thecurrent time zone.get_current_timezone_name
()[源代码]Returns the name of the current time zone.
activate
(timezone)[源代码]Sets the current time zone. The
timezone
argument must be an instance of atzinfo
subclass or a time zone name.deactivate
()[源代码]Unsets the current time zone.
override
(timezone)[源代码]- This is a Python context manager that sets the current time zone on entry with
activate()
, and restoresthe previously active time zone on exit. If thetimezone
argument isNone
, the current time zone is unseton entry withdeactivate()
instead.
override
is also usable as a function decorator.
localtime
(value=None, timezone=None)[源代码]- 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.
localdate
(value=None, timezone=None)[源代码]- Uses
localtime()
to convert an awaredatetime
to adate()
in a different time zone, by default thecurrent time zone.
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
isFalse
, 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
isTrue
, this will be anaware datetime representing thecurrent time in UTC. Note thatnow()
will always returntimes in UTC regardless of the value ofTIME_ZONE
;you can uselocaltime()
to get the time in the current time zone.
- If
isaware
(_value)[源代码]Returns
True
ifvalue
is aware,False
if it is naive. Thisfunction assumes thatvalue
is adatetime
.isnaive
(_value)[源代码]Returns
True
ifvalue
is naive,False
if it is aware. Thisfunction assumes thatvalue
is adatetime
.makeaware
(_value, timezone=None, is_dst=None)[源代码]- Returns an aware
datetime
that represents the samepoint in time asvalue
intimezone
,value
being a naivedatetime
. Iftimezone
is set toNone
, 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 asvalue
,value
being anawaredatetime
. Iftimezone
is set toNone
, 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 thecontext
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
andplural
and returns the appropriate stringbased onnumber
.npgettext
(context, singular, plural, number)[源代码]Translates
singular
andplural
and returns the appropriate stringbased onnumber
and thecontext
.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 uses
django.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 thedeactivate
argumentisTrue
. If you passNone
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 (bydeactivate_all()
orwhenNone
is passed tooverride()
).get_language_bidi
()[源代码]Returns selected language's BiDi layout:
False
= left-to-right layoutTrue
= 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_code
s 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.- Session key under which the active language for the current session isstored.