Django - 如何指定验证失败的字段? [英] Django - How to specify which field a validation fails on?
本文介绍了Django - 如何指定验证失败的字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在管理页面中显示了这个模型:
class Dog(models.Model):
bark_volume = models.DecimalField(...
unladen_speed = models.DecimalField(...
def clean(self):
if self.bark_volume< 5:
raise ValidationError(must be louder!)
正如你所看到的,验证模型,但是我想要发生的是管理页面显示bark_volume字段旁边的错误,而不是现在的一般错误。有没有办法指定验证失败的字段? / p>
非常感谢提前。
解决方案
从此答案。
你必须这样做:
class Dog(models.Model) :
bark_ volume = models.DecimalField(...
unladen_speed = models.DecimalField(...
def clean_fields(self):
if self.bark_volume< 5:
raise ValidationError({'bark_volume':[Must be louder!,]})
I have this model I'm showing in the admin page:
class Dog(models.Model):
bark_volume = models.DecimalField(...
unladen_speed = models.DecimalField(...
def clean(self):
if self.bark_volume < 5:
raise ValidationError("must be louder!")
As you can see I put a validation on the model. But what I want to happen is for the admin page to show the error next to the bark_volume field instead of a general error like it is now. Is there a way to specify which field the validation is failing on?
Much thanks in advance.
解决方案
OK, I figured it out from this answer.
You have to do something like this:
class Dog(models.Model):
bark_volume = models.DecimalField(...
unladen_speed = models.DecimalField(...
def clean_fields(self):
if self.bark_volume < 5:
raise ValidationError({'bark_volume': ["Must be louder!",]})
这篇关于Django - 如何指定验证失败的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文