Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 带有clean的Django验证不起作用_Python_Django - Fatal编程技术网

Python 带有clean的Django验证不起作用

Python 带有clean的Django验证不起作用,python,django,Python,Django,我的视图.py class AccountListView(ListView): context_object_name = 'accounts' model = models.Account class AccountCreateView(CreateView): fields = ('foo', 'bar') model = models.Account class AccountForm(forms.ModelForm): foo = forms

我的
视图.py

class AccountListView(ListView):
    context_object_name = 'accounts'
    model = models.Account

class AccountCreateView(CreateView):
    fields = ('foo', 'bar')
    model = models.Account
class AccountForm(forms.ModelForm):
    foo = forms.ModelDecimalField()
    bar = forms.ModelDateField()

    def clean_foo(self):
        foo_passed = self.cleaned_data.get("foo")
        if foo_passed > 1000:
            raise forms.ValidationError("Sorry, Maximum is 1000.")
        return foo_passed
我的
forms.py

class AccountListView(ListView):
    context_object_name = 'accounts'
    model = models.Account

class AccountCreateView(CreateView):
    fields = ('foo', 'bar')
    model = models.Account
class AccountForm(forms.ModelForm):
    foo = forms.ModelDecimalField()
    bar = forms.ModelDateField()

    def clean_foo(self):
        foo_passed = self.cleaned_data.get("foo")
        if foo_passed > 1000:
            raise forms.ValidationError("Sorry, Maximum is 1000.")
        return foo_passed
我的
template.html

{{form.as_p}}

在我上面的代码中,我正在尝试验证输入,如果值大于1000,则会引发错误。但是它不起作用,我错过了什么。

您需要告诉视图使用表单类:

class AccountCreateView(CreateView):
    fields = ('foo', 'bar')
    model = models.Account
    form_class = AccountForm

您需要告诉视图使用表单类:

class AccountCreateView(CreateView):
    fields = ('foo', 'bar')
    model = models.Account
    form_class = AccountForm

请显示视图。什么是ModelDecimalField和ModelDateField?@Alasdair更新了我的view@DanielRoseman在我的模型上,这个字段名为foo-barIt's-ok。创建一个简化的示例,而不是显示实际代码,这通常可以使问题更容易理解。但是您应该确保示例代码有效。Django没有
表单.ModelDecimalField
表单.ModelDateField
,因此,这让问题变得扑朔迷离。请显示视图。ModelDecimalField和ModelDateField是什么?@Alasdair更新了我的view@DanielRoseman在我的模型上,这个字段名为foo-barIt's-ok。创建一个简化的示例,而不是显示实际代码,这通常可以使问题更容易理解。但是您应该确保示例代码有效。Django没有
forms.ModelDecimalField
forms.ModelDateField
,因此它使问题变得混乱。