Fixed #36658 -- Raised TemplateSyntaxError for invalid numeric litera… #19944
+131
−26
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
What's the issue?
Right now, if you write something like {% if 1.1.1 %} in a template, Django doesn't throw an error. Instead, it treats "1.1.1" as a variable name and tries to look it up in the context. This is confusing because it looks like you're trying to use a number, but it silently fails.
I ran into this while debugging a template and it took me a while to figure out what was happening. The ticket reporter had the same issue.
What does this fix?
Now when you use an invalid numeric literal (anything with multiple dots like 1.1.1, 1.2.3.4, etc.), Django will raise a TemplateSyntaxError at parse time with a clear message: "Invalid numeric literal: '1.1.1'"
Valid floats like 1.5 and scientific notation like 1e5 still work fine.
Changes
Modified Variable.init in django/template/base.py to check if a string:
If all three are true, raise TemplateSyntaxError.
Tests
Added tests for:
Also updated some existing tests in test_basic.py (basic-syntax30 through 34) that were using "1.2.3" as variable names. Those now expect TemplateSyntaxError instead.
All template tests pass (1547 tests).
Backward compatibility
This is technically a breaking change. If someone was actually using "1.2.3" as a variable name in their templates, this will break their code. But I think that's pretty unlikely - it's more likely a typo or mistake. The new behavior is more intuitive and prevents silent bugs.