Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/365.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 &引用;此字段不能为空";即使字段不是空的?_Python_Django - Fatal编程技术网

Python &引用;此字段不能为空";即使字段不是空的?

Python &引用;此字段不能为空";即使字段不是空的?,python,django,Python,Django,型号。py: class Test(PolymorphicModel): title = models.CharField(max_length=300) class RestaurantForm(forms.ModelForm): class Meta: model = Test fields = [ 'title', ] def clean_title(self, *args, **kwargs):

型号。py:

class Test(PolymorphicModel):
    title = models.CharField(max_length=300)
class RestaurantForm(forms.ModelForm):
    class Meta:
        model = Test
        fields = [
            'title',
        ]
def clean_title(self, *args, **kwargs):
    title = self.cleaned_data.get("title")
    if len(title) < 3:
        raise forms.ValidationError("Please, enter at least 3 symbols!")
forms.py:

class Test(PolymorphicModel):
    title = models.CharField(max_length=300)
class RestaurantForm(forms.ModelForm):
    class Meta:
        model = Test
        fields = [
            'title',
        ]
def clean_title(self, *args, **kwargs):
    title = self.cleaned_data.get("title")
    if len(title) < 3:
        raise forms.ValidationError("Please, enter at least 3 symbols!")
class RestaurantForm(forms.ModelForm):
类元:
模型=测试
字段=[
“头衔”,
]
def clean_标题(自身、*args、**kwargs):
title=self.cleanned_data.get(“title”)
如果len(标题)<3:
raise forms.ValidationError(“请输入至少3个符号!”)

好的,当尝试提交带有文本的表单时,如“aa”,它会显示错误“请至少输入3个符号!”它工作正常,但当添加3个以上的符号时,它会返回我此字段不能为空,这来自模型,因为没有
blank=True
,但字段不是空的,我很困惑。

django的
clean\u xxx
方法期望您返回希望使用的已清除值,而在您的情况下,它是无值的。 另外,更好的方法是使用
self.add_error
,而不是引发ValidationError

您的代码应该如下所示:

def clean_标题(自):
title=自清理的_数据[“title”]
如果len(标题)<3:
self.add_错误(“标题”,“请输入至少3个符号!”)
返回标题

你忘了在
clean_title
方法中返回
标题。很好,如果我有多个字段验证,我每次都应该返回“field”吗?