ProfHase85
ProfHase85

Reputation: 12183

Can I show/set the decimal separator required by Django DecimalFields?

I’ve got the following form in Django:

class MyForm(forms.ModelForm):
    val = forms.DecimalField(localize=True)
    class Meta:
        model = MyModel

with the following model:

class MyModel(models.Model):
    val = models.DecimalField("Betrag", max_digits=11, decimal_places=2)

My settings.py contains:

LANGUAGE_CODE = 'de-de'
USE_I18N = True
USE_L10N = True
DECIMAL_SEPARATOR=','

When evaluating the form in the following way I am getting errors:

form = MyForm({'val':'10,5'})
form['val'].errors 
# [u'Enter a number.']
form['val'].value()
# '10,5'

Of course I do not get any validation errors if I use '.' as decimal separator.

  1. Is there any way to show/set the decimal separator for the 'value' field of the form manually?
  2. How can I get an overwiev of my locale settings?
  3. Is there any way to change locale settings on the fly?

* EDIT *: I Tried to add to MyForm:

def __init__(self,*args,**kwargs):
    super(MyForm,self).__init__(*args,**kwargs)
    self.fields['val'].localize=True
    if __debug__:
        print self.fields['val'].localize
        print ("Separator: "+settings.DECIMAL_SEPARATOR)
        print ("Language: " +settings.LANGUAGE_CODE)

When executing I am getting:

#True
#Separator: ,
#Language: de-de

Upvotes: 2

Views: 2078

Answers (2)

ProfHase85
ProfHase85

Reputation: 12183

There seems to be an error with django shell/ ipython shell, that is why it did not work. I moved it to this post

python django shell (ipython) unexpected behavior or bug?

Upvotes: 0

Paulo Bu
Paulo Bu

Reputation: 29794

Define the form class like this:

class MyForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(TestForm, self).__init__(*args, **kwargs)
        self.fields['val'].localize=True

    class Meta:
        model = MyModel

Is a little complicated but I think that should work.

Upvotes: 2

Related Questions