Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems trying to format currency with Python (Django)

Tags:

I have the following code in Django:

import locale  locale.setlocale( locale.LC_ALL, '' )  def format_currency(i):     return locale.currency(float(i), grouping=True) 

It work on some computers in dev mode, but as soon as I try to deploy it on production I get this error:

Exception Type: TemplateSyntaxError Exception Value: Caught ValueError while rendering: Currency formatting is not possible using the 'C' locale. Exception Location: /usr/lib/python2.6/locale.py in currency, line 240 

The weird thing is that I can do this on the production server and it will work without any errors:

python manage.py shell >>> import locale  >>> locale.setlocale( locale.LC_ALL, '' ) 'en_CA.UTF-8' >>> locale.currency(1, grouping=True) '$1.00' 

I .. don't get it.i

like image 455
h3. Avatar asked Jun 01 '10 19:06

h3.


People also ask

How do you format currency in Python?

To format numbers as currency in Python, the easiest way is with the locale module. You can also use the string format() function. Finally, you can use the babel. numbers module to format numbers as money and currency.

What is format in Django?

Django's formatting system is capable of displaying dates, times and numbers in templates using the format specified for the current locale. It also handles localized input in forms.


1 Answers

On the production server, try

locale.setlocale( locale.LC_ALL, 'en_CA.UTF-8' ) 

instead of

locale.setlocale( locale.LC_ALL, '' ) 

When you use '', the locale is set to the user's default (usually specified by the LANG environment variable). On the production server, that appears to be 'C', while as a test user it appears to be 'en_CA.UTF-8'.

like image 136
unutbu Avatar answered Sep 28 '22 07:09

unutbu