首页 > 解决方案 > "This field cannot be blank" even if the field is not empty?

问题描述

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

Okay, when try to submit the form with text, like "aa" it shows error "Please, enter at least 3 symbols!" it works fine, but when add more than 3 symbols it returns me This field cannot be blank which comes from Model, because there is no blank=True, but field is not empty, I'm confused.

标签: pythondjango

解决方案


django 的clean_xxx方法希望您返回要使用的清理值,在您的情况下它是无。此外,更好的方法是使用self.add_error而不是引发 ValidationError。

您的代码应如下所示:

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

推荐阅读