"This field cannot be blank"即使字段不为空?



>models.py:

class Test(PolymorphicModel):
title = models.CharField(max_length=300)

forms.py:

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!")

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

Django 的clean_xxx方法希望你返回你要使用的清理值,在你的例子中它是 None。 此外,更好的方法是使用self.add_error而不是引发验证错误。

您的代码应如下所示:

def clean_title(self):
title = self.cleaned_data["title"]
if len(title) < 3:
self.add_error("title", "Please, enter at least 3 symbols!")
return title

相关内容

最新更新