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 theCache-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 isTrue (exactlyTrue, not just atrue value), only the parameter name is added to the header.
  • All other parameters are added with their value, after applyingstr() to it.
get_max_age(response)

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

patch_response_headers(response,cache_timeout=None)

Adds some useful headers to the givenHttpResponse object:

  • Expires
  • Cache-Control

Each header is only added if it isn’t already set.

cache_timeout is in seconds. TheCACHE_MIDDLEWARE_SECONDSsetting is used by default.

add_never_cache_headers(response)

Adds anExpires header to the current date/time.

Adds aCache-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) theVary 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 returnsNone.

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 intheVary 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’sdatetime module.
  • They raiseValueError if their input is well formatted but isn’t avalid date or time.
  • They returnNone 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 adatetime.date.

parse_time(value)

Parses a string and returns adatetime.time.

UTC offsets aren’t supported; ifvalue describes one, the result isNone.

parse_datetime(value)

Parses a string and returns adatetime.datetime.

UTC offsets are supported; ifvalue describes one, the result’stzinfo attribute is adatetime.timezone instance.

parse_duration(value)

Parses a string and returns adatetime.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 likeprocess_request(),process_exception(), andprocess_response()).

decorator_from_middleware_with_args(middleware_class)[source]

Likedecorator_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 astr object representing arbitrary objects. Treatsbytestrings using theencoding codec.

Ifstrings_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 toforce_str(strings_only=True).

force_str(s,encoding='utf-8',strings_only=False,errors='strict')[source]

Similar tosmart_str(), except that lazy instances are resolved tostrings, rather than kept as lazy objects.

Ifstrings_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 objects, encoded asspecified inencoding.

Ifstrings_only isTrue, don’t convert (some) non-string-likeobjects.

force_bytes(s,encoding='utf-8',strings_only=False,errors='strict')[source]

Similar tosmart_bytes, except that lazy instances are resolved tobytestrings, rather than kept as lazy objects.

Ifstrings_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 aPath.

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.

escape_uri_path(path)[source]

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

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

classSyndicationFeed[source]

Base class for all syndication feeds. Subclasses should providewrite().

__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, exceptcategories, 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 exceptpubdate andupdateddate, which aredatetime.datetimeobjects, andenclosures, which is a list ofEnclosure instances.

num_items()[source]
root_attributes()[source]

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

add_root_elements(handler)[source]

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

item_attributes(item)[source]

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

add_item_elements(handler,item)[source]

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

write(outfile,encoding)[source]

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

writeString(encoding)[source]

Returns the feed in the given encoding as a string.

latest_post_date()[source]

Returns the latestpubdate orupdateddate for all items in thefeed. If no items have either of these attributes this returns thecurrent UTC date/time.

Enclosure

classEnclosure[source]

Represents an RSS enclosure

RssFeed

classRssFeed(SyndicationFeed)[source]

Rss201rev2Feed

classRss201rev2Feed(RssFeed)[source]

Spec:https://cyber.harvard.edu/rss/rss.html

RssUserland091Feed

classRssUserland091Feed(RssFeed)[source]

Spec:http://backend.userland.com/rss091

Atom1Feed

classAtom1Feed(SyndicationFeed)[source]

Spec:RFC 4287

django.utils.functional

classcached_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, usingdel (ordelattr) on acached_property that hasn’t been accessed raisesAttributeError.

As well as offering potential performance advantages,@cached_propertycan ensure that an attribute’s value does not change unexpectedly over thelife of an instance. This could occur with a method whose computation isbased 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 anexpensiveget_friends() method and wanted to allow calling it withoutretrieving the cached value, you could write:

friends=cached_property(get_friends)

Whileperson.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:Thename parameter is deprecated and will be removed in Django 5.0as it’s unnecessary as of Python 3.6.

classclassproperty(method=None)[source]

Similar to@classmethod, the@classpropertydecorator 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 indjango.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 thedjango.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):...

Thekeep_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 forkeep_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.safestringwhere appropriate. This module provides some additional low level utilities forescaping HTML.

escape(text)

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

conditional_escape(text)

Similar toescape(), except that it doesn’t operate on preescapedstrings, so it will not double escape.

format_html(format_string,*args,**kwargs)

This is similar tostr.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 applyescape() to eachargument and risk a bug and an XSS vulnerability if you forget one.

Note that although this function usesstr.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 offormat_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>'

Theencoder, 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, theelement_id argument was required.

Changed in Django 4.2:

Theencoder 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 astrip_tag call withoutescaping it first, for example withescape().

