KensonMan
KensonMan

Reputation: 55

Django number_format not function

I'm trying to use the intcomma to format my number in template, but it cannot work properly.

{%load humanize%}
{%blocktrans with val=myvalue|intcomma%}The number is {{val}}{%endblocktrans%}

After some searching, I found the django.utils.formats.number_format is not function. Hereunder is my testing:

corpweb@56944bf480d1:~$ ./manage.py shell
Python 3.4.4 (default, Feb 17 2016, 02:50:56) 
[GCC 4.9.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> import locale
>>> from django.utils.formats import number_format
>>> val=123456789
>>> number_format(val,force_grouping=True)
'123456789'
>>> locale.getlocale()
('en_US', 'UTF-8')
>>> 

Is there have anything I setup wrong?

Upvotes: 0

Views: 646

Answers (2)

Gleb Denisov
Gleb Denisov

Reputation: 26

When rendering templates or using number_format outside of the Django app flow the translation module is not activated. Here are a few notes and instructions on how to turn on translation in custom management commands.

To make the shell example work we just need to activate the translation module as such:

(venv) $ ./manage.py shell
Python 3.6.4 (default, Mar  1 2018, 18:36:50)
>>> from django.utils.formats import number_format
>>> from django.utils import translation
>>> translation.activate('en-us')
>>> number_format(50000, force_grouping=True)
'50,000'

The key line above is: translation.activate('en-us')

Upvotes: 1

sehrob
sehrob

Reputation: 1044

Everything is ok with your setup I guess. Just set USE_L10N = True in your settings.py if it is set to False, as @Tim Schneider mentioned, and you better try it like this {{ val|intcomma }} as @Leonard2 mentioned and it must work. And also as it is mentioned here make sure:

To activate these filters, add 'django.contrib.humanize' to your INSTALLED_APPS setting.

Upvotes: 0

Related Questions