如果Django管理中的字段为空,我想显示错误消息。目前,我知道如何在页面的早期引入ValidationError,但我需要在空白字段正上方显示消息。怎么办呢?
尚未找到答案。
class Article(models.Model):
...
title_ru = models.CharField(max_length=255, blank=True)
...
class ArticleAdmin(admin.ModelAdmin):
class form(forms.ModelForm):
class Meta:
model = models.Article
def clean(self):
cleaned_data = super(forms.ModelForm, self).clean()
title_ru = cleaned_data['title_ru']
if not title_ru:
raise forms.ValidationError("Title ru")
return self.cleaned_data
forms.ValidationError("Title ru")
会在页面顶部显示一条消息,但我需要在该字段上显示此消息
如何通过Title_ru字段获取消息?
答案 0 :(得分:2)
由于您在ValidationError
方法中引发了clean
,因此您会在页面顶部看到错误消息。提高clean_title_ru
中的验证错误
def clean_title_ru(self):
title_ru = self.cleaned_data['title_ru']
if not title_ru:
raise forms.ValidationError("Title ru")
return self.cleaned_data['title_ru']
答案 1 :(得分:0)
最好的方法是检查clean_title_ru中的值,但是如果要检查多个值,可以采用以下方式执行:
def clean(self):
cleaned_data = super(forms.ModelForm, self).clean()
title_ru = cleaned_data['title_ru']
if not title_ru:
msg = u"error in Title ru"
self._errors["title_ru"] = self.error_class([msg])
# These fields are no longer valid. Remove them from the cleaned data.
del cleaned_data["title_ru"]
return self.cleaned_data