我可以显示/设置Django DecimalFields所需的十进制分隔符吗?

时间:2022-02-08 16:32:25

I’ve got the following form in Django:

我在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:

我的设置。py包含:

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. 是否有办法手动显示/设置表单的“值”字段的小数分隔符?
  3. How can I get an overwiev of my locale settings?
  4. 如何获得语言环境设置的权限?
  5. Is there any way to change locale settings on the fly?
  6. 有什么方法可以动态地更改语言环境设置吗?

* EDIT *: I Tried to add to MyForm:

*编辑*:我尝试添加到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

2 个解决方案

#1


2  

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.

这有点复杂,但我认为这是可行的。

#2


0  

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

django shell/ ipython shell似乎有一个错误,这就是它不能工作的原因。我把它搬到了这个岗位上。

python django shell (ipython) unexpected behavior or bug?

python django shell (ipython)意外行为或错误?

#1


2  

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.

这有点复杂,但我认为这是可行的。

#2


0  

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

django shell/ ipython shell似乎有一个错误,这就是它不能工作的原因。我把它搬到了这个岗位上。

python django shell (ipython) unexpected behavior or bug?

python django shell (ipython)意外行为或错误?