templatetags: correct add filter (#42650)

This commit is contained in:
Nicolas Roche 2020-05-09 09:25:52 +02:00
parent cfcd6bf423
commit 6e493325d4
2 changed files with 29 additions and 2 deletions

View File

@ -465,14 +465,18 @@ def decimal(value, arg=None):
def add(term1, term2):
'''replace the "add" native django filter'''
if term1 is None:
term1 = ''
if term2 is None:
term2 = ''
term1_decimal = parse_decimal(term1, default=None)
term2_decimal = parse_decimal(term2, default=None)
if term1_decimal is not None and term2_decimal is not None:
return term1_decimal + term2_decimal
if not term1 and term2_decimal is not None:
if term1 == '' and term2_decimal is not None:
return term2_decimal
if not term2 and term1_decimal is not None:
if term2 == '' and term1_decimal is not None:
return term1_decimal
return defaultfilters.add(term1, term2)

View File

@ -567,6 +567,12 @@ def test_mathematics_templatetag():
assert tmpl.render(Context({'term1': '', 'term2': 0})) == '0'
assert tmpl.render(Context({'term1': 0, 'term2': 0})) == '0'
# if term is '' or None and other term is decimal
assert tmpl.render(Context({'term1': '', 'term2': 2.2})) == '2.2'
assert tmpl.render(Context({'term1': None, 'term2': 2.2})) == '2.2'
assert tmpl.render(Context({'term1': 2.2, 'term2': ''})) == '2.2'
assert tmpl.render(Context({'term1': 2.2, 'term2': None})) == '2.2'
# add using ',' instead of '.' decimal separator
assert tmpl.render(Context({'term1': '1,1', 'term2': '2,2'})) == '3.3'
assert tmpl.render(Context({'term1': '1,1', 'term2': '2.2'})) == '3.3'
@ -624,6 +630,23 @@ def test_mathematics_templatetag():
assert tmpl.render(Context({'term1': 2, 'term2': 3})) == '0.67'
def test_concatenation_templatetag():
tmpl = Template('{{ term1|add:term2 }}')
# fallback to Django native add filter
assert tmpl.render(Context({'term1': 'foo', 'term2': 'bar'})) == 'foobar'
assert tmpl.render(Context({'term1': 'foo', 'term2': ''})) == 'foo'
assert tmpl.render(Context({'term1': 'foo', 'term2': None})) == 'foo'
assert tmpl.render(Context({'term1': 'foo', 'term2': 0})) == ''
assert tmpl.render(Context({'term1': '', 'term2': 'bar'})) == 'bar'
assert tmpl.render(Context({'term1': '', 'term2': ''})) == ''
assert tmpl.render(Context({'term1': '', 'term2': None})) == ''
assert tmpl.render(Context({'term1': None, 'term2': 'bar'})) == 'bar'
assert tmpl.render(Context({'term1': None, 'term2': ''})) == ''
assert tmpl.render(Context({'term1': None, 'term2': None})) == ''
assert tmpl.render(Context({'term1': 0, 'term2': 'bar'})) == ''
def test_rounding_templatetag():
# ceil
tmpl = Template('{{ value|ceil }}')