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

3

I have the following class:

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

And their respective form:

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

When you print the form in the template an input of type number is appearing:

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

The question is how do I allow this field to accept semicolon values? Currently accepting only the decimal separation (ex: 1253,00), I would like you to accept the separation of the thousands using dot (ex: 1,253.00). What is the correct solution for this case? The idea is in the input the value come in the currency format (1,253.00) and in the database store as normal decimal (1253.00).

    
asked by anonymous 03.04.2015 / 19:01

2 answers

2

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

What worked for me was the following:

settings.py

DECIMAL_SEPARATOR = ','
USE_THOUSAND_SEPARATOR = True

Function __ init __ of form

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