Opened 5 hours ago

Last modified 5 hours ago

#35816 new Uncategorized

Django Template Language doesn't support all float literals

Reported by: Lily Foote Owned by:
Component: Uncategorized Version: 5.1
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

When parsing arguments to filters, Django converts numeric literals to float or int, but in the case of scientific notation for float this is incomplete:

>>> from django.template.base import Template
>>> from django.template.engine import Engine
>>> 5.2e3
5200.0
>>> Template("{{ foo|default:5.2e3 }}", engine=e)
<Template template_string="{{ foo|default:5.2e3...">
>>> 5.2e-3
0.0052
>>> Template("{{ foo|default:5.2e-3 }}", engine=e)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/lily/.local/share/lilyenv/virtualenvs/django-rusty-templates/3.12/lib/python3.12/site-packages/django/template/base.py", line 154, in __init__
    self.nodelist = self.compile_nodelist()
                    ^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/lily/.local/share/lilyenv/virtualenvs/django-rusty-templates/3.12/lib/python3.12/site-packages/django/template/base.py", line 196, in compile_nodelist
    nodelist = parser.parse()
               ^^^^^^^^^^^^^^
  File "/home/lily/.local/share/lilyenv/virtualenvs/django-rusty-templates/3.12/lib/python3.12/site-packages/django/template/base.py", line 489, in parse
    raise self.error(token, e)
  File "/home/lily/.local/share/lilyenv/virtualenvs/django-rusty-templates/3.12/lib/python3.12/site-packages/django/template/base.py", line 487, in parse
    filter_expression = self.compile_filter(token.contents)
                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/lily/.local/share/lilyenv/virtualenvs/django-rusty-templates/3.12/lib/python3.12/site-packages/django/template/base.py", line 605, in compile_filter
    return FilterExpression(token, self)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/lily/.local/share/lilyenv/virtualenvs/django-rusty-templates/3.12/lib/python3.12/site-packages/django/template/base.py", line 706, in __init__
    raise TemplateSyntaxError(
django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '-3' from 'foo|default:5.2e-3'

I couldn't actually find the documentation for Django's handling of numeric literals in templates, so this may be an undocumented implementation detail. If so, perhaps deprecating scientific notation would be appropriate. Otherwise, we should support this case.

Change History (1)

comment:1 by Lily Foote, 5 hours ago

Version: 5.05.1
Note: See TracTickets for help on using tickets.
Back to Top