Django - 如何指定验证失败的字段? [英] Django - How to specify which field a validation fails on?

查看:18
本文介绍了Django - 如何指定验证失败的字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在管理页面中显示了这个模型:

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

如您所见,我对模型进行了验证.但我希望管理页面在 bark_volume 字段旁边显示错误,而不是像现在这样的一般错误.有没有办法指定验证失败的字段?

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?

非常感谢.

推荐答案

好的,我想通了 来自这个答案.

你必须这样做:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