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

查看:27
本文介绍了在 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 视图,例如Django 管理员将无法处理 save 方法中的验证错误,因此您的用户将收到 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天全站免登陆