Transform a locale-aware unicode string in a valid Decimal number in Python/Django
<p>In my <strong>Django 1.7.11</strong> 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:</p>

<pre><code>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.
</code></pre>

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

<pre><code>class MyModel(models.Model):
    my_number = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True)
</code></pre>

<p>In my settings.py, I have </p>

<pre><code>USE_L10N=True
USE_I18N=True
</code></pre>

<p>If I try something like</p>

<pre><code>m = MyModel()
m.my_number = spanish_number # This is, u'12,542'
m.save()
</code></pre>

<p>It fails with a ValidationError because </p>

<pre><code>u'12,542' must be a decimal number
</code></pre>

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

<p>P.S.: I know Django has a <a href="https://docs.djangoproject.com/en/1.7/ref/forms/fields/#decimalfield" rel="nofollow">DecimalField</a> for forms, with a localize=True option, but I'm directly dealing with Models, not with Forms. </p>

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

<pre><code>import django.utils.formats
m.my_number = formats.sanitize_separators(spanish_number)
</code></pre>

python django unicode localization