Perlengkapan Django¶
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 HTTP 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:ExpiresCache-Control
Setiap kepala hanya ditambahkan jika belum disetel.
cache_timeoutis in seconds. TheCACHE_MIDDLEWARE_SECONDSsetting is used by default.
-
add_never_cache_headers(response)¶ Adds an
Expiresheader to the current date/time.Adds a
Cache-Control: max-age=0, no-cache, no-store, must-revalidate, privateheader to a response to indicate that a page should never be cached.Setiap kepala hanya ditambahkan jika belum disetel.
-
patch_vary_headers(response, newheaders)¶ Adds (or updates) the
Varyheader in the givenHttpResponseobject.newheadersis a list of header names that should be inVary. If headers contains an asterisk, thenVaryheader will consist of a single asterisk'*', according to RFC 7231#section-7.1.4. Otherwise, existing headers inVaryaren't removed.
-
get_cache_key(request, key_prefix=None, method='GET', cache=None)¶ Mengembalikan sebuah kunci cache pada jalur permintaan. Itu dapat digunakan di tahapan permintaan karena itu mengambil daftar dari kepala untuk diambil kedalam akun dari registrar jalur global dan menggunakan mereka untuk membangun sebuah kunci cache untuk memeriksa.
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, cache=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 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 accept strings in ISO 8601 date/time formats (or some close
alternatives) and return objects from the corresponding classes in Python's
datetimemodule. - 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)¶ Mengurai string dan mengembalikan
datetime.date.
-
parse_time(value)¶ Mengurai string dan mengembalikan
datetime.time.UTC offsets aren't supported; if
valuedescribes one, the result isNone.
-
parse_datetime(value)¶ Mengurai string dan mengembalikan
datetime.datetime.UTC offsets are supported; if
valuedescribes one, the result'stzinfoattribute is adatetime.timezoneinstance.
-
parse_duration(value)¶ Mengurai string dan mengembalikan
datetime.timedelta.Expects data in the format
"DD HH:MM:SS.uuuuuu","DD HH:MM:SS,uuuuuu", or as specified by ISO 8601 (e.g.P4DT1H15M20Swhich is equivalent to4 1:15:20) or PostgreSQL's day-time interval format (e.g.3 days 04:05:06).
django.utils.decorators¶
-
method_decorator(decorator, name='')[sumber]¶ 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.Lihat decorating class based views untuk contoh penggunaan.
-
decorator_from_middleware(middleware_class)[sumber]¶ 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)[sumber]¶ 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
-
sync_only_middleware(middleware)[sumber]¶ Marks a middleware as synchronous-only. (The default in Django, but this allows you to future-proof if the default ever changes in a future release.)
-
async_only_middleware(middleware)[sumber]¶ Marks a middleware as asynchronous-only. Django will wrap it in an asynchronous event loop when it is called from the WSGI request path.
-
sync_and_async_middleware(middleware)[sumber]¶ Marks a middleware as sync and async compatible, this allows to avoid converting requests. You must implement detection of the current request type to use this decorator. See asynchronous middleware documentation for details.
django.utils.encoding¶
-
smart_str(s, encoding='utf-8', strings_only=False, errors='strict')[sumber]¶ Returns a
strobject representing arbitrary objects. Treats bytestrings using theencodingcodec.If
strings_onlyisTrue, don't convert (some) non-string-like objects.
-
is_protected_type(obj)[sumber]¶ Tentukan jika instance obyek adalah jenis dilindungi.
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')[sumber]¶ Similar to
smart_str(), 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.
-
smart_bytes(s, encoding='utf-8', strings_only=False, errors='strict')[sumber]¶ Returns a bytestring version of arbitrary object
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')[sumber]¶ 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.
-
iri_to_uri(iri)[sumber]¶ 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, slightly simplified since the input is assumed to be a string rather than an arbitrary byte stream.
Takes an IRI (string or UTF-8 bytes) and returns a string containing the encoded result.
-
uri_to_iri(uri)[sumber]¶ Merubah Uniform Resource Identifier menjadi Internationalized Resource Identifier.
Ini adalah sebuah algoritma dari bagian 3.2 dari RFC 3987#section-3.2.
Takes a URI in ASCII bytes and returns a string containing the encoded result.
-
filepath_to_uri(path)[sumber]¶ 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 bytes, string, or a
Path.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¶
Contoh penggunaan:
>>> 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 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.",
... )
>>> 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
Untuk pengertian dari versi berbeda dari RSS, lihat https://web.archive.org/web/20110718035220/http://diveintomark.org/archives/2004/02/04/incompatible-rss
-
get_tag_uri(url, date)¶ Membuat TagURI.
Lihat 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 strings, except
categories, which should be 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)¶ Adds an item to the feed. All args are expected to be strings except
pubdateandupdateddate, which aredatetime.datetimeobjects, andenclosures, which is a list ofEnclosureinstances.
-
num_items()¶
-
root_attributes()¶ Return extra attributes to place on the root (i.e. feed/channel) element. Called from
write().
-
add_root_elements(handler)¶ Tambah unsur-unsur dalam akar unsur (yaitu feed/channel). Dipanggil dari
write().
-
item_attributes(item)¶ Mengembalikan atribut tambahan untuk ditempatkan pada setiap unsur (yaitu item/entry) barang
-
add_item_elements(handler, item)¶ Tambah unsur-unsur pada setiap unsur (yaitu item/entry) barang.
-
write(outfile, encoding)¶ Outputs the feed in the given encoding to
outfile, which is a file-like object. Subclasses should override this.
-
writeString(encoding)¶ Returns the feed in the given encoding as a string.
-
latest_post_date()¶ Returns the latest
pubdateorupdateddatefor all items in the feed. If no items have either of these attributes this returns the current UTC date/time.
-
Rss201rev2Feed¶
-
class
Rss201rev2Feed(RssFeed)¶ Specifikasi: https://cyber.harvard.edu/rss/rss.html
RssUserland091Feed¶
-
class
RssUserland091Feed(RssFeed)¶ Spesifikasi: http://backend.userland.com/rss091
django.utils.functional¶
-
class
cached_property(func, name=None)[sumber]¶ 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(): ...
Dan dalam cetakan anda akan miliki:
{% 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 accessed appropriately:
# in the view: if person.friends: ...
The cached value can be treated like an ordinary attribute of the instance:
# clear it, requiring re-computation next time it's called del person.friends # or delattr(person, "friends") # set a value manually, that will persist on the instance until cleared person.friends = ["Huckleberry Finn", "Tom Sawyer"]
Because of the way the descriptor protocol works, using
del(ordelattr) on acached_propertythat 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 the life of an instance. This could occur with a method whose computation is based ondatetime.now(), or 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 make cached properties of methods. For example, if you had an expensive
get_friends()method and wanted to allow calling it without retrieving the cached value, you could write:friends = cached_property(get_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
-
class
classproperty(method=None)[sumber]¶ Similar to
@classmethod, the@classpropertydecorator converts the result of a method with a singleclsargument into a property that can be accessed directly from the class.
-
keep_lazy(func, *resultclasses)[sumber]¶ Django menawarkan banyak fungsi-fungsi kegunaan (khususnya dalam
django.utils) yang mengambil sebuah string sebagai argumen pertama mereka dan melakukan sesuatu ke string itu. Fungsi-fungsi ini digunakan oleh penyaring cetakan sama halnya langsung dalam kode lain.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.Sebagai contoh:
from django.utils.functional import keep_lazy, keep_lazy_text def fancy_utility_function(s, ...): # Do some conversion on string 's' ... fancy_utility_function = keep_lazy(str)(fancy_utility_function) # Or more succinctly: @keep_lazy(str) def fancy_utility_function(s, ...): ...
The
keep_lazy()decorator takes a number of extra arguments (*args) specifying the type(s) that the original function can return. A common use case is to have functions that return text. For these, you can pass thestrtype tokeep_lazy(or use thekeep_lazy_text()decorator described in the next section).Menggunakan penghias ini berarti anda dapat menulis fungsi anda dan menganggap bahwa masukan adalah string yang sesuai, kemudian tambah dukungan untuk obyek terjemahan lazy pada akhirnya.
-
keep_lazy_text(func)[sumber]¶ Sebuah jalan pintas untuk
keep_lazy(str)(func).If you have a function that returns text and you want to be able to take lazy arguments while delaying their evaluation, you can use this decorator:
from django.utils.functional import keep_lazy, keep_lazy_text # Our previous example was: @keep_lazy(str) def fancy_utility_function(s, ...): ... # Which can be rewritten as: @keep_lazy_text def fancy_utility_function(s, ...): ...
django.utils.html¶
Usually you should build up HTML using Django's templates to make use of 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)[sumber]¶ Returns the given text with ampersands, quotes and angle brackets encoded for use in HTML. The input is first coerced to a string and the output has
mark_safe()applied.
-
conditional_escape(text)[sumber]¶ Mirip pada
escape(), kecuali bahwa itu tidak berjalan pada string pra-pelolosan, jadi itu tidak akan pelolosan ganda.
-
format_html(format_string, *args, **kwargs)[sumber]¶ 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.Jadi, daripada menulis:
mark_safe("%s <b>%s</b> %s" % ( some_html, escape(some_text), escape(some_other_text), ))
Sebaiknya anda gunakan:
format_html("{} <b>{}</b> {}", mark_safe(some_html), some_text, some_other_text, )
Ini mempunyai keuntungan bahwa anda tidak butuh memberlakukan salinan
escape()pada setiap argumen dan resiko sebuah kesalahan dan kerentanan XSS jika anda melupakan satu.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_str()on the values.
-
format_html_join(sep, format_string, args_generator)[sumber]¶ 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) )
-
strip_tags(value)[sumber]¶ Mencoba memindahkan apapun yang terlihat seperti etiket HTML dari string, yaitu apapun mengandung dalam
<>.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().Sebagai contoh:
strip_tags(value)
Jika
valueadalah"<b>Joel</b> <button>is</button> a <span>slug</span>"nilai balikan akan menjadi"Joel is a slug".Jika anda mencari pemecahan yang lebih kuat, lihatlah pustaka Python bleach.
-
html_safe()[sumber]¶ Metode
__html__()pada kelas membantu cetakan bukan-Django mengenali kelas-kelas yang keluarannya tidak membutuhkan pelolosan HTML.This decorator defines the
__html__()method on the decorated class by wrapping__str__()inmark_safe(). Ensure the__str__()method does indeed return text that doesn't require HTML escaping.
django.utils.http¶
-
urlencode(query, doseq=False)[sumber]¶ Versi dari fungsi
urllib.parse.urlencode()python yang dapat beroperasi padaMultiValueDictdan nilai-nilai bukan-string.
-
http_date(epoch_seconds=None)[sumber]¶ Formats the time to match the RFC 1123#section-5.2.14 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.
django.utils.module_loading¶
Fungsi-fungsi untuk bekerja dengan modeul-modul Python.
-
import_string(dotted_path)[sumber]¶ 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')
setara pada:
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
SafeString[sumber]¶ A
strsubclass that has been specifically marked as "safe" (requires no further escaping) for HTML output purposes.
-
mark_safe(s)[sumber]¶ Explicitly mark a string as safe for (HTML) output purposes. The returned object 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/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 = [ 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)[sumber]¶ Merubah string menjadi sebuah tanda siput URL dengan:
- Converting to ASCII if
allow_unicodeisFalse(the default). - Merubah ke huruf kecil.
- Removing characters that aren't alphanumerics, underscores, hyphens, or whitespace.
- Replacing any whitespace or repeated dashes with single dashes.
- Removing leading and trailing whitespace, dashes, and underscores.
Sebagai contoh:
>>> slugify(' Joel is a slug ') 'joel-is-a-slug'
If you want to allow Unicode characters, pass
allow_unicode=True. For example:>>> slugify('你好 World', allow_unicode=True) '你好-world'
Changed in Django 3.2:In older versions, leading and trailing dashes and underscores are not removed.
- Converting to ASCII if
django.utils.timezone¶
-
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()¶ Tidak disetel 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.Ketika
valuedihilangkan, itu awalan padanow().Fungsi ini tidak bekerja pada datetime yang tidak dibuat-buat., gunakan
make_aware()sebagai gantinya.
-
localdate(value=None, timezone=None)¶ Uses
localtime()to convert an awaredatetimeto adate()in a different time zone, by default the current time zone.Ketika
valuedihilangkan, itu awalan padanow().Fungsi ini tidak bekerja pada datetime yang tidak dibuat-buat.
-
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 get the 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.Ditinggalkan sejak versi 4.0: When using
pytz, thepytz.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.When using
pytz, thepytz.NonExistentTimeErrorexception is raised if you try to makevalueaware during a DST transition such that the time never occurred. For example, if the 2:00 hour is skipped during a DST transition, trying to make 2:30 aware in that time zone will raise an exception. To avoid that you can useis_dstto specify howmake_aware()should interpret such a nonexistent time. Ifis_dst=Truethen the above time would be interpreted as 2:30 DST time (equivalent to 1:30 local time). Conversely, ifis_dst=Falsethe time would be interpreted as 2:30 standard time (equivalent to 3:30 local time).The
is_dstparameter has no effect when using non-pytztimezone implementations.The
is_dstparameter is deprecated and will be removed in Django 5.0.
-
make_naive(value, timezone=None)¶ Returns a 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¶
Untuk obrolan lengkap pada penggunakan dari berikut lihat translation documentation.
-
pgettext(context, message)[sumber]¶ Menterjemahkan
messagememberikancontectdan mengembalikan itu sebagai sebuah string.Untuk informasi lebih, lihat Contextual markers.
-
gettext_lazy(message)¶
-
pgettext_lazy(context, message)¶ Same as the non-lazy versions above, but using lazy execution.
-
gettext_noop(message)[sumber]¶ Marks strings for translation but doesn't translate them now. This can be used to store strings in global variables that should stay in the base language (because they might be used externally) and will be translated later.
-
ngettext(singular, plural, number)[sumber]¶ Translates
singularandpluraland returns the appropriate string based onnumber.
-
npgettext(context, singular, plural, number)[sumber]¶ Translates
singularandpluraland returns the appropriate string based onnumberand thecontext.
-
npgettext_lazy(context, singular, plural, number)[sumber]¶ Same as the non-lazy versions above, but using lazy execution.
-
activate(language)[sumber]¶ Fetches the translation object for a given language and activates it as the current translation object for the current thread.
-
deactivate()[sumber]¶ Deactivates the currently active translation object so that further _ calls will resolve against the default translation object, again.
-
deactivate_all()[sumber]¶ Makes the active translation object a
NullTranslations()instance. This is useful when we want delayed translations to appear as the original string for some reason.
-
override(language, deactivate=False)[sumber]¶ A Python context manager that uses
django.utils.translation.activate()to fetch the translation object for a given language, activates it as the translation object for the current thread and reactivates the previous active language on exit. Optionally, it can deactivate the temporary translation on exit withdjango.utils.translation.deactivate()if thedeactivateargument isTrue. If you passNoneas the language argument, aNullTranslations()instance is activated within the context.overrideis also usable as a function decorator.
-
check_for_language(lang_code)[sumber]¶ Checks whether there is a global language file for the given language code (e.g. 'fr', 'pt_BR'). This is used to decide whether a user-provided language is available.
-
get_language()[sumber]¶ Returns the currently selected language code. Returns
Noneif translations are temporarily deactivated (bydeactivate_all()or whenNoneis passed tooverride()).
-
get_language_bidi()[sumber]¶ Returns selected language's BiDi layout:
False= tata letak kiri-ke-kananTrue= tata letak kanan-ke-kiri
-
get_language_from_request(request, check_path=False)[sumber]¶ Analyzes the request to find what language the user wants the system to show. Only languages listed in settings.LANGUAGES are taken into account. If the user requests a sublanguage where we have a main language, we send out the main language.
If
check_pathisTrue, the function first checks the requested URL for whether its path begins with a language code listed in theLANGUAGESsetting.
-
get_supported_language_variant(lang_code, strict=False)[sumber]¶ Returns
lang_codeif it's in theLANGUAGESsetting, possibly selecting a more generic variant. For example,'es'is returned iflang_codeis'es-ar'and'es'is inLANGUAGESbut'es-ar'isn't.If
strictisFalse(the default), a country-specific variant may be returned when neither the language code nor its generic variant is found. For example, if only'es-co'is inLANGUAGES, that's returned forlang_codes like'es'and'es-ar'. Those matches aren't returned ifstrict=True.Memunculkan
LookupErrorjika tidak ditemukan apapun.