显示Django管理员网站中的自定义模型验证异常 [英] Showing custom model validation exceptions in the Django admin site

查看:176
本文介绍了显示Django管理员网站中的自定义模型验证异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个预订模型,需要检查是否可以预订的物品。我想要弄清楚这个项目是否可用于集中式的逻辑,以便无论我在哪里保存实例,代码都可以保存。

I have a booking model that needs to check if the item being booked out is available. I would like to have the logic behind figuring out if the item is available centralised so that no matter where I save the instance this code validates that it can be saved.

在我的模型类的自定义保存功能中我有这个代码的时刻:

At the moment I have this code in a custom save function of my model class:

def save(self):
    if self.is_available(): # my custom check availability function
        super(MyObj, self).save()
    else:
        # this is the bit I'm stuck with..
        raise forms.ValidationError('Item already booked for those dates')

如果项目不可用,并且我的项目未保存,则会出现错误。我可以从我的前端表单代码捕获异常,但Django管理员网站呢?如何让我的异常像管理网站中的任何其他验证错误一样显示?

This works fine - the error is raised if the item is unavailable, and my item is not saved. I can capture the exception from my front end form code, but what about the Django admin site? How can I get my exception to be displayed like any other validation error in the admin site?

推荐答案

在django 1.2中,模型验证已经添加。

In django 1.2, model validation has been added.

现在,您可以在模型中添加一个干净的方法,这会引发ValidationError异常,并且在使用django管理时将自动调用它。

You can now add a "clean" method to your models which raise ValidationError exceptions, and it will be called automatically when using the django admin.

(在文档中不太清楚,干净的方法是由管理员调用的,但我已经在这里进行了验证)

(It's not very clear in the documentation that the clean method is called by the admin, but I've verified it here)

http:// docs.djangoproject.com/en/dev/ref/models/instances/?from=olddocs#validating-objects

所以你的干净的方法可能是一些东西像这样:

So your clean method could be something like this:

from django.core.exceptions import ValidationError

class MyModel(models.Model):

    def is_available(self):
        #do check here
        return result

    def clean(self):
        if not self.is_available():
            raise ValidationError('Item already booked for those dates')

我没有广泛使用它,但是似乎比创建一个ModelForm的代码要少得多,然后将该表单链接到admin.py文件中,用于django admin。

I haven't made use of it extensively, but seems like much less code than having to create a ModelForm, and then link that form in the admin.py file for use in django admin.

这篇关于显示Django管理员网站中的自定义模型验证异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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