Django Utils¶
This document covers all stable modules indjango.utils
. Most of themodules indjango.utils
are designed for internal use and only thefollowing parts can be considered stable and thus backwards compatible as pertheinternal release deprecation policy.
django.utils.cache
¶
This module contains helper functions for controlling HTTP caching. It does soby managing theVary
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 theVary
header, seeRFC 9110#section-12.5.5.
Essentially, theVary
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 inVary
need to get differentcache keys to prevent delivery of wrong content.
For example,internationalization middleware wouldneed to distinguish caches by theAccept-language
header.
patch_cache_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.
get_max_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).
patch_response_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. TheCACHE_MIDDLEWARE_SECONDS
setting is used by default.
add_never_cache_headers
(response)¶Adds an
Expires
header to the current date/time.Adds a
Cache-Control:max-age=0,no-cache,no-store,must-revalidate,private
header to a response to indicate that a page should never becached.Each header is only added if it isn’t already set.
patch_vary_headers
(response,newheaders)¶Adds (or updates) the
Vary
header in the givenHttpResponse
object.newheaders
is a list of header names that should be inVary
. Ifheaders contains an asterisk, thenVary
header will consist of a singleasterisk'*'
, according toRFC 9110#section-12.5.5. Otherwise,existing headers inVary
aren’t removed.
get_cache_key
(request,key_prefix=None,method='GET',cache=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
.
learn_cache_key
(request,response,cache_timeout=None,key_prefix=None,cache=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 means that we have to build the response once to get at theVary 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.
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
value
describes one, the result isNone
.
parse_datetime
(value)¶Parses a string and returns a
datetime.datetime
.UTC offsets are supported; if
value
describes one, the result’stzinfo
attribute is adatetime.timezone
instance.
parse_duration
(value)¶Parses a string and returns a
datetime.timedelta
.Expects data in the format
"DDHH:MM:SS.uuuuuu"
,"DDHH:MM:SS,uuuuuu"
, or as specified by ISO 8601 (e.g.P4DT1H15M20S
which is equivalent to41:15:20
) or PostgreSQL’sday-time interval format (e.g.3days04:05:06
).
django.utils.decorators
¶
method_decorator
(decorator,name='')[source]¶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.Seedecorating class based views forexample usage.
decorator_from_middleware
(middleware_class)[source]¶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()
, andprocess_response()
).
decorator_from_middleware_with_args
(middleware_class)[source]¶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)defmy_view(request):pass
sync_only_middleware
(middleware)[source]¶Marks a middleware assynchronous-only. (Thedefault in Django, but this allows you to future-proof if the default everchanges in a future release.)
async_only_middleware
(middleware)[source]¶Marks a middleware asasynchronous-only. Djangowill wrap it in an asynchronous event loop when it is called from the WSGIrequest path.
sync_and_async_middleware
(middleware)[source]¶Marks a middleware assync and async compatible,this allows to avoid converting requests. You must implement detection ofthe current request type to use this decorator. Seeasynchronousmiddleware documentation for details.
django.utils.encoding
¶
smart_str
(s,encoding='utf-8',strings_only=False,errors='strict')[source]¶Returns a
str
object representing arbitrary objects
. Treatsbytestrings using theencoding
codec.If
strings_only
isTrue
, don’t convert (some) non-string-likeobjects.
is_protected_type
(obj)[source]¶Determine if the object instance is of a protected type.
Objects of protected types are preserved as-is when passed to
force_str(strings_only=True)
.
force_str
(s,encoding='utf-8',strings_only=False,errors='strict')[source]¶Similar to
smart_str()
, except that lazy instances are resolved tostrings, rather than kept as lazy objects.If
strings_only
isTrue
, don’t convert (some) non-string-likeobjects.
smart_bytes
(s,encoding='utf-8',strings_only=False,errors='strict')[source]¶Returns a bytestring version of arbitrary object
s
, encoded asspecified inencoding
.If
strings_only
isTrue
, don’t convert (some) non-string-likeobjects.
force_bytes
(s,encoding='utf-8',strings_only=False,errors='strict')[source]¶Similar to
smart_bytes
, except that lazy instances are resolved tobytestrings, rather than kept as lazy objects.If
strings_only
isTrue
, don’t convert (some) non-string-likeobjects.
iri_to_uri
(iri)[source]¶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 ofRFC 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.
uri_to_iri
(uri)[source]¶Converts a Uniform Resource Identifier into an Internationalized ResourceIdentifier.
This is an algorithm from section 3.2 ofRFC 3987#section-3.2.
Takes a URI in ASCII bytes and returns a string containing the encodedresult.
filepath_to_uri
(path)[source]¶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, string, or a
Path
.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. See
encodeURIComponent()
JavaScript function for more details.Returns an ASCII string containing the encoded result.
django.utils.feedgenerator
¶
Sample usage:
>>>fromdjango.utilsimportfeedgenerator>>>feed=feedgenerator.Rss201rev2Feed(...title="Poynter E-Media Tidbits",...link="http://www.poynter.org/column.asp?id=31",...description="A group blog by the sharpest minds in online media/journalism/publishing.",...language="en",...)>>>feed.add_item(...title="Hello",...link="http://www.holovaty.com/test/",...description="Testing.",...)>>>withopen("test.rss","w")asfp:...feed.write(fp,"utf-8")...
For simplifying the selection of a generator usefeedgenerator.DefaultFeed
which is currentlyRss201rev2Feed
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)[source]¶Creates a TagURI.
Seehttps://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id
SyndicationFeed
¶
- class
SyndicationFeed
[source]¶ 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)[source]¶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.
add_item
(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)[source]¶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.
root_attributes
()[source]¶Return extra attributes to place on the root (i.e. feed/channel)element. Called from
write()
.
add_root_elements
(handler)[source]¶Add elements in the root (i.e. feed/channel) element.Called from
write()
.
item_attributes
(item)[source]¶Return extra attributes to place on each item (i.e. item/entry)element.
django.utils.functional
¶
- class
cached_property
(func,name=None)[source]¶ 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 modelclassPerson(models.Model):deffriends(self):# expensive computation...returnfriends# in the view:ifperson.friends():...
And in the template you would have:
{%forfriendinperson.friends%}
Here,
friends()
will be called twice. Since the instanceperson
inthe view and the template are the same, decorating thefriends()
methodwith@cached_property
can avoid that:fromdjango.utils.functionalimportcached_propertyclassPerson(models.Model):@cached_propertydeffriends(self):...
Note that as the method is now a property, in Python code it will need tobe accessed appropriately:
# in the view:ifperson.friends:...
The cached value can be treated like an ordinary attribute of the instance:
# clear it, requiring re-computation next time it's calleddelperson.friends# or delattr(person, "friends")# set a value manually, that will persist on the instance until clearedperson.friends=["Huckleberry Finn","Tom Sawyer"]
Because of the way thedescriptor protocol works, using
del
(ordelattr
) on acached_property
that hasn’t been accessed raisesAttributeError
.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 ondatetime.now()
, or if a change were saved to the database bysome other process in the brief interval between subsequent invocations ofa 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)
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 timey=person.get_friends()# calls againz=person.friends# does not callxisz# is True
Deprecated since version 4.1:The
name
parameter is deprecated and will be removed in Django 5.0as it’s unnecessary as of Python 3.6.
- class
classproperty
(method=None)[source]¶ Similar to
@classmethod
, the@classproperty
decorator converts the result of a method with a singlecls
argumentinto a property that can be accessed directly from the class.
keep_lazy
(func,*resultclasses)[source]¶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.keep_lazy()
decorator. It modifies the function so thatif 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:
fromdjango.utils.functionalimportkeep_lazy,keep_lazy_textdeffancy_utility_function(s,*args,**kwargs):# Do some conversion on string 's'...fancy_utility_function=keep_lazy(str)(fancy_utility_function)# Or more succinctly:@keep_lazy(str)deffancy_utility_function(s,*args,**kwargs):...
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 pass thestr
type tokeep_lazy
(or use thekeep_lazy_text()
decoratordescribed 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.
keep_lazy_text
(func)[source]¶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, you can use thisdecorator:
fromdjango.utils.functionalimportkeep_lazy,keep_lazy_text# Our previous example was:@keep_lazy(str)deffancy_utility_function(s,*args,**kwargs):...# Which can be rewritten as:@keep_lazy_textdeffancy_utility_function(s,*args,**kwargs):...
django.utils.html
¶
Usually you should build up HTML using Django’s templates to make use of itsautoescape mechanism, using the utilities indjango.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.
conditional_escape
(text)¶Similar to
escape()
, except that it doesn’t operate on preescapedstrings, so it will not double escape.
format_html
(format_string,*args,**kwargs)¶This is similar to
str.format()
, except that it is appropriate forbuilding up HTML fragments. The first argumentformat_string
is notescaped but all other args and kwargs are passed throughconditional_escape()
before being passed tostr.format()
.Finally, the output hasmark_safe()
applied.For the case of building up small HTML fragments, this function is to bepreferred over string interpolation using
%
orstr.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 bystr.format()
(e.g. number formatting) will not work, since all arguments are passedthroughconditional_escape()
which (ultimately) callsforce_str()
on the values.
format_html_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 toformat_html()
. For example:format_html_join("\n","<li>{}{}</li>",((u.first_name,u.last_name)foruinusers))
json_script
(value,element_id=None,encoder=None)¶Escapes all HTML/XML special characters with their Unicode escapes, sovalue is safe for use with JavaScript. Also wraps the escaped JSON in a
<script>
tag. If theelement_id
parameter is notNone
, the<script>
tag is given the passed id. For example:>>>json_script({"hello":"world"},element_id="hello-data")'<script id="hello-data" type="application/json">{"hello": "world"}</script>'
The
encoder
, which defaults todjango.core.serializers.json.DjangoJSONEncoder
, will be used toserialize the data. SeeJSON serialization for more details about this serializer.Changed in Django 4.1:In older versions, the
element_id
argument was required.Changed in Django 4.2:The
encoder
argument was added.
strip_tags
(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 withescape()
.For example:
strip_tags(value)
If
value
is"<b>Joel</b><button>is</button>a<span>slug</span>"
the return value will be"Joelisaslug"
.If you are looking for a more robust solution, consider using a third-partyHTML sanitizing tool.
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__()
inmark_safe()
.Ensure the__str__()
method does indeed return text that doesn’trequire HTML escaping.
django.utils.http
¶
urlencode
(query,doseq=False)[source]¶A version of Python’s
urllib.parse.urlencode()
function that canoperate onMultiValueDict
and non-string values.
http_date
(epoch_seconds=None)[source]¶Formats the time to match theRFC 1123#section-5.2.14 date format asspecified by HTTPRFC 9110#section-5.6.7.
Accepts a floating point number expressed in seconds since the epoch inUTC–such as that outputted by
time.time()
. If set toNone
,defaults to the current time.Outputs a string in the format
Wdy,DDMonYYYYHH:MM:SSGMT
.
content_disposition_header
(as_attachment,filename)[source]¶- New in Django 4.2.
Constructs a
Content-Disposition
HTTP header value from the givenfilename
as specified byRFC 6266. ReturnsNone
ifas_attachment
isFalse
andfilename
isNone
, otherwisereturns a string suitable for theContent-Disposition
HTTP header.
django.utils.module_loading
¶
Functions for working with Python modules.
import_string
(dotted_path)[source]¶Imports a dotted module path and returns the attribute/class designated bythe last name in the path. Raises
ImportError
if the import failed. Forexample:fromdjango.utils.module_loadingimportimport_stringValidationError=import_string("django.core.exceptions.ValidationError")
is equivalent to:
fromdjango.core.exceptionsimportValidationError
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
[source]¶ A
str
subclass that has been specifically marked as “safe” (requires nofurther escaping) for HTML output purposes.
mark_safe
(s)[source]¶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 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.SafeString'>>>>mystr=mystr.strip()# removing whitespace>>>type(mystr)<type 'str'>
django.utils.text
¶
format_lazy
(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:fromdjango.utils.textimportformat_lazyfromdjango.utils.translationimportpgettext_lazyurlpatterns=[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 match
persona/(?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). - Converting to lowercase.
- Removing characters that aren’t alphanumerics, underscores, hyphens, orwhitespace.
- Replacing any whitespace or repeated dashes with single dashes.
- Removing leading and trailing whitespace, dashes, and underscores.
For example:
>>>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'
- Converting to ASCII if
django.utils.timezone
¶
utc
¶tzinfo
instance that represents UTC.Deprecated since version 4.1:This is an alias to
datetime.timezone.utc
. Usedatetime.timezone.utc
directly.
get_fixed_timezone
(offset)¶Returns a
tzinfo
instance that represents a time zonewith a fixed offset from UTC.offset
is adatetime.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 thedefault time zone.
get_current_timezone
()¶Returns a
tzinfo
instance that represents thecurrent time zone.
get_current_timezone_name
()¶Returns the name of thecurrent time zone.
activate
(timezone)¶Sets thecurrent time zone. The
timezone
argument must be an instance of atzinfo
subclass or a time zone name.
deactivate
()¶Unsets thecurrent time zone.
override
(timezone)¶This is a Python context manager that sets thecurrent time zone on entry with
activate()
, and restoresthe previously active time zone on exit. If thetimezone
argument isNone
, thecurrent 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 thecurrent time zone.When
value
is omitted, it defaults tonow()
.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 tonow()
.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
is_aware
(value)¶Returns
True
ifvalue
is aware,False
if it is naive. Thisfunction assumes thatvalue
is adatetime
.
is_naive
(value)¶Returns
True
ifvalue
is naive,False
if it is aware. Thisfunction assumes thatvalue
is adatetime
.
make_aware
(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 thecurrent time zone.Deprecated since version 4.0:When using
pytz
, thepytz.AmbiguousTimeError
exception israised if you try to makevalue
aware during a DST transition wherethe same time occurs twice (when reverting from DST). Settingis_dst
toTrue
orFalse
will avoid the exception bychoosing if the time is pre-transition or post-transition respectively.When using
pytz
, thepytz.NonExistentTimeError
exception israised if you try to makevalue
aware during a DST transition suchthat the time never occurred. For example, if the 2:00 hour is skippedduring a DST transition, trying to make 2:30 aware in that time zonewill raise an exception. To avoid that you can useis_dst
tospecify howmake_aware()
should interpret such a nonexistent time.Ifis_dst=True
then the above time would be interpreted as 2:30 DSTtime (equivalent to 1:30 local time). Conversely, ifis_dst=False
the time would be interpreted as 2:30 standard time (equivalent to 3:30local time).The
is_dst
parameter has no effect when using non-pytz
timezoneimplementations.The
is_dst
parameter is deprecated and will be removed in Django5.0.
make_naive
(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 thecurrent time zone.
django.utils.translation
¶
For a complete discussion on the usage of the following see thetranslation documentation.
gettext
(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, seeContextual markers.
gettext_lazy
(message)¶
pgettext_lazy
(context,message)¶Same as the non-lazy versions above, but using lazy execution.
gettext_noop
(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)¶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
.
ngettext_lazy
(singular,plural,number)¶
npgettext_lazy
(context,singular,plural,number)¶Same as the non-lazy versions above, but using lazy execution.
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 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.
check_for_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
get_language_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
isTrue
, the function first checks the requested URLfor whether its path begins with a language code listed in theLANGUAGES
setting.
get_supported_language_variant
(lang_code,strict=False)¶Returns
lang_code
if it’s in theLANGUAGES
setting, possiblyselecting a more generic variant. For example,'es'
is returned iflang_code
is'es-ar'
and'es'
is inLANGUAGES
but'es-ar'
isn’t.If
strict
isFalse
(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 inLANGUAGES
, that’sreturned forlang_code
s like'es'
and'es-ar'
. Those matchesaren’t returned ifstrict=True
.Raises
LookupError
if nothing is found.
to_locale
(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.