我想在 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 中执行此操作,而不是在保存
To assign exceptions to a specific field, instantiate the ValidationError with a dictionary, where the keys are the field names. We could update the previous example to assign the error to the pub_date field:
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 admin 输入错误后出现错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27450005/