How to allow a Decimalfield with the BR currency format in Django?

Asked

Viewed 2,875 times

3

I have the following class:

class Carro(models.Model):    
    valor = models.DecimalField(max_digits=8, decimal_places=2, default=0)

And its respective form:

class CarroForm(forms.ModelForm):
    class Meta():
        model = Carro
        fields = ['valor']

When printing the form in the template one appears input of the kind number:

<input id="id_valor" name="valor" step="0.01" type="number" value="0">

The question is how to allow this field to accept point and comma values? Currently only accepting decimal separation (ex: 1253.00), I would like you to accept separation from thousands using point (ex: 1.253,00). What is the correct solution for this case? The idea is in the input the value come in currency format (1.253,00) and in the bank store as normal decimal (1253.00).

2 answers

2


To accept point in the thousand separation just put localize=True in the field, in the template Django will print the input guy text:

class CarroForm(forms.ModelForm):
    valor = forms.DecimalField(max_digits=8, decimal_places=2, localize=True)
    class Meta():
        model = Carro
        fields = ['valor']

1

What worked for me was this:

py Settings.

DECIMAL_SEPARATOR = ','
USE_THOUSAND_SEPARATOR = True

Function __init__ form

def __init__(self, *args, **kwargs):
    super(SeuForm, self).__init__(*args, **kwargs)
    self.fields['campo'].localize = True
    self.fields['campo'].widget.is_localized = True

Browser other questions tagged

You are not signed in. Login or sign up in order to post.