python 从 django 模型的保存方法中引发 ValidationError?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1473888/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 22:21:07  来源:igfitidea点击:

Raising ValidationError from django model's save method?

pythondjango

提问by slypete

I need to raise an exception in a model's save method. I'm hoping that an exception exists that will be caught by any django ModelFormthat uses this model including the admin forms.

我需要在模型的保存方法中引发异常。我希望存在一个异常,该异常将被ModelForm使用此模型的任何 django 捕获,包括管理表单。

I tried raising django.forms.ValidationError, but this seems to be uncaught by the admin forms. The model makes a remote procedure call at save time, and it's not known until this call if the input is valid.

我尝试提高django.forms.ValidationError,但这似乎没有被管理表单捕获。该模型在保存时进行远程过程调用,直到此调用才知道输入是否有效。

Thanks, Pete

谢谢,皮特

采纳答案by Daniel Roseman

There's currently no way of performing validation in model save methods. This is however being developed, as a separate model-validation branch, and should be merged into trunk in the next few months.

目前无法在模型保存方法中执行验证。然而,这是作为一个单独的模型验证分支开发的,应该在接下来的几个月内合并到主干中。

In the meantime, you need to do the validation at the form level. It's quite simple to create a ModelFormsubclass with a clean()method which does your remote call and raises the exception accordingly, and use this both in the admin and as the basis for your other forms.

同时,您需要在表单级别进行验证。创建一个ModelForm带有clean()方法的子类非常简单,该方法执行您的远程调用并相应地引发异常,并在管理中使用它并作为其他表单的基础。

回答by Cerin

Since Django 1.2, this is what I've been doing:

从 Django 1.2 开始,这就是我一直在做的事情:

class MyModel(models.Model):

    <...model fields...>

    def clean(self, *args, **kwargs):
        if <some constraint not met>:
            raise ValidationError('You have not met a constraint!')
        super(MyModel, self).clean(*args, **kwargs)

    def full_clean(self, *args, **kwargs):
        return self.clean(*args, **kwargs)

    def save(self, *args, **kwargs):
        self.full_clean()
        super(MyModel, self).save(*args, **kwargs)

This has the benefit of working both inside and outside of admin.

这有利于在管理员内部和外部工作。