For example:

strip_tags(value)

Ifvalue 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’surllib.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 bytime.time(). If set toNone,defaults to the current time.

Outputs a string in the formatWdy,DDMonYYYYHH:MM:SSGMT.

content_disposition_header(as_attachment,filename)[source]
New in Django 4.2.

Constructs aContent-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.

base36_to_int(s)[source]

Converts a base 36 string to an integer.

int_to_base36(i)[source]

Converts a positive integer to a base 36 string.

urlsafe_base64_encode(s)[source]

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

urlsafe_base64_decode(s)[source]

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

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

classSafeString[source]

Astr 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 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.SafeString'>>>>mystr=mystr.strip()# removing whitespace>>>type(mystr)<type 'str'>

django.utils.text

format_lazy(format_string,*args,**kwargs)

A version ofstr.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 matchpersona/(?P<pk>\d+)/$, e.g.persona/5/.

slugify(value,allow_unicode=False)

Converts a string to a URL slug by:

  1. Converting to ASCII ifallow_unicode isFalse (the default).
  2. Converting to lowercase.
  3. Removing characters that aren’t alphanumerics, underscores, hyphens, orwhitespace.
  4. Replacing any whitespace or repeated dashes with single dashes.
  5. 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, passallow_unicode=True. Forexample:

>>>slugify("你好 World",allow_unicode=True)'你好-world'

django.utils.timezone

utc

tzinfo instance that represents UTC.

Deprecated since version 4.1:This is an alias todatetime.timezone.utc. Usedatetime.timezone.utc directly.

get_fixed_timezone(offset)

Returns atzinfo 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 atzinfo instance that represents thedefault time zone.

get_default_timezone_name()

Returns the name of thedefault time zone.

get_current_timezone()

Returns atzinfo instance that represents thecurrent time zone.

get_current_timezone_name()

Returns the name of thecurrent time zone.

activate(timezone)

Sets thecurrent time zone. Thetimezone argument must be an instance of atzinfosubclass 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 withactivate(), 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 awaredatetime to a different time zone,by default thecurrent time zone.

Whenvalue is omitted, it defaults tonow().

This function doesn’t work on naive datetimes; usemake_aware()instead.

localdate(value=None,timezone=None)

Useslocaltime() to convert an awaredatetime to adate() in a different time zone, by default thecurrent time zone.

Whenvalue is omitted, it defaults tonow().

This function doesn’t work on naive datetimes.

now()

Returns adatetime that represents thecurrent point in time. Exactly what’s returned depends on the value ofUSE_TZ:

  • IfUSE_TZ isFalse, this will be anaive datetime (i.e. a datetimewithout an associated timezone) that represents the current timein the system’s local timezone.
  • IfUSE_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.
is_aware(value)

ReturnsTrue ifvalue is aware,False if it is naive. Thisfunction assumes thatvalue is adatetime.

is_naive(value)

ReturnsTrue ifvalue is naive,False if it is aware. Thisfunction assumes thatvalue is adatetime.

make_aware(value,timezone=None,is_dst=None)

Returns an awaredatetime 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 usingpytz, 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 usingpytz, 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=Falsethe time would be interpreted as 2:30 standard time (equivalent to 3:30local time).

Theis_dst parameter has no effect when using non-pytz timezoneimplementations.

Theis_dst parameter is deprecated and will be removed in Django5.0.

make_naive(value,timezone=None)

Returns a naivedatetime 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)

Translatesmessage and returns it as a string.

pgettext(context,message)

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

Seelazy translations documentation.

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)

Translatessingular andplural and returns the appropriate stringbased onnumber.

npgettext(context,singular,plural,number)

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

Seelazy 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 aNullTranslations() instance.This is useful when we want delayed translations to appear as the originalstring for some reason.

override(language,deactivate=False)

A Python context manager that usesdjango.utils.translation.activate() to fetch the translation objectfor a given language, activates it as the translation object for thecurrent thread and reactivates the previous active language on exit.Optionally, it can 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. ReturnsNone iftranslations are temporarily deactivated (bydeactivate_all() orwhenNone is passed tooverride()).

get_language_bidi()

Returns selected language’s BiDi layout:

  • False = left-to-right layout
  • True = 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.

Ifcheck_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)

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

Ifstrict 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_codes like'es' and'es-ar'. Those matchesaren’t returned ifstrict=True.

RaisesLookupError 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 byxgettext.It does so by translating the Django translation tags into standardgettext function invocations.

django.urls functions for use in URLconfs
Validators
Back to Top