在Django中的模型保存方法中提高验证错误 [英] Raise a validation error in a model's save method in Django

查看:127
本文介绍了在Django中的模型保存方法中提高验证错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道如何在模型的保存方法中正确提出验证错误,并向用户发回一条明确的消息。

I'm not sure how to properly raise a validation error in a model's save method and send back a clear message to the user.

基本上我想知道if的每个部分应该如何结束,我想提出错误
和实际保存的错误一个:

Basically I want to know how each part of the "if" should end, the one where I want to raise the error and the one where it actually saves:

def save(self, *args, **kwargs):
    if not good_enough_to_be_saved:
        raise ValidationError
    else:
        super(Model, self).save(*args, **kwargs)

然后我想知道如何发送验证错误,恰恰对用户说错了,就像Django自动返回,例如值不唯一。
我正在使用(ModelForm)并调整模型中的所有内容。

Then I want to know what to do to send a validation error that says exactly to the user what's wrong just like the one Django automatically returns if for example a value is not unique. I'm using a (ModelForm) and tune everything from the model.

推荐答案

Django管理员将无法处理保存方法中的验证错误,因此您的用户将获得500个错误。

Most Django views e.g. the Django admin will not be able to handle a validation error in the save method, so your users will get 500 errors.

您应该在模型窗体或该模型,并提出 ValidationError 那里。然后调用 save(),只有模型表单数据足够好保存。

You should do validation on the model form or on the model, and raise ValidationError there. Then call save() only if the model form data is 'good enough to save'.

这篇关于在Django中的模型保存方法中提高验证错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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