luzik
luzik

Reputation: 703

django templates decimal separator with safe tag

view.py

def a(request)
  a=3.222
  c=1.555
  if a>5:
    b='<h1>%0.3f</h1>' % (a)
  else
    b='%0.3f' % (a)
  content={'a':b, 'c':c}
  return render(request, 'a.html', context)

a.html

{{ a|safe }}
{{ c }}

In PL loc. decimal separator is ',' C value is printed as 1,555 - nice, but b is printed as 3.222 because of using safe which i have to use because of html tags. How can i make all float values separated with ',' ?

Upvotes: 0

Views: 715

Answers (1)

Ludwik Trammer
Ludwik Trammer

Reputation: 25062

I don't think you problem is in any way connected to using safe. It's just a case of python string formating (that you use in your view) not being location-aware. You could try using locale.format() instead, which is intended as a locale-aware alternative.

But it is not a good practice to put HTML into your views anyway. So I would move formating logic to your template:

view.py

def a(request)
  a=3.222
  c=1.555
  content={'a':b, 'c':c}
  return render(request, 'a.html', context)

a.html

{% if a>5 %}
    <b>{{ a }}</b>
{% else %}
    {{ a }}
{% endif %}

{{ c }}

Upvotes: 1

Related Questions