Jorge Arévalo
Jorge Arévalo

Reputation: 3008

Transform a locale-aware unicode string in a valid Decimal number in Python/Django

In my Django 1.7.11 app, I get data formatted with a spanish locale via HTTP. So, in my view, I get a unicode string representing a decimal number in spanish locale:

spanish_number = request.GET.get('some_post_value', 0)
# spanish_number may be u'12,542' now, for example. And may come via POST. This is not important. Just the value itself is important: it contains commas as decimal separator.

And I want to store that in a Django Model's field of type DecimalField:

class MyModel(models.Model):
    my_number = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True)

In my settings.py, I have

USE_L10N=True
USE_I18N=True

If I try something like

m = MyModel()
m.my_number = spanish_number # This is, u'12,542'
m.save()

It fails with a ValidationError because

u'12,542' must be a decimal number

What would be the right way to deal with this? I mean, with the fact that my application is going to receive numbers (and dates...) formatted this way (spanish locale)

P.S.: I know Django has a DecimalField for forms, with a localize=True option, but I'm directly dealing with Models, not with Forms.

Upvotes: 0

Views: 327

Answers (1)

Peter DeGlopper
Peter DeGlopper

Reputation: 37344

You're on the right track looking at form DecimalField. If you check its source, you'll see that when set to localize it runs the string through formats.sanitize_separators. You can call this directly to convert to the format Decimal() expects:

import django.utils.formats
m.my_number = formats.sanitize_separators(spanish_number)

Upvotes: 2

Related Questions