summaryrefslogtreecommitdiff
path: root/django/templatetags
diff options
context:
space:
mode:
authordjango-bot <ops@djangoproject.com>2022-02-03 20:24:19 +0100
committerMariusz Felisiak <felisiak.mariusz@gmail.com>2022-02-07 20:37:05 +0100
commit9c19aff7c7561e3a82978a272ecdaad40dda5c00 (patch)
treef0506b668a013d0063e5fba3dbf4863b466713ba /django/templatetags
parentf68fa8b45dfac545cfc4111d4e52804c86db68d3 (diff)
Refs #33476 -- Reformatted code with Black.
Diffstat (limited to 'django/templatetags')
-rw-r--r--django/templatetags/cache.py35
-rw-r--r--django/templatetags/i18n.py189
-rw-r--r--django/templatetags/l10n.py10
-rw-r--r--django/templatetags/static.py32
-rw-r--r--django/templatetags/tz.py51
5 files changed, 190 insertions, 127 deletions
diff --git a/django/templatetags/cache.py b/django/templatetags/cache.py
index 9e402a1206..4a60cd8afd 100644
--- a/django/templatetags/cache.py
+++ b/django/templatetags/cache.py
@@ -1,8 +1,6 @@
from django.core.cache import InvalidCacheBackendError, caches
from django.core.cache.utils import make_template_fragment_key
-from django.template import (
- Library, Node, TemplateSyntaxError, VariableDoesNotExist,
-)
+from django.template import Library, Node, TemplateSyntaxError, VariableDoesNotExist
register = Library()
@@ -19,26 +17,34 @@ class CacheNode(Node):
try:
expire_time = self.expire_time_var.resolve(context)
except VariableDoesNotExist:
- raise TemplateSyntaxError('"cache" tag got an unknown variable: %r' % self.expire_time_var.var)
+ raise TemplateSyntaxError(
+ '"cache" tag got an unknown variable: %r' % self.expire_time_var.var
+ )
if expire_time is not None:
try:
expire_time = int(expire_time)
except (ValueError, TypeError):
- raise TemplateSyntaxError('"cache" tag got a non-integer timeout value: %r' % expire_time)
+ raise TemplateSyntaxError(
+ '"cache" tag got a non-integer timeout value: %r' % expire_time
+ )
if self.cache_name:
try:
cache_name = self.cache_name.resolve(context)
except VariableDoesNotExist:
- raise TemplateSyntaxError('"cache" tag got an unknown variable: %r' % self.cache_name.var)
+ raise TemplateSyntaxError(
+ '"cache" tag got an unknown variable: %r' % self.cache_name.var
+ )
try:
fragment_cache = caches[cache_name]
except InvalidCacheBackendError:
- raise TemplateSyntaxError('Invalid cache name specified for cache tag: %r' % cache_name)
+ raise TemplateSyntaxError(
+ "Invalid cache name specified for cache tag: %r" % cache_name
+ )
else:
try:
- fragment_cache = caches['template_fragments']
+ fragment_cache = caches["template_fragments"]
except InvalidCacheBackendError:
- fragment_cache = caches['default']
+ fragment_cache = caches["default"]
vary_on = [var.resolve(context) for var in self.vary_on]
cache_key = make_template_fragment_key(self.fragment_name, vary_on)
@@ -49,7 +55,7 @@ class CacheNode(Node):
return value
-@register.tag('cache')
+@register.tag("cache")
def do_cache(parser, token):
"""
This will cache the contents of a template fragment for a given amount
@@ -75,18 +81,19 @@ def do_cache(parser, token):
Each unique set of arguments will result in a unique cache entry.
"""
- nodelist = parser.parse(('endcache',))
+ nodelist = parser.parse(("endcache",))
parser.delete_first_token()
tokens = token.split_contents()
if len(tokens) < 3:
raise TemplateSyntaxError("'%r' tag requires at least 2 arguments." % tokens[0])
- if len(tokens) > 3 and tokens[-1].startswith('using='):
- cache_name = parser.compile_filter(tokens[-1][len('using='):])
+ if len(tokens) > 3 and tokens[-1].startswith("using="):
+ cache_name = parser.compile_filter(tokens[-1][len("using=") :])
tokens = tokens[:-1]
else:
cache_name = None
return CacheNode(
- nodelist, parser.compile_filter(tokens[1]),
+ nodelist,
+ parser.compile_filter(tokens[1]),
tokens[2], # fragment_name can't be a variable.
[parser.compile_filter(t) for t in tokens[3:]],
cache_name,
diff --git a/django/templatetags/i18n.py b/django/templatetags/i18n.py
index efe5f28941..9724efbd91 100644
--- a/django/templatetags/i18n.py
+++ b/django/templatetags/i18n.py
@@ -15,8 +15,10 @@ class GetAvailableLanguagesNode(Node):
self.variable = variable
def render(self, context):
- context[self.variable] = [(k, translation.gettext(v)) for k, v in settings.LANGUAGES]
- return ''
+ context[self.variable] = [
+ (k, translation.gettext(v)) for k, v in settings.LANGUAGES
+ ]
+ return ""
class GetLanguageInfoNode(Node):
@@ -27,7 +29,7 @@ class GetLanguageInfoNode(Node):
def render(self, context):
lang_code = self.lang_code.resolve(context)
context[self.variable] = translation.get_language_info(lang_code)
- return ''
+ return ""
class GetLanguageInfoListNode(Node):
@@ -46,7 +48,7 @@ class GetLanguageInfoListNode(Node):
def render(self, context):
langs = self.languages.resolve(context)
context[self.variable] = [self.get_language_info(lang) for lang in langs]
- return ''
+ return ""
class GetCurrentLanguageNode(Node):
@@ -55,7 +57,7 @@ class GetCurrentLanguageNode(Node):
def render(self, context):
context[self.variable] = translation.get_language()
- return ''
+ return ""
class GetCurrentLanguageBidiNode(Node):
@@ -64,47 +66,54 @@ class GetCurrentLanguageBidiNode(Node):
def render(self, context):
context[self.variable] = translation.get_language_bidi()
- return ''
+ return ""
class TranslateNode(Node):
child_nodelists = ()
- def __init__(self, filter_expression, noop, asvar=None,
- message_context=None):
+ def __init__(self, filter_expression, noop, asvar=None, message_context=None):
self.noop = noop
self.asvar = asvar
self.message_context = message_context
self.filter_expression = filter_expression
if isinstance(self.filter_expression.var, str):
self.filter_expression.is_var = True
- self.filter_expression.var = Variable("'%s'" %
- self.filter_expression.var)
+ self.filter_expression.var = Variable("'%s'" % self.filter_expression.var)
def render(self, context):
self.filter_expression.var.translate = not self.noop
if self.message_context:
- self.filter_expression.var.message_context = (
- self.message_context.resolve(context))
+ self.filter_expression.var.message_context = self.message_context.resolve(
+ context
+ )
output = self.filter_expression.resolve(context)
value = render_value_in_context(output, context)
# Restore percent signs. Percent signs in template text are doubled
# so they are not interpreted as string format flags.
is_safe = isinstance(value, SafeData)
- value = value.replace('%%', '%')
+ value = value.replace("%%", "%")
value = mark_safe(value) if is_safe else value
if self.asvar:
context[self.asvar] = value
- return ''
+ return ""
else:
return value
class BlockTranslateNode(Node):
-
- def __init__(self, extra_context, singular, plural=None, countervar=None,
- counter=None, message_context=None, trimmed=False, asvar=None,
- tag_name='blocktranslate'):
+ def __init__(
+ self,
+ extra_context,
+ singular,
+ plural=None,
+ countervar=None,
+ counter=None,
+ message_context=None,
+ trimmed=False,
+ asvar=None,
+ tag_name="blocktranslate",
+ ):
self.extra_context = extra_context
self.singular = singular
self.plural = plural
@@ -117,9 +126,9 @@ class BlockTranslateNode(Node):
def __repr__(self):
return (
- f'<{self.__class__.__qualname__}: '
- f'extra_context={self.extra_context!r} '
- f'singular={self.singular!r} plural={self.plural!r}>'
+ f"<{self.__class__.__qualname__}: "
+ f"extra_context={self.extra_context!r} "
+ f"singular={self.singular!r} plural={self.plural!r}>"
)
def render_token_list(self, tokens):
@@ -127,11 +136,11 @@ class BlockTranslateNode(Node):
vars = []
for token in tokens:
if token.token_type == TokenType.TEXT:
- result.append(token.contents.replace('%', '%%'))
+ result.append(token.contents.replace("%", "%%"))
elif token.token_type == TokenType.VAR:
- result.append('%%(%s)s' % token.contents)
+ result.append("%%(%s)s" % token.contents)
vars.append(token.contents)
- msg = ''.join(result)
+ msg = "".join(result)
if self.trimmed:
msg = translation.trim_whitespace(msg)
return msg, vars
@@ -143,7 +152,9 @@ class BlockTranslateNode(Node):
message_context = None
# Update() works like a push(), so corresponding context.pop() is at
# the end of function
- context.update({var: val.resolve(context) for var, val in self.extra_context.items()})
+ context.update(
+ {var: val.resolve(context) for var, val in self.extra_context.items()}
+ )
singular, vars = self.render_token_list(self.singular)
if self.plural and self.countervar and self.counter:
count = self.counter.resolve(context)
@@ -155,8 +166,7 @@ class BlockTranslateNode(Node):
context[self.countervar] = count
plural, plural_vars = self.render_token_list(self.plural)
if message_context:
- result = translation.npgettext(message_context, singular,
- plural, count)
+ result = translation.npgettext(message_context, singular, plural, count)
else:
result = translation.ngettext(singular, plural, count)
vars.extend(plural_vars)
@@ -171,7 +181,7 @@ class BlockTranslateNode(Node):
if key in context:
val = context[key]
else:
- val = default_value % key if '%s' in default_value else default_value
+ val = default_value % key if "%s" in default_value else default_value
return render_value_in_context(val, context)
data = {v: render_value(v) for v in vars}
@@ -182,14 +192,14 @@ class BlockTranslateNode(Node):
if nested:
# Either string is malformed, or it's a bug
raise TemplateSyntaxError(
- '%r is unable to format string returned by gettext: %r '
- 'using %r' % (self.tag_name, result, data)
+ "%r is unable to format string returned by gettext: %r "
+ "using %r" % (self.tag_name, result, data)
)
with translation.override(None):
result = self.render(context, nested=True)
if self.asvar:
context[self.asvar] = result
- return ''
+ return ""
else:
return result
@@ -221,8 +231,10 @@ def do_get_available_languages(parser, token):
"""
# token.split_contents() isn't useful here because this tag doesn't accept variable as arguments
args = token.contents.split()
- if len(args) != 3 or args[1] != 'as':
- raise TemplateSyntaxError("'get_available_languages' requires 'as variable' (got %r)" % args)
+ if len(args) != 3 or args[1] != "as":
+ raise TemplateSyntaxError(
+ "'get_available_languages' requires 'as variable' (got %r)" % args
+ )
return GetAvailableLanguagesNode(args[2])
@@ -242,8 +254,10 @@ def do_get_language_info(parser, token):
{{ l.bidi|yesno:"bi-directional,uni-directional" }}
"""
args = token.split_contents()
- if len(args) != 5 or args[1] != 'for' or args[3] != 'as':
- raise TemplateSyntaxError("'%s' requires 'for string as variable' (got %r)" % (args[0], args[1:]))
+ if len(args) != 5 or args[1] != "for" or args[3] != "as":
+ raise TemplateSyntaxError(
+ "'%s' requires 'for string as variable' (got %r)" % (args[0], args[1:])
+ )
return GetLanguageInfoNode(parser.compile_filter(args[2]), args[4])
@@ -267,30 +281,32 @@ def do_get_language_info_list(parser, token):
{% endfor %}
"""
args = token.split_contents()
- if len(args) != 5 or args[1] != 'for' or args[3] != 'as':
- raise TemplateSyntaxError("'%s' requires 'for sequence as variable' (got %r)" % (args[0], args[1:]))
+ if len(args) != 5 or args[1] != "for" or args[3] != "as":
+ raise TemplateSyntaxError(
+ "'%s' requires 'for sequence as variable' (got %r)" % (args[0], args[1:])
+ )
return GetLanguageInfoListNode(parser.compile_filter(args[2]), args[4])
@register.filter
def language_name(lang_code):
- return translation.get_language_info(lang_code)['name']
+ return translation.get_language_info(lang_code)["name"]
@register.filter
def language_name_translated(lang_code):
- english_name = translation.get_language_info(lang_code)['name']
+ english_name = translation.get_language_info(lang_code)["name"]
return translation.gettext(english_name)
@register.filter
def language_name_local(lang_code):
- return translation.get_language_info(lang_code)['name_local']
+ return translation.get_language_info(lang_code)["name_local"]
@register.filter
def language_bidi(lang_code):
- return translation.get_language_info(lang_code)['bidi']
+ return translation.get_language_info(lang_code)["bidi"]
@register.tag("get_current_language")
@@ -307,8 +323,10 @@ def do_get_current_language(parser, token):
"""
# token.split_contents() isn't useful here because this tag doesn't accept variable as arguments
args = token.contents.split()
- if len(args) != 3 or args[1] != 'as':
- raise TemplateSyntaxError("'get_current_language' requires 'as variable' (got %r)" % args)
+ if len(args) != 3 or args[1] != "as":
+ raise TemplateSyntaxError(
+ "'get_current_language' requires 'as variable' (got %r)" % args
+ )
return GetCurrentLanguageNode(args[2])
@@ -327,8 +345,10 @@ def do_get_current_language_bidi(parser, token):
"""
# token.split_contents() isn't useful here because this tag doesn't accept variable as arguments
args = token.contents.split()
- if len(args) != 3 or args[1] != 'as':
- raise TemplateSyntaxError("'get_current_language_bidi' requires 'as variable' (got %r)" % args)
+ if len(args) != 3 or args[1] != "as":
+ raise TemplateSyntaxError(
+ "'get_current_language_bidi' requires 'as variable' (got %r)" % args
+ )
return GetCurrentLanguageBidiNode(args[2])
@@ -384,7 +404,7 @@ def do_translate(parser, token):
asvar = None
message_context = None
seen = set()
- invalid_context = {'as', 'noop'}
+ invalid_context = {"as", "noop"}
while remaining:
option = remaining.pop(0)
@@ -392,21 +412,23 @@ def do_translate(parser, token):
raise TemplateSyntaxError(
"The '%s' option was specified more than once." % option,
)
- elif option == 'noop':
+ elif option == "noop":
noop = True
- elif option == 'context':
+ elif option == "context":
try:
value = remaining.pop(0)
except IndexError:
raise TemplateSyntaxError(
- "No argument provided to the '%s' tag for the context option." % bits[0]
+ "No argument provided to the '%s' tag for the context option."
+ % bits[0]
)
if value in invalid_context:
raise TemplateSyntaxError(
- "Invalid argument '%s' provided to the '%s' tag for the context option" % (value, bits[0]),
+ "Invalid argument '%s' provided to the '%s' tag for the context option"
+ % (value, bits[0]),
)
message_context = parser.compile_filter(value)
- elif option == 'as':
+ elif option == "as":
try:
value = remaining.pop(0)
except IndexError:
@@ -417,8 +439,10 @@ def do_translate(parser, token):
else:
raise TemplateSyntaxError(
"Unknown argument for '%s' tag: '%s'. The only options "
- "available are 'noop', 'context' \"xxx\", and 'as VAR'." % (
- bits[0], option,
+ "available are 'noop', 'context' \"xxx\", and 'as VAR'."
+ % (
+ bits[0],
+ option,
)
)
seen.add(option)
@@ -478,19 +502,21 @@ def do_block_translate(parser, token):
option = remaining_bits.pop(0)
if option in options:
raise TemplateSyntaxError(
- 'The %r option was specified more than once.' % option
+ "The %r option was specified more than once." % option
)
- if option == 'with':
+ if option == "with":
value = token_kwargs(remaining_bits, parser, support_legacy=True)
if not value:
raise TemplateSyntaxError(
'"with" in %r tag needs at least one keyword argument.' % bits[0]
)
- elif option == 'count':
+ elif option == "count":
value = token_kwargs(remaining_bits, parser, support_legacy=True)
if len(value) != 1:
- raise TemplateSyntaxError('"count" in %r tag expected exactly '
- 'one keyword argument.' % bits[0])
+ raise TemplateSyntaxError(
+ '"count" in %r tag expected exactly '
+ "one keyword argument." % bits[0]
+ )
elif option == "context":
try:
value = remaining_bits.pop(0)
@@ -506,23 +532,25 @@ def do_block_translate(parser, token):
value = remaining_bits.pop(0)
except IndexError:
raise TemplateSyntaxError(
- "No argument provided to the '%s' tag for the asvar option." % bits[0]
+ "No argument provided to the '%s' tag for the asvar option."
+ % bits[0]
)
asvar = value
else:
- raise TemplateSyntaxError('Unknown argument for %r tag: %r.' %
- (bits[0], option))
+ raise TemplateSyntaxError(
+ "Unknown argument for %r tag: %r." % (bits[0], option)
+ )
options[option] = value
- if 'count' in options:
- countervar, counter = next(iter(options['count'].items()))
+ if "count" in options:
+ countervar, counter = next(iter(options["count"].items()))
else:
countervar, counter = None, None
- if 'context' in options:
- message_context = options['context']
+ if "context" in options:
+ message_context = options["context"]
else:
message_context = None
- extra_context = options.get('with', {})
+ extra_context = options.get("with", {})
trimmed = options.get("trimmed", False)
@@ -535,21 +563,34 @@ def do_block_translate(parser, token):
else:
break
if countervar and counter:
- if token.contents.strip() != 'plural':
- raise TemplateSyntaxError("%r doesn't allow other block tags inside it" % bits[0])
+ if token.contents.strip() != "plural":
+ raise TemplateSyntaxError(
+ "%r doesn't allow other block tags inside it" % bits[0]
+ )
while parser.tokens:
token = parser.next_token()
if token.token_type in (TokenType.VAR, TokenType.TEXT):
plural.append(token)
else:
break
- end_tag_name = 'end%s' % bits[0]
+ end_tag_name = "end%s" % bits[0]
if token.contents.strip() != end_tag_name:
- raise TemplateSyntaxError("%r doesn't allow other block tags (seen %r) inside it" % (bits[0], token.contents))
+ raise TemplateSyntaxError(
+ "%r doesn't allow other block tags (seen %r) inside it"
+ % (bits[0], token.contents)
+ )
- return BlockTranslateNode(extra_context, singular, plural, countervar,
- counter, message_context, trimmed=trimmed,
- asvar=asvar, tag_name=bits[0])
+ return BlockTranslateNode(
+ extra_context,
+ singular,
+ plural,
+ countervar,
+ counter,
+ message_context,
+ trimmed=trimmed,
+ asvar=asvar,
+ tag_name=bits[0],
+ )
@register.tag
@@ -567,6 +608,6 @@ def language(parser, token):
if len(bits) != 2:
raise TemplateSyntaxError("'%s' takes one argument (language)" % bits[0])
language = parser.compile_filter(bits[1])
- nodelist = parser.parse(('endlanguage',))
+ nodelist = parser.parse(("endlanguage",))
parser.delete_first_token()
return LanguageNode(nodelist, language)
diff --git a/django/templatetags/l10n.py b/django/templatetags/l10n.py
index 9212753286..45e9a6ac50 100644
--- a/django/templatetags/l10n.py
+++ b/django/templatetags/l10n.py
@@ -28,7 +28,7 @@ class LocalizeNode(Node):
self.use_l10n = use_l10n
def __repr__(self):
- return '<%s>' % self.__class__.__name__
+ return "<%s>" % self.__class__.__name__
def render(self, context):
old_setting = context.use_l10n
@@ -38,7 +38,7 @@ class LocalizeNode(Node):
return output
-@register.tag('localize')
+@register.tag("localize")
def localize_tag(parser, token):
"""
Force or prevents localization of values, regardless of the value of
@@ -54,10 +54,10 @@ def localize_tag(parser, token):
bits = list(token.split_contents())
if len(bits) == 1:
use_l10n = True
- elif len(bits) > 2 or bits[1] not in ('on', 'off'):
+ elif len(bits) > 2 or bits[1] not in ("on", "off"):
raise TemplateSyntaxError("%r argument should be 'on' or 'off'" % bits[0])
else:
- use_l10n = bits[1] == 'on'
- nodelist = parser.parse(('endlocalize',))
+ use_l10n = bits[1] == "on"
+ nodelist = parser.parse(("endlocalize",))
parser.delete_first_token()
return LocalizeNode(nodelist, use_l10n)
diff --git a/django/templatetags/static.py b/django/templatetags/static.py
index 4d1a05ee03..7a5147a0dd 100644
--- a/django/templatetags/static.py
+++ b/django/templatetags/static.py
@@ -9,14 +9,14 @@ register = template.Library()
class PrefixNode(template.Node):
-
def __repr__(self):
return "<PrefixNode for %r>" % self.name
def __init__(self, varname=None, name=None):
if name is None:
raise template.TemplateSyntaxError(
- "Prefix nodes must be given a name to return.")
+ "Prefix nodes must be given a name to return."
+ )
self.varname = varname
self.name = name
@@ -27,9 +27,10 @@ class PrefixNode(template.Node):
"""
# token.split_contents() isn't useful here because tags using this method don't accept variable as arguments
tokens = token.contents.split()
- if len(tokens) > 1 and tokens[1] != 'as':
+ if len(tokens) > 1 and tokens[1] != "as":
raise template.TemplateSyntaxError(
- "First argument in '%s' must be 'as'" % tokens[0])
+ "First argument in '%s' must be 'as'" % tokens[0]
+ )
if len(tokens) > 1:
varname = tokens[2]
else:
@@ -41,9 +42,9 @@ class PrefixNode(template.Node):
try:
from django.conf import settings
except ImportError:
- prefix = ''
+ prefix = ""
else:
- prefix = iri_to_uri(getattr(settings, name, ''))
+ prefix = iri_to_uri(getattr(settings, name, ""))
return prefix
def render(self, context):
@@ -51,7 +52,7 @@ class PrefixNode(template.Node):
if self.varname is None:
return prefix
context[self.varname] = prefix
- return ''
+ return ""
@register.tag
@@ -96,13 +97,14 @@ class StaticNode(template.Node):
def __init__(self, varname=None, path=None):
if path is None:
raise template.TemplateSyntaxError(
- "Static template nodes must be given a path to return.")
+ "Static template nodes must be given a path to return."
+ )
self.path = path
self.varname = varname
def __repr__(self):
return (
- f'{self.__class__.__name__}(varname={self.varname!r}, path={self.path!r})'
+ f"{self.__class__.__name__}(varname={self.varname!r}, path={self.path!r})"
)
def url(self, context):
@@ -116,12 +118,13 @@ class StaticNode(template.Node):
if self.varname is None:
return url
context[self.varname] = url
- return ''
+ return ""
@classmethod
def handle_simple(cls, path):
- if apps.is_installed('django.contrib.staticfiles'):
+ if apps.is_installed("django.contrib.staticfiles"):
from django.contrib.staticfiles.storage import staticfiles_storage
+
return staticfiles_storage.url(path)
else:
return urljoin(PrefixNode.handle_simple("STATIC_URL"), quote(path))
@@ -135,11 +138,12 @@ class StaticNode(template.Node):
if len(bits) < 2:
raise template.TemplateSyntaxError(
- "'%s' takes at least one argument (path to file)" % bits[0])
+ "'%s' takes at least one argument (path to file)" % bits[0]
+ )
path = parser.compile_filter(bits[1])
- if len(bits) >= 2 and bits[-2] == 'as':
+ if len(bits) >= 2 and bits[-2] == "as":
varname = bits[3]
else:
varname = None
@@ -147,7 +151,7 @@ class StaticNode(template.Node):
return cls(varname, path)
-@register.tag('static')
+@register.tag("static")
def do_static(parser, token):
"""
Join the given path with the STATIC_URL setting.
diff --git a/django/templatetags/tz.py b/django/templatetags/tz.py
index 489391a267..50810cece6 100644
--- a/django/templatetags/tz.py
+++ b/django/templatetags/tz.py
@@ -22,6 +22,7 @@ class UnknownTimezoneException(BaseException):
def timezone_constructor(tzname):
if settings.USE_DEPRECATED_PYTZ:
import pytz
+
try:
return pytz.timezone(tzname)
except pytz.UnknownTimeZoneError:
@@ -40,6 +41,7 @@ class datetimeobject(datetime):
# Template filters
+
@register.filter
def localtime(value):
"""
@@ -58,7 +60,7 @@ def utc(value):
return do_timezone(value, timezone.utc)
-@register.filter('timezone')
+@register.filter("timezone")
def do_timezone(value, arg):
"""
Convert a datetime to local time in a given time zone.
@@ -68,7 +70,7 @@ def do_timezone(value, arg):
Naive datetimes are assumed to be in local time in the default time zone.
"""
if not isinstance(value, datetime):
- return ''
+ return ""
# Obtain a timezone-aware datetime
try:
@@ -78,7 +80,7 @@ def do_timezone(value, arg):
# Filters must never raise exceptions, and pytz' exceptions inherit
# Exception directly, not a specific subclass. So catch everything.
except Exception:
- return ''
+ return ""
# Obtain a tzinfo instance
if isinstance(arg, tzinfo):
@@ -87,27 +89,36 @@ def do_timezone(value, arg):
try:
tz = timezone_constructor(arg)
except UnknownTimezoneException:
- return ''
+ return ""
else:
- return ''
+ return ""
result = timezone.localtime(value, tz)
# HACK: the convert_to_local_time flag will prevent
# automatic conversion of the value to local time.
- result = datetimeobject(result.year, result.month, result.day,
- result.hour, result.minute, result.second,
- result.microsecond, result.tzinfo)
+ result = datetimeobject(
+ result.year,
+ result.month,
+ result.day,
+ result.hour,
+ result.minute,
+ result.second,
+ result.microsecond,
+ result.tzinfo,
+ )
result.convert_to_local_time = False
return result
# Template tags
+
class LocalTimeNode(Node):
"""
Template node class used by ``localtime_tag``.
"""
+
def __init__(self, nodelist, use_tz):
self.nodelist = nodelist
self.use_tz = use_tz
@@ -124,6 +135,7 @@ class TimezoneNode(Node):
"""
Template node class used by ``timezone_tag``.
"""
+
def __init__(self, nodelist, tz):
self.nodelist = nodelist
self.tz = tz
@@ -138,15 +150,16 @@ class GetCurrentTimezoneNode(Node):
"""
Template node class used by ``get_current_timezone_tag``.
"""
+
def __init__(self, variable):
self.variable = variable
def render(self, context):
context[self.variable] = timezone.get_current_timezone_name()
- return ''
+ return ""
-@register.tag('localtime')
+@register.tag("localtime")
def localtime_tag(parser, token):
"""
Force or prevent conversion of datetime objects to local time,
@@ -159,17 +172,16 @@ def localtime_tag(parser, token):
bits = token.split_contents()
if len(bits) == 1:
use_tz = True
- elif len(bits) > 2 or bits[1] not in ('on', 'off'):
- raise TemplateSyntaxError("%r argument should be 'on' or 'off'" %
- bits[0])
+ elif len(bits) > 2 or bits[1] not in ("on", "off"):
+ raise TemplateSyntaxError("%r argument should be 'on' or 'off'" % bits[0])
else:
- use_tz = bits[1] == 'on'
- nodelist = parser.parse(('endlocaltime',))
+ use_tz = bits[1] == "on"
+ nodelist = parser.parse(("endlocaltime",))
parser.delete_first_token()
return LocalTimeNode(nodelist, use_tz)
-@register.tag('timezone')
+@register.tag("timezone")
def timezone_tag(parser, token):
"""
Enable a given time zone just for this block.
@@ -186,10 +198,9 @@ def timezone_tag(parser, token):
"""
bits = token.split_contents()
if len(bits) != 2:
- raise TemplateSyntaxError("'%s' takes one argument (timezone)" %
- bits[0])
+ raise TemplateSyntaxError("'%s' takes one argument (timezone)" % bits[0])
tz = parser.compile_filter(bits[1])
- nodelist = parser.parse(('endtimezone',))
+ nodelist = parser.parse(("endtimezone",))
parser.delete_first_token()
return TimezoneNode(nodelist, tz)
@@ -208,7 +219,7 @@ def get_current_timezone_tag(parser, token):
"""
# token.split_contents() isn't useful here because this tag doesn't accept variable as arguments
args = token.contents.split()
- if len(args) != 3 or args[1] != 'as':
+ if len(args) != 3 or args[1] != "as":
raise TemplateSyntaxError(
"'get_current_timezone' requires 'as variable' (got %r)" % args
)