doc_content
stringlengths
1
386k
doc_id
stringlengths
5
188
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 ...
django.ref.utils#django.utils.cache.learn_cache_key
patch_cache_control(response, **kwargs) This function patches the Cache-Control header 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 (exactly True, not just a ...
django.ref.utils#django.utils.cache.patch_cache_control
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. The CACHE_MIDDLEWARE_SECONDS setting is used by default.
django.ref.utils#django.utils.cache.patch_response_headers
patch_vary_headers(response, newheaders) Adds (or updates) the Vary header in the given HttpResponse object. newheaders is a list of header names that should be in Vary. If headers contains an asterisk, then Vary header will consist of a single asterisk '*', according to RFC 7231#section-7.1.4. Otherwise, existing he...
django.ref.utils#django.utils.cache.patch_vary_headers
parse_date(value) Parses a string and returns a datetime.date.
django.ref.utils#django.utils.dateparse.parse_date
parse_datetime(value) Parses a string and returns a datetime.datetime. UTC offsets are supported; if value describes one, the result’s tzinfo attribute is a datetime.timezone instance.
django.ref.utils#django.utils.dateparse.parse_datetime
parse_duration(value) Parses a string and returns a 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. P4DT1H15M20S which is equivalent to 4 1:15:20) or PostgreSQL’s day-time interval format (e.g. 3 days 04:05:06).
django.ref.utils#django.utils.dateparse.parse_duration
parse_time(value) Parses a string and returns a datetime.time. UTC offsets aren’t supported; if value describes one, the result is None.
django.ref.utils#django.utils.dateparse.parse_time
async_only_middleware(middleware) [source] Marks a middleware as asynchronous-only. Django will wrap it in an asynchronous event loop when it is called from the WSGI request path.
django.ref.utils#django.utils.decorators.async_only_middleware
decorator_from_middleware(middleware_class) [source] 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...
django.ref.utils#django.utils.decorators.decorator_from_middleware
decorator_from_middleware_with_args(middleware_class) [source] Like decorator_from_middleware, but returns a function that accepts the arguments to be passed to the middleware_class. For example, the cache_page() decorator is created from the CacheMiddleware like this: cache_page = decorator_from_middleware_with_args...
django.ref.utils#django.utils.decorators.decorator_from_middleware_with_args
method_decorator(decorator, name='') [source] Converts a function decorator into a method decorator. It can be used to decorate methods or classes; in the latter case, name is the name of the method to be decorated and is required. decorator may also be a list or tuple of functions. They are wrapped in reverse order ...
django.ref.utils#django.utils.decorators.method_decorator
sync_and_async_middleware(middleware) [source] 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.ref.utils#django.utils.decorators.sync_and_async_middleware
sync_only_middleware(middleware) [source] 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.)
django.ref.utils#django.utils.decorators.sync_only_middleware
class django.utils.deprecation.MiddlewareMixin
django.topics.http.middleware#django.utils.deprecation.MiddlewareMixin
escape_uri_path(path) [source] Escapes the unsafe characters from the path portion of a Uniform Resource Identifier (URI).
django.ref.utils#django.utils.encoding.escape_uri_path
filepath_to_uri(path) [source] 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 n...
django.ref.utils#django.utils.encoding.filepath_to_uri
force_bytes(s, encoding='utf-8', strings_only=False, errors='strict') [source] Similar to smart_bytes, except that lazy instances are resolved to bytestrings, rather than kept as lazy objects. If strings_only is True, don’t convert (some) non-string-like objects.
django.ref.utils#django.utils.encoding.force_bytes
force_str(s, encoding='utf-8', strings_only=False, errors='strict') [source] Similar to smart_str(), except that lazy instances are resolved to strings, rather than kept as lazy objects. If strings_only is True, don’t convert (some) non-string-like objects.
django.ref.utils#django.utils.encoding.force_str
iri_to_uri(iri) [source] 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...
django.ref.utils#django.utils.encoding.iri_to_uri
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).
django.ref.utils#django.utils.encoding.is_protected_type
smart_bytes(s, encoding='utf-8', strings_only=False, errors='strict') [source] Returns a bytestring version of arbitrary object s, encoded as specified in encoding. If strings_only is True, don’t convert (some) non-string-like objects.
django.ref.utils#django.utils.encoding.smart_bytes
smart_str(s, encoding='utf-8', strings_only=False, errors='strict') [source] Returns a str object representing arbitrary object s. Treats bytestrings using the encoding codec. If strings_only is True, don’t convert (some) non-string-like objects.
django.ref.utils#django.utils.encoding.smart_str
uri_to_iri(uri) [source] Converts a Uniform Resource Identifier into an Internationalized Resource Identifier. This is an algorithm from section 3.2 of RFC 3987#section-3.2. Takes a URI in ASCII bytes and returns a string containing the encoded result.
django.ref.utils#django.utils.encoding.uri_to_iri
class Atom1Feed(SyndicationFeed) Spec: RFC 4287
django.ref.utils#django.utils.feedgenerator.Atom1Feed
class Enclosure Represents an RSS enclosure
django.ref.utils#django.utils.feedgenerator.Enclosure
get_tag_uri(url, date) Creates a TagURI. See https://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id
django.ref.utils#django.utils.feedgenerator.get_tag_uri
class Rss201rev2Feed(RssFeed) Spec: https://cyber.harvard.edu/rss/rss.html
django.ref.utils#django.utils.feedgenerator.Rss201rev2Feed
class RssFeed(SyndicationFeed)
django.ref.utils#django.utils.feedgenerator.RssFeed
class RssUserland091Feed(RssFeed) Spec: http://backend.userland.com/rss091
django.ref.utils#django.utils.feedgenerator.RssUserland091Feed
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...
django.ref.utils#django.utils.feedgenerator.SyndicationFeed
__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 keywor...
django.ref.utils#django.utils.feedgenerator.SyndicationFeed.__init__
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 pubdate and updateddate...
django.ref.utils#django.utils.feedgenerator.SyndicationFeed.add_item
add_item_elements(handler, item) Add elements on each item (i.e. item/entry) element.
django.ref.utils#django.utils.feedgenerator.SyndicationFeed.add_item_elements
add_root_elements(handler) Add elements in the root (i.e. feed/channel) element. Called from write().
django.ref.utils#django.utils.feedgenerator.SyndicationFeed.add_root_elements
item_attributes(item) Return extra attributes to place on each item (i.e. item/entry) element.
django.ref.utils#django.utils.feedgenerator.SyndicationFeed.item_attributes
latest_post_date() Returns the latest pubdate or updateddate for all items in the feed. If no items have either of these attributes this returns the current UTC date/time.
django.ref.utils#django.utils.feedgenerator.SyndicationFeed.latest_post_date
num_items()
django.ref.utils#django.utils.feedgenerator.SyndicationFeed.num_items
root_attributes() Return extra attributes to place on the root (i.e. feed/channel) element. Called from write().
django.ref.utils#django.utils.feedgenerator.SyndicationFeed.root_attributes
write(outfile, encoding) Outputs the feed in the given encoding to outfile, which is a file-like object. Subclasses should override this.
django.ref.utils#django.utils.feedgenerator.SyndicationFeed.write
writeString(encoding) Returns the feed in the given encoding as a string.
django.ref.utils#django.utils.feedgenerator.SyndicationFeed.writeString
class cached_property(func, name=None) [source] The @cached_property decorator caches the result of a method with a single self argument 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 retu...
django.ref.utils#django.utils.functional.cached_property
class classproperty(method=None) [source] Similar to @classmethod, the @classproperty decorator converts the result of a method with a single cls argument into a property that can be accessed directly from the class.
django.ref.utils#django.utils.functional.classproperty
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 other code. If you write your own similar functions and deal with...
django.ref.utils#django.utils.functional.keep_lazy
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 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(...
django.ref.utils#django.utils.functional.keep_lazy_text
conditional_escape(text) Similar to escape(), except that it doesn’t operate on pre-escaped strings, so it will not double escape.
django.ref.utils#django.utils.html.conditional_escape
escape(text) 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.
django.ref.utils#django.utils.html.escape
format_html(format_string, *args, **kwargs) This is similar to str.format(), except that it is appropriate for building up HTML fragments. All args and kwargs are passed through conditional_escape() before being passed to str.format(). For the case of building up small HTML fragments, this function is to be preferred...
django.ref.utils#django.utils.html.format_html
format_html_join(sep, format_string, args_generator) A wrapper of format_html(), for the common case of a group of arguments that need to be formatted using the same format string, and then joined using sep. sep is also passed through conditional_escape(). args_generator should be an iterator that returns the sequenc...
django.ref.utils#django.utils.html.format_html_join
html_safe() The __html__() method on a class helps non-Django templates detect classes whose output doesn’t require HTML escaping. This decorator defines the __html__() method on the decorated class by wrapping __str__() in mark_safe(). Ensure the __str__() method does indeed return text that doesn’t require HTML esc...
django.ref.utils#django.utils.html.html_safe
strip_tags(value) Tries to remove anything that looks like an HTML tag from the string, that is anything contained within <>. Absolutely NO guarantee is provided about the resulting string being HTML safe. So NEVER mark safe the result of a strip_tag call without escaping it first, for example with escape(). For exam...
django.ref.utils#django.utils.html.strip_tags
base36_to_int(s) [source] Converts a base 36 string to an integer.
django.ref.utils#django.utils.http.base36_to_int
http_date(epoch_seconds=None) [source] 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 to None, defaults to the current time. Outpu...
django.ref.utils#django.utils.http.http_date
int_to_base36(i) [source] Converts a positive integer to a base 36 string.
django.ref.utils#django.utils.http.int_to_base36
urlencode(query, doseq=False) [source] A version of Python’s urllib.parse.urlencode() function that can operate on MultiValueDict and non-string values.
django.ref.utils#django.utils.http.urlencode
urlsafe_base64_decode(s) [source] Decodes a base64 encoded string, adding back any trailing equal signs that might have been stripped.
django.ref.utils#django.utils.http.urlsafe_base64_decode
urlsafe_base64_encode(s) [source] Encodes a bytestring to a base64 string for use in URLs, stripping any trailing equal signs.
django.ref.utils#django.utils.http.urlsafe_base64_encode
class AdminEmailHandler(include_html=False, email_backend=None, reporter_class=None) This handler sends an email to the site ADMINS for each log message it receives. If the log record contains a request attribute, the full details of the request will be included in the email. The email subject will include the phrase...
django.ref.logging#django.utils.log.AdminEmailHandler
send_mail(subject, message, *args, **kwargs) Sends emails to admin users. To customize this behavior, you can subclass the AdminEmailHandler class and override this method.
django.ref.logging#django.utils.log.AdminEmailHandler.send_mail
class CallbackFilter(callback) This filter accepts a callback function (which should accept a single argument, the record to be logged), and calls it for each record that passes through the filter. Handling of that record will not proceed if the callback returns False. For instance, to filter out UnreadablePostError ...
django.ref.logging#django.utils.log.CallbackFilter
class RequireDebugFalse This filter will only pass on records when settings.DEBUG is False. This filter is used as follows in the default LOGGING configuration to ensure that the AdminEmailHandler only sends error emails to admins when DEBUG is False: 'filters': { 'require_debug_false': { '()': 'django.ut...
django.ref.logging#django.utils.log.RequireDebugFalse
class RequireDebugTrue This filter is similar to RequireDebugFalse, except that records are passed only when DEBUG is True.
django.ref.logging#django.utils.log.RequireDebugTrue
import_string(dotted_path) [source] Imports a dotted module path and returns the attribute/class designated by the last name in the path. Raises ImportError if the import failed. For example: from django.utils.module_loading import import_string ValidationError = import_string('django.core.exceptions.ValidationError'...
django.ref.utils#django.utils.module_loading.import_string
mark_safe(s) [source] 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.for...
django.ref.utils#django.utils.safestring.mark_safe
class SafeString [source] A str subclass that has been specifically marked as “safe” (requires no further escaping) for HTML output purposes.
django.ref.utils#django.utils.safestring.SafeString
format_lazy(format_string, *args, **kwargs) A version of str.format() for when format_string, args, and/or kwargs contain 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(...
django.ref.utils#django.utils.text.format_lazy
slugify(value, allow_unicode=False) Converts a string to a URL slug by: Converting to ASCII if allow_unicode is False (the default). Converting to lowercase. Removing characters that aren’t alphanumerics, underscores, hyphens, or whitespace. Replacing any whitespace or repeated dashes with single dashes. Removing le...
django.ref.utils#django.utils.text.slugify
activate(timezone) Sets the current time zone. The timezone argument must be an instance of a tzinfo subclass or a time zone name.
django.ref.utils#django.utils.timezone.activate
deactivate() Unsets the current time zone.
django.ref.utils#django.utils.timezone.deactivate
get_current_timezone() Returns a tzinfo instance that represents the current time zone.
django.ref.utils#django.utils.timezone.get_current_timezone
get_current_timezone_name() Returns the name of the current time zone.
django.ref.utils#django.utils.timezone.get_current_timezone_name
get_default_timezone() Returns a tzinfo instance that represents the default time zone.
django.ref.utils#django.utils.timezone.get_default_timezone
get_default_timezone_name() Returns the name of the default time zone.
django.ref.utils#django.utils.timezone.get_default_timezone_name
get_fixed_timezone(offset) Returns a tzinfo instance that represents a time zone with a fixed offset from UTC. offset is a datetime.timedelta or an integer number of minutes. Use positive values for time zones east of UTC and negative values for west of UTC.
django.ref.utils#django.utils.timezone.get_fixed_timezone
is_aware(value) Returns True if value is aware, False if it is naive. This function assumes that value is a datetime.
django.ref.utils#django.utils.timezone.is_aware
is_naive(value) Returns True if value is naive, False if it is aware. This function assumes that value is a datetime.
django.ref.utils#django.utils.timezone.is_naive
localdate(value=None, timezone=None) Uses localtime() to convert an aware datetime to a date() in a different time zone, by default the current time zone. When value is omitted, it defaults to now(). This function doesn’t work on naive datetimes.
django.ref.utils#django.utils.timezone.localdate
localtime(value=None, timezone=None) Converts an aware datetime to a different time zone, by default the current time zone. When value is omitted, it defaults to now(). This function doesn’t work on naive datetimes; use make_aware() instead.
django.ref.utils#django.utils.timezone.localtime
make_aware(value, timezone=None, is_dst=None) Returns an aware datetime that represents the same point in time as value in timezone, value being a naive datetime. If timezone is set to None, it defaults to the current time zone. Deprecated since version 4.0: When using pytz, the pytz.AmbiguousTimeError exception is ...
django.ref.utils#django.utils.timezone.make_aware
make_naive(value, timezone=None) Returns a naive datetime that represents in timezone the same point in time as value, value being an aware datetime. If timezone is set to None, it defaults to the current time zone.
django.ref.utils#django.utils.timezone.make_naive
now() Returns a datetime that represents the current point in time. Exactly what’s returned depends on the value of USE_TZ: If USE_TZ is False, 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_TZ is True, this will ...
django.ref.utils#django.utils.timezone.now
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 the timezone argument is None, the current time zone is unset on entry with deactivate() instead. override is also usable as a function decorator.
django.ref.utils#django.utils.timezone.override
utc tzinfo instance that represents UTC.
django.ref.utils#django.utils.timezone.utc
activate(language) Fetches the translation object for a given language and activates it as the current translation object for the current thread.
django.ref.utils#django.utils.translation.activate
check_for_language(lang_code) 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.
django.ref.utils#django.utils.translation.check_for_language
deactivate() Deactivates the currently active translation object so that further _ calls will resolve against the default translation object, again.
django.ref.utils#django.utils.translation.deactivate
deactivate_all() 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.
django.ref.utils#django.utils.translation.deactivate_all
get_language() Returns the currently selected language code. Returns None if translations are temporarily deactivated (by deactivate_all() or when None is passed to override()).
django.ref.utils#django.utils.translation.get_language
get_language_bidi() Returns selected language’s BiDi layout: False = left-to-right layout True = right-to-left layout
django.ref.utils#django.utils.translation.get_language_bidi
get_language_from_request(request, check_path=False) 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_path is True,...
django.ref.utils#django.utils.translation.get_language_from_request
get_language_info()
django.topics.i18n.translation#django.utils.translation.get_language_info
get_supported_language_variant(lang_code, strict=False) Returns lang_code if it’s in the LANGUAGES setting, possibly selecting a more generic variant. For example, 'es' is returned if lang_code is 'es-ar' and 'es' is in LANGUAGES but 'es-ar' isn’t. If strict is False (the default), a country-specific variant may be r...
django.ref.utils#django.utils.translation.get_supported_language_variant
gettext(message) Translates message and returns it as a string.
django.ref.utils#django.utils.translation.gettext
gettext_lazy(message)
django.ref.utils#django.utils.translation.gettext_lazy
gettext_noop(message) 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.
django.ref.utils#django.utils.translation.gettext_noop
ngettext(singular, plural, number) Translates singular and plural and returns the appropriate string based on number.
django.ref.utils#django.utils.translation.ngettext
ngettext_lazy(singular, plural, number)
django.ref.utils#django.utils.translation.ngettext_lazy
npgettext(context, singular, plural, number) Translates singular and plural and returns the appropriate string based on number and the context.
django.ref.utils#django.utils.translation.npgettext
npgettext_lazy(context, singular, plural, number) Same as the non-lazy versions above, but using lazy execution. See lazy translations documentation.
django.ref.utils#django.utils.translation.npgettext_lazy
override(language, deactivate=False) 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 tempor...
django.ref.utils#django.utils.translation.override