dragonroot
dragonroot

Reputation: 5841

Applying str() explicitly vs allowing Django to do it itself yields different results in templates

Given a template {{ foo }} {{ bar }} and a context {'foo': Decimal('12.34'), 'bar': str(Decimal('12.34'))}, the template renders as 12,34 12.34. Why are the results different?

Upvotes: 2

Views: 28

Answers (2)

Matt
Matt

Reputation: 10362

That would be Django doing format localization for you. You can disable it by setting USE_L10N to False within your settings.

For your particular problem you could set the DECIMAL_SEPARATOR setting to a a dot instead of a comma, so in your settings it would be:

DECIMAL_SEPARATOR = '.'

Upvotes: 1

Maxime Lorant
Maxime Lorant

Reputation: 36181

Because foo is a number (Decimal type) and is formatted according to the current localization of your application. In the language you set, the decimal separator is a comma.

On the other side, bar is a string, formatted by Python. When you apply str to a Decimal, the string representation does not take into account the localization of the Django project (because it is a Python methods and not related to Django) and returns the common "English" format, with a dot.

Django can apply format localization only on numeric objects (and also dates and times and other minors things), not plain string. It would be too heavy to analyse each string to check if there is a number and if it needs to be formatted...

More information about Django localization in the official documentation.

Upvotes: 2

Related Questions