我想在django admin中添加对输入数据的验证,所以我已经将这样的代码添加到了我的models.py
class Score(models.Model):
#fields description
def save(self, *args, **kw):
if (validating data):
super(Score, self).save(*args, **kw)
else:
raise forms.ValidationError("Error input")
我不明白自己要在
ValidationError
中写什么才能看到此消息。 最佳答案
您应该在proper place中而不是在save
中执行此操作
要将例外分配给特定字段,请实例化
带字典的ValidationError,其中的键是字段名称。
我们可以更新前面的示例,将错误分配给
pub_date字段:
class Article(models.Model):
...
def clean(self):
# Don't allow draft entries to have a pub_date.
if self.status == 'draft' and self.pub_date is not None:
raise ValidationError({'pub_date': 'Draft entries may not have a publication date.'})
...
关于python - 在Django管理员中输入错误后出现错误消息,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27450005/