简体   繁体   English

Django Model Form验证失败用于FloatField

[英]Django Model Form validation failing for FloatField

I have a model form; 我有一个模特表格; having a field cost . 有现场cost I am using jquery number on that field that appends commas when the value exceeds 999. eg 我在该字段上使用jquery number ,当值超过999时会追加逗号。例如

Changes 1234 to 1,234

When the user submits the form; 用户提交表单时; the data is not validated. 数据未经验证。 I try to catch in Clean method, but this value does not exist in self.cleaned_data. 我尝试捕获Clean方法,但是self.cleaned_data中不存在此值。 I also tried to extract that value from the self.data and convert it to 1234 float and append to self.cleaned_data and return. 我还尝试从self.data中提取该值,并将其转换为1234 float,然后追加到self.cleaned_data并返回。 but that didn't work too. 但这也不起作用。

Please let me konw. 请让我知道。

Cost: Enter a number.

What am i missing? 我想念什么?

https://docs.djangoproject.com/en/1.7/topics/i18n/formatting/ https://docs.djangoproject.com/en/1.7/topics/i18n/formatting/

First, set proper locale: settings.USE_I18N, settings.USE_L10N, settings.LANGUAGE_CODE, settings.USE_THOUSAND_SEPARATOR 首先,设置适当的语言环境:settings.USE_I18N,settings.USE_L10N,settings.LANGUAGE_CODE,settings.USE_THOUSAND_SEPARATOR

Second, set widget to be localized: 其次,将小部件设置为本地化:

class MyForm(forms.ModelForm):
       ...
       def __init__(self, *args, **kwargs):
           super(MyForm, self).__init__(*args, **kwargs)
           self.fields['cost'].localize = True
           self.fields['cost'].widget.is_localized = True

if you are using forms.Form instead of modelform, then you only need to pass localize=True argument to your field definition 如果您使用forms.Form而不是forms.Form ,则只需将localize=True参数传递给字段定义

Edit: while FormField(localize=True) and therefore form.fileds['fieldname'].localize = True is documented, widget.is_localized is not documented and I've taken this directly from django code . 编辑:虽然有FormField(localize=True)并因此有form.fileds['fieldname'].localize = True的文档, widget.is_localized没有widget.is_localized的文档,我直接从django代码中获取了它 So potentially behaviour may chage in next django versions and so prefered way is using FormField(localize=True) 因此,潜在的行为可能会在下一个Django版本中发生变化,因此首选方式是使用FormField(localize=True)

Python can't convert "1,234" string to float. Python无法将“ 1,234”字符串转换为浮点型。

>>> float("1,234")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for float(): 1,234
>>> 

You can sanitize this data in the form's __init__ method: 您可以使用表单的__init__方法清除此数据:

class MyForm(forms.Form):
    def __init__(self, data=None, *args, **kwargs)
        if data and 'cost' in data:
            data['cost'] = data['cost'].replace(',', '')
        super(MyForm, self).__init__(data, *args, **kwargs)

You can just override the default field like this: 您可以像这样覆盖默认字段:

class MyForm(forms.ModelForm):
    cost = forms.CharField()

    def clean_cost(self):
        data = self.cleaned_data['cost']
        return float(data.replace(',', ''))

    class Meta:
       model = MyModel
       field = {'cost', ...}

Detailed documentation is here: https://docs.djangoproject.com/en/1.7/topics/forms/modelforms/#overriding-the-default-fields 详细的文档在这里: https : //docs.djangoproject.com/en/1.7/topics/forms/modelforms/#overriding-the-default-fields

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM