1
0
mirror of https://github.com/django/django.git synced 2025-06-20 19:09:13 +00:00

Fixed #36465, Refs #35816 -- Disallowed '+' and '-' characters in template variable names.

Regression in 5183f7c287a9a5d61ca1103b55166cda52d9c647.

Thank you to Jon Banafato and Baptiste Mispelon for the report.
This commit is contained in:
haileyajohnson 2025-06-16 14:22:34 -07:00 committed by Sarah Boyce
parent db4d65f8be
commit 22506b2c16
3 changed files with 34 additions and 6 deletions

View File

@ -852,6 +852,13 @@ class Variable:
"Variables and attributes may "
"not begin with underscores: '%s'" % var
)
# Disallow characters that are allowed in numbers but not in a
# variable name.
for c in ["+", "-"]:
if c in var:
raise TemplateSyntaxError(
"Invalid character ('%s') in variable name: '%s'" % (c, var)
)
self.lookups = tuple(var.split(VARIABLE_ATTRIBUTE_SEPARATOR))
def resolve(self, context):

View File

@ -78,9 +78,6 @@ class VariableTests(SimpleTestCase):
def test_nonliterals(self):
"""Variable names that aren't resolved as literals."""
var_names = []
for var in ("inf", "infinity", "iNFiniTy", "nan"):
var_names.extend((var, "-" + var, "+" + var))
for var in var_names:
for var in ["inf", "infinity", "iNFiniTy", "nan"]:
with self.subTest(var=var):
self.assertIsNone(Variable(var).literal)

View File

@ -126,6 +126,16 @@ class ParserTests(SimpleTestCase):
):
Variable({})
# Variables should raise when invalid characters in name.
for c in ["+", "-"]:
with self.subTest(invalid_character=c):
variable_name = f"variable{c}name"
with self.assertRaisesMessage(
TemplateSyntaxError,
f"Invalid character ('{c}') in variable name: '{variable_name}'",
):
Variable(variable_name)
def test_filter_args_count(self):
parser = Parser("")
register = Library()
@ -174,6 +184,7 @@ class ParserTests(SimpleTestCase):
def test_filter_numeric_argument_parsing(self):
p = Parser("", builtins=[filter_library])
# Values that resolve to a numeric literal.
cases = {
"5": 5,
"-5": -5,
@ -193,6 +204,7 @@ class ParserTests(SimpleTestCase):
FilterExpression(f"0|default:{num}", p).resolve({}), expected
)
# Values that are interpreted as names of variables that do not exist.
invalid_numbers = [
"abc123",
"123abc",
@ -205,8 +217,6 @@ class ParserTests(SimpleTestCase):
"1e2.0",
"1e2a",
"1e2e3",
"1e-",
"1e-a",
]
for num in invalid_numbers:
@ -216,3 +226,17 @@ class ParserTests(SimpleTestCase):
)
with self.assertRaises(VariableDoesNotExist):
FilterExpression(f"0|default:{num}", p).resolve({})
# Values that are interpreted as an invalid variable name.
invalid_numbers_and_var_names = [
"1e-",
"1e-a",
"1+1",
"1-1",
]
for num in invalid_numbers_and_var_names:
with self.subTest(num=num):
with self.assertRaises(TemplateSyntaxError):
FilterExpression(num, p).resolve({})
with self.assertRaises(TemplateSyntaxError):
FilterExpression(f"0|default:{num}", p).resolve({})