Django Utils¶
This document covers all stable modules in django.utils. Most of the
modules in django.utils are designed for internal use and only the
following parts can be considered stable and thus backwards compatible as per
the internal release deprecation policy.
django.utils.cache¶
This module contains helper functions for controlling caching. It does so by
managing the Vary header of responses. It includes functions to patch the
header of response objects directly and decorators that change functions to do
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 take
into account when building its cache key. Requests with the same path but
different header content for headers named in Vary need to get different
cache keys to prevent delivery of wrong content.
For example, internationalization middleware would
need to distinguish caches by the Accept-language header.
-
patch_cache_control(response, **kwargs)[ソース]¶ This function patches the
Cache-Controlheader by adding all keyword arguments to it. The transformation is as follows:- All keyword parameter names are turned to lowercase, and underscores are converted to hyphens.
- If the value of a parameter is
True(exactlyTrue, not just a true value), only the parameter name is added to the header. - All other parameters are added with their value, after applying
str()to it.
-
get_max_age(response)[ソース]¶ Returns the max-age from the response Cache-Control header as an integer (or
Noneif it wasn’t found or wasn’t an integer).
-
patch_response_headers(response, cache_timeout=None)[ソース]¶ Adds some useful headers to the given
HttpResponseobject:ETagExpiresCache-Control
Each header is only added if it isn’t already set.
cache_timeoutis in seconds. TheCACHE_MIDDLEWARE_SECONDSsetting is used by default.Changed in Django 1.11:In older versions, the
Last-Modifiedheader was also set.バージョン 1.11 で撤廃: Since the
USE_ETAGSsetting is deprecated, this function won’t set theETagheader when the deprecation ends in Django 2.1.
-
add_never_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.
-
patch_vary_headers(response, newheaders)[ソース]¶ Adds (or updates) the
Varyheader in the givenHttpResponseobject.newheadersis a list of header names that should be inVary. Existing headers inVaryaren’t removed.
-
get_cache_key(request, key_prefix=None)[ソース]¶ 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.
-
learn_cache_key(request, response, cache_timeout=None, key_prefix=None)[ソース]¶ 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
Varyheader 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 just 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.
django.utils.dateparse¶
The functions defined in this module share the following properties:
- They raise
ValueErrorif their input is well formatted but isn’t a valid date or time. - They return
Noneif it isn’t well formatted at all. - They accept up to picosecond resolution in input, but they truncate it to microseconds, since that’s what Python supports.
-
parse_date(value)[ソース]¶ Parses a string and returns a
datetime.date.
-
parse_time(value)[ソース]¶ Parses a string and returns a
datetime.time.UTC offsets aren’t supported; if
valuedescribes one, the result isNone.
-
parse_datetime(value)[ソース]¶ Parses a string and returns a
datetime.datetime.UTC offsets are supported; if
valuedescribes one, the result’stzinfoattribute is aFixedOffsetinstance.
-
parse_duration(value)[ソース]¶ Parses a string and returns a
datetime.timedelta.Expects data in the format
"DD HH:MM:SS.uuuuuu"or as specified by ISO 8601 (e.g.P4DT1H15M20Swhich is equivalent to4 1:15:20).
django.utils.decorators¶
-
method_decorator(decorator, name='')[ソース]¶ Converts a function decorator into a method decorator. It can be used to decorate methods or classes; in the latter case,
nameis the name of the method to be decorated and is required.decoratormay 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.
-
decorator_from_middleware(middleware_class)[ソース]¶ 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(), andprocess_response()).
-
decorator_from_middleware_with_args(middleware_class)[ソース]¶ Like
decorator_from_middleware, but returns a function that accepts the arguments to be passed to the middleware_class. For example, thecache_page()decorator is created from theCacheMiddlewarelike 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__and__str__methods under Python 2. Under Python 3 it does nothing.To support Python 2 and 3 with a single code base, define a
__str__method returning text (usesix.text_type()if you’re doing some casting) and apply this decorator to the class.
-
smart_text(s, encoding='utf-8', strings_only=False, errors='strict')[ソース]¶ Returns a text object representing
s–unicodeon Python 2 andstron Python 3. Treats bytestrings using theencodingcodec.If
strings_onlyisTrue, don’t convert (some) non-string-like objects.
-
smart_unicode(s, encoding='utf-8', strings_only=False, errors='strict')¶ Historical name of
smart_text(). Only available under Python 2.
-
is_protected_type(obj)[ソース]¶ Determine if the object instance is of a protected type.
Objects of protected types are preserved as-is when passed to
force_text(strings_only=True).
-
force_text(s, encoding='utf-8', strings_only=False, errors='strict')[ソース]¶ Similar to
smart_text, except that lazy instances are resolved to strings, rather than kept as lazy objects.If
strings_onlyisTrue, don’t convert (some) non-string-like objects.
-
force_unicode(s, encoding='utf-8', strings_only=False, errors='strict')¶ Historical name of
force_text(). Only available under Python 2.
-
smart_bytes(s, encoding='utf-8', strings_only=False, errors='strict')[ソース]¶ Returns a bytestring version of
s, encoded as specified inencoding.If
strings_onlyisTrue, don’t convert (some) non-string-like objects.
-
force_bytes(s, encoding='utf-8', strings_only=False, errors='strict')[ソース]¶ Similar to
smart_bytes, except that lazy instances are resolved to bytestrings, rather than kept as lazy objects.If
strings_onlyisTrue, don’t convert (some) non-string-like objects.
-
smart_str(s, encoding='utf-8', strings_only=False, errors='strict')¶ Alias of
smart_bytes()on Python 2 andsmart_text()on Python 3. This function returns astror a lazy string.For instance, this is suitable for writing to
sys.stdouton Python 2 and 3.
-
force_str(s, encoding='utf-8', strings_only=False, errors='strict')¶ Alias of
force_bytes()on Python 2 andforce_text()on Python 3. This function always returns astr.
-
iri_to_uri(iri)[ソース]¶ 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. However, since we are assuming input is either UTF-8 or unicode already, we can simplify things a little from the full method.
Takes an IRI in UTF-8 bytes and returns ASCII bytes containing the encoded result.
-
uri_to_iri(uri)[ソース]¶ 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 unicode string containing the encoded result.
-
filepath_to_uri(path)[ソース]¶ 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 or unicode.
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.
django.utils.feedgenerator¶
使用例:
>>> 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
-
get_tag_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 applies to the entire feed.
Any extra keyword arguments you pass to
__init__will be stored inself.feed.All parameters should be Unicode objects, except
categories, which should be a sequence of Unicode objects.
-
add_item(title, link, description, author_email=None, author_name=None, author_link=None, pubdate=None, comments=None, unique_id=None, enclosure=None, categories=(), item_copyright=None, ttl=None, updateddate=None, enclosures=None, **kwargs)[ソース]¶ Adds an item to the feed. All args are expected to be Python
unicodeobjects exceptpubdateandupdateddate, which aredatetime.datetimeobjects,enclosure, which is anEnclosureinstance, andenclosures, which is a list ofEnclosureinstances.バージョン 1.9 で撤廃: The
enclosurekeyword argument is deprecated in favor of the newenclosureskeyword argument which accepts a list ofEnclosureobjects.
-
root_attributes()[ソース]¶ Return extra attributes to place on the root (i.e. feed/channel) element. Called from
write().
-
add_root_elements(handler)[ソース]¶ Add elements in the root (i.e. feed/channel) element. Called from
write().
-
item_attributes(item)[ソース]¶ Return extra attributes to place on each item (i.e. item/entry) element.
-
django.utils.functional¶
-
class
cached_property(object, name)[ソース]¶ The
@cached_propertydecorator caches the result of a method with a singleselfargument 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:
# 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 instancepersonin the view and the template are the same, decorating thefriends()method with@cached_propertycan 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 to be invoked 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"]
As well as offering potential performance advantages,
@cached_propertycan 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 ondatetime.now(), or simply 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 use the
nameargument to make cached properties of other methods. For example, if you had an expensiveget_friends()method and wanted to allow calling it without retrieving the cached value, you could write:friends = cached_property(get_friends, name='friends')
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:x = person.friends # calls first time y = person.get_friends() # calls again z = person.friends # does not call x is z # is True
-
allow_lazy(func, *resultclasses)[ソース]¶ バージョン 1.10 で撤廃.
Works like
keep_lazy()except that it can’t be used as a decorator.
-
keep_lazy(func, *resultclasses)[ソース]¶ - New in Django 1.10.
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:
from django.utils import six 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(six.text_type)(fancy_utility_function) # Or more succinctly: @keep_lazy(six.text_type) 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 common use case is to have functions that return text. For these, you can just pass thesix.text_typetype tokeep_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 the input is a proper string, then add support for lazy translation objects at the end.
-
keep_lazy_text(func)[ソース]¶ - New in Django 1.10.
A shortcut for
keep_lazy(six.text_type)(func).If you have a function that returns text and you want to be able to take lazy arguments while delaying their evaluation, simply use this decorator:
from django.utils import six from django.utils.functional import keep_lazy, keep_lazy_text # Our previous example was: @keep_lazy(six.text_type) 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 its
autoescape mechanism, using the utilities in django.utils.safestring
where appropriate. This module provides some additional low level utilities for
escaping HTML.
-
escape(text)[ソース]¶ Returns the given text with ampersands, quotes and angle brackets encoded for use in HTML. The input is first passed through
force_text()and the output hasmark_safe()applied.
-
conditional_escape(text)[ソース]¶ Similar to
escape(), except that it doesn’t operate on pre-escaped strings, so it will not double escape.
-
format_html(format_string, *args, **kwargs)[ソース]¶ This is similar to
str.format(), except that it is appropriate for building 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 be preferred over string interpolation using
%orstr.format()directly, because it applies escaping to all arguments - just like the template 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 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 bystr.format()(e.g. number formatting) will not work, since all arguments are passed throughconditional_escape()which (ultimately) callsforce_text()on the values.
-
format_html_join(sep, format_string, args_generator)[ソース]¶ 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 usingsep.sepis also passed throughconditional_escape().args_generatorshould be an iterator that returns the sequence ofargsthat will be passed toformat_html(). For example:format_html_join( '\n', "<li>{} {}</li>", ((u.first_name, u.last_name) for u in users) )
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_tagcall without escaping it first, for example withescape().For example:
strip_tags(value)
If
valueis"<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 detect classes whose output doesn’t require HTML escaping.This decorator defines the
__html__()method on the decorated class by wrapping the__unicode__()(Python 2) or__str__()(Python 3) inmark_safe(). Ensure the__unicode__()or__str__()method does indeed return text that doesn’t require HTML escaping.
django.utils.http¶
-
urlquote(url, safe='/')[ソース]¶ A version of Python’s
urllib.quote()function that can operate on unicode strings. The url is first UTF-8 encoded before quoting. The returned string can safely be used as part of an argument to a subsequentiri_to_uri()call without double-quoting occurring. Employs lazy execution.
-
urlquote_plus(url, safe='')[ソース]¶ A version of Python’s urllib.quote_plus() function that can operate on unicode strings. The url is first UTF-8 encoded before quoting. The returned string can safely be used as part of an argument to a subsequent
iri_to_uri()call without double-quoting occurring. Employs lazy execution.
-
urlencode(query, doseq=0)[ソース]¶ A version of Python’s urllib.urlencode() function that can operate on unicode strings. The parameters are first cast to UTF-8 encoded strings and then encoded as per normal.
Formats the time to ensure compatibility with Netscape’s cookie standard.
Accepts a floating point number expressed in seconds since the epoch in UTC–such as that outputted by
time.time(). If set toNone, defaults to the current time.Outputs a string in the format
Wdy, DD-Mon-YYYY HH:MM:SS GMT.
-
http_date(epoch_seconds=None)[ソース]¶ Formats the time to match the RFC 1123 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 toNone, defaults to the current time.Outputs a string in the format
Wdy, DD Mon YYYY HH:MM:SS GMT.
-
base36_to_int(s)[ソース]¶ Converts a base 36 string to an integer. On Python 2 the output is guaranteed to be an
intand not along.
-
int_to_base36(i)[ソース]¶ Converts a positive integer to a base 36 string. On Python 2
imust be smaller than sys.maxint.
django.utils.module_loading¶
Functions for working with Python modules.
-
import_string(dotted_path)[ソース]¶ Imports a dotted module path and returns the attribute/class designated by the last name in the path. Raises
ImportErrorif the import failed. For example:from django.utils.module_loading import import_string ValidationError = import_string('django.core.exceptions.ValidationError')
これは以下と同じです:
from django.core.exceptions import ValidationError
django.utils.safestring¶
Functions and classes for working with 「safe strings」: strings that can be displayed safely without further escaping in HTML. Marking something as a 「safe string」 means that the producer of the string has already turned characters that should not be interpreted by the HTML engine (e.g. 『<』) into the appropriate entities.
-
class
SafeBytes[ソース]¶ A
bytessubclass that has been specifically marked as 「safe」 (requires no further escaping) for HTML output purposes.
-
class
SafeString¶ A
strsubclass that has been specifically marked as 「safe」 (requires no further escaping) for HTML output purposes. This isSafeByteson Python 2 andSafeTexton Python 3.
-
class
SafeText[ソース]¶ A
str(in Python 3) orunicode(in Python 2) subclass that has been specifically marked as 「safe」 for HTML output purposes.
-
mark_safe(s)[ソース]¶ Explicitly mark a string as safe for (HTML) output purposes. The returned object can be used everywhere a string or unicode object 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:
>>> mystr = '<b>Hello World</b> ' >>> mystr = mark_safe(mystr) >>> type(mystr) <class 'django.utils.safestring.SafeBytes'> >>> mystr = mystr.strip() # removing whitespace >>> type(mystr) <type 'str'>
Changed in Django 1.11:Added support for decorator usage.
django.utils.text¶
-
format_lazy(format_string, *args, **kwargs)¶ - New in Django 1.11.
A version of
str.format()for whenformat_string,args, and/orkwargscontain lazy objects. The first argument is the string to be formatted. For example:from django.utils.text import format_lazy from django.utils.translation import pgettext_lazy urlpatterns = [ url(format_lazy(r'{person}/(?P<pk>\d+)/$', 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 match
persona/(?P<pk>\d+)/$, e.g.persona/5/.
-
slugify(allow_unicode=False)[ソース]¶ Converts to ASCII if
allow_unicodeisFalse(default). Converts spaces to hyphens. Removes characters that aren’t alphanumerics, underscores, or hyphens. Converts to lowercase. Also strips leading and trailing whitespace.For example:
slugify(value)
valueが"<b>Joel</b> <button>is</button> a <span>slug</span>"であるとき、出力は"Joel is a slug"となります。You can set the
allow_unicodeparameter toTrue, if you want to allow Unicode characters:slugify(value, allow_unicode=True)
If
valueis"你好 World", the output will be"你好-world".
django.utils.timezone¶
-
class
FixedOffset(offset=None, name=None)[ソース]¶ A
tzinfosubclass modeling a fixed offset from UTC.offsetis an integer number of minutes east of UTC.
-
get_fixed_timezone(offset)[ソース]¶ Returns a
tzinfoinstance that represents a time zone with a fixed offset from UTC.offsetis adatetime.timedeltaor an integer number of minutes. Use positive values for time zones east of UTC and negative values for west of UTC.
-
get_default_timezone()[ソース]¶ Returns a
tzinfoinstance that represents the default time zone.
-
get_default_timezone_name()[ソース]¶ Returns the name of the default time zone.
-
get_current_timezone()[ソース]¶ Returns a
tzinfoinstance that represents the current time zone.
-
get_current_timezone_name()[ソース]¶ Returns the name of the current time zone.
-
activate(timezone)[ソース]¶ Sets the current time zone. The
timezoneargument must be an instance of atzinfosubclass 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 restores the previously active time zone on exit. If thetimezoneargument isNone, the current time zone is unset on entry withdeactivate()instead.overrideis also usable as a function decorator.
-
localtime(value=None, timezone=None)[ソース]¶ Converts an aware
datetimeto a different time zone, by default the current time zone.When
valueis omitted, it defaults tonow().This function doesn’t work on naive datetimes; use
make_aware()instead.Changed in Django 1.11:In older versions,
valueis a required argument.
-
localdate(value=None, timezone=None)[ソース]¶ - New in Django 1.11.
Uses
localtime()to convert an awaredatetimeto adate()in a different time zone, by default the current time zone.When
valueis omitted, it defaults tonow().This function doesn’t work on naive datetimes.
-
now()[ソース]¶ Returns a
datetimethat represents the current point in time. Exactly what’s returned depends on the value ofUSE_TZ:- If
USE_TZisFalse, this will be a naive datetime (i.e. a datetime without an associated timezone) that represents the current time in the system’s local timezone. - If
USE_TZisTrue, this will be an aware datetime representing the current time in UTC. Note thatnow()will always return times in UTC regardless of the value ofTIME_ZONE; you can uselocaltime()to convert to a time in the current time zone.
- If
-
is_aware(value)[ソース]¶ Returns
Trueifvalueis aware,Falseif it is naive. This function assumes thatvalueis adatetime.
-
is_naive(value)[ソース]¶ Returns
Trueifvalueis naive,Falseif it is aware. This function assumes thatvalueis adatetime.
-
make_aware(value, timezone=None, is_dst=None)[ソース]¶ Returns an aware
datetimethat represents the same point in time asvalueintimezone,valuebeing a naivedatetime. Iftimezoneis set toNone, it defaults to the current time zone.The
pytz.AmbiguousTimeErrorexception is raised if you try to makevalueaware during a DST transition where the same time occurs twice (when reverting from DST). Settingis_dsttoTrueorFalsewill avoid the exception by choosing if the time is pre-transition or post-transition respectively.The
pytz.NonExistentTimeErrorexception is raised if you try to makevalueaware during a DST transition such that the time never occurred (when entering into DST). Settingis_dsttoTrueorFalsewill avoid the exception by moving the hour backwards or forwards by 1 respectively. For example,is_dst=Truewould change a non-existent time of 2:30 to 1:30 andis_dst=Falsewould change the time to 3:30.
-
make_naive(value, timezone=None)[ソース]¶ Returns an naive
datetimethat represents intimezonethe same point in time asvalue,valuebeing an awaredatetime. Iftimezoneis set toNone, it defaults to the current time zone.
django.utils.translation¶
以下の使い方の完全な説明は、翻訳ドキュメント を参照してください。
-
pgettext(context, message)[ソース]¶ コンテキストに与えられたmessageを翻訳し、unicode 文字列で返します。詳しくは 文脈マーカー を参照してください。
-
gettext_lazy(message)¶
-
ugettext_lazy(message)¶
-
pgettext_lazy(context, message)¶ 上述の lazy ではないものと同じですが、遅延処理を使用します。
遅延翻訳ドキュメント を参照してください。
-
ugettext_noop(message)¶ 翻訳用に文字列をマークしますが、この段階では翻訳しません。(外部で使われる可能性があるため) ベースの言語のままにする必要があるグローバル変数に文字列を保持するために使えます。そして、後の時点で翻訳します。
-
ngettext(singular, plural, number)[ソース]¶ singular(単数形) とplural(複数形) を翻訳し、numberに基づいた適切な文字列を UTF-8 バイト文字列で返します。
-
ungettext(singular, plural, number)[ソース]¶ singular(単数形) とplural(複数形) を翻訳し、numberに基づいた適切な文字列を unicode 文字列で返します。
-
npgettext(context, singular, plural, number)[ソース]¶ singular(単数形) とplural(複数形) を翻訳し、numberとcontextに基づいた適切な文字列を unicode 文字列で返します。
-
npgettext_lazy(context, singular, plural, number)[ソース]¶ 上述の lazy ではないものと同じですが、遅延処理を使用します。
遅延翻訳ドキュメント を参照してください。
-
string_concat(*strings)¶ バージョン 1.11 で撤廃: Use
django.utils.text.format_lazy()instead.string_concat(*strings)can be replaced byformat_lazy('{}' * len(strings), *strings).文字列結合の遅延の形で、複数のパートで構成される翻訳に対して必要となります。
-
deactivate_all()[ソース]¶ アクティブな翻訳オブジェクトを
NullTranslations()のインスタンスにします。何らかの理由で遅延された翻訳を元の文字列で表示したいときに役立ちます。
-
override(language, deactivate=False)[ソース]¶ django.utils.translation.activate()を使って、与えられた言語に対して翻訳オブジェクトを取り出す Python コンテキストマネージャです。現在のスレッドに対してこの翻訳オブジェクトを有効化し、退出時に元の言語に戻します。オプションで、deactivate引数がTrueの場合、django.utils.translation.deactivate()を使って退出時に単に一時的な翻訳を無効にするようにできます。language 引数にNoneを渡した場合、NullTranslations()のインスタンスがコンテキスト内で有効化されます。overrideis also usable as a function decorator.
-
check_for_language(lang_code)[ソース]¶ 与えられた言語コード (例えば 『fr』 や 『pt_BR』) に対するグローバル言語ファイルが存在するかどうかをチェックします。ユーザーが提供する言語が有効かどうかを決めるために使われます。
-
get_language()[ソース]¶ 現在選択中の言語コードを返します。翻訳が (
deactivate_all()やNoneがoverride()に渡されることによって) 一時的に無効化されている場合はNoneを返します。
-
get_language_from_request(request, check_path=False)[ソース]¶ リクエストを分析して、ユーザがシステムにどの言語を表示させたいかを明らかにします。settings.LANGUAGES にリストアップされている言語のみが考慮されます。ユーザが主言語の他に副言語をリクエストする場合は、主言語が送信されます。
check_pathがTrueの場合、関数はまず、パスがLANGUAGES設定にリストアップされた言語コードで始まるかどうか、リクエストされた URL をチェックします。
-
templatize(src)[ソース]¶ Django テンプレートを
xgettextによって理解されるものに変更します。Django 翻訳タグを標準的なgettext関数の文に変換することによって行われます。
-
LANGUAGE_SESSION_KEY¶ 現在のセッションに対してアクティブな言語が保持されるセッションキーです。