Skip to content

Conversation

segnimekonnen7
Copy link

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:

  • Starts with a digit
  • Has more than one dot
  • Couldn't be parsed as a float

If all three are true, raise TemplateSyntaxError.

Tests

Added tests for:

  • Invalid cases: 1.1.1, 1.2.3.4, 10.20.30
  • Valid cases: 1.1, 1.0, 0.0, 1e5
  • Both in {% if %} tags and Variable class directly

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.

…ls in templates.

Invalid numeric literals with multiple dots (e.g., '1.1.1', '1.2.3.4') are now
properly rejected during template parsing instead of being silently treated as
variable names. This prevents confusing behavior where strings that look like
malformed numbers are used as variables.

Updated existing tests that relied on the old behavior to reflect the new,
more intuitive behavior.
Copy link

Hello! Thank you for your contribution 💪

As it's your first contribution be sure to check out the patch review checklist.

If you're fixing a ticket from Trac make sure to set the "Has patch" flag and include a link to this PR in the ticket!

If you have any design or process questions then you can ask in the Django forum.

Welcome aboard ⛵️!

@segnimekonnen7 segnimekonnen7 force-pushed the fix-36658-invalid-numeric-literals branch from e72d031 to 8cc39ed Compare October 12, 2025 13:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant