从自定义视图引发django管理员验证错误 [英] Raise django admin validation error from a custom view

查看:50
本文介绍了从自定义视图引发django管理员验证错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在django-admin中有一些自定义视图链接到我的change_form。
一切正常,但是现在我想从我的自定义视图中引发一个ValidationError,并因此在django-admin中获得闪存,其中打印了ValidationError的消息,这与在模型中引发它时的情况相同.clean()。

I've some custom views in django-admin linked to my change_form. All works well, but now I'd want to raise a ValidationError from my custom views and consequently get the flash in django-admin that prints the msg of ValidationError, that is the same that occurs if I raise it in model.clean().

我使用的自定义视图示例:

an example of custom view that I use:

@site.admin_view
def send_transaction_mail(request, obj_id, typ):
    order = Order.objects.get(id=obj_id)
    if typ == 'SHIPMENT':
        send_order_confirm(order)
    else:
        raise Exception("Something goes wrong sending transaction mail")
    return HttpResponseRedirect(request.META['HTTP_REFERER'])

有办法吗?谢谢

推荐答案

不确定我是否很好理解你的要求:

Not sure I understood what you want well:

您有一个视图,根据定义,该视图是公共页面。您希望它在管理页面(按定义为privates页面)中显示错误消息吗?这很奇怪。但是,如果您愿意的话。

You have a view, by definition a public page. You want it to display an error message in the admin pages (by definition privates page) ? It's odd. But if you want so.

要在管理页面中显示错误,请使用 Django消息框架。这就是在页面顶部显示带有错误/通知的黄色行的方法。

To display an error in the admin pages, use the Django Message Framework. It's what is in use to display the yellow rows with errors/notifications on the top of the pages.

from django.contrib import messages
messages.error(request, "Something goes wrong sending transaction mail");

确实,验证错误仅与表单一起显示。因此,只能在表单,表单集或字段的clean()方法中引发它们。

Indeed, validation errors an only displayed with forms. And thus, they are to be raised only in the clean() method of a form, a formset, or a field.

这篇关于从自定义视图引发django管理员验证错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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