如何记录所有 Django 表单验证错误? [英] How to log all Django form validation errors?

查看:17
本文介绍了如何记录所有 Django 表单验证错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 Django 应用程序中,我有一个 forms.py 文件,我在其中定义了与表单输入屏幕相对应的类负载.这些类中的每一个都在该属性/字段特定的 _clean() 函数或表单类的整体 clean() 函数中进行一些验证.如果在这些 clean() 函数中的任何一个中验证失败,我会引发如下错误:

In my Django application, I have a forms.py file in which I define loads of classes corresponding to form input screens. Each of these classes does some validation either in that attribute/field specific _clean() functions or in the overall clean() function for the form class. If validation fails in any of these clean() functions, I raise an error like this:

raise forms.ValidationError('Invalid value dude!!')                

当出现此类错误时,应用程序会捕获错误并将其显示在表单上供用户使用.

When such an error is raised, the application catches the error and displays it on the form for the user.

我还在这个文件的顶部定义了一个记录器,如下所示:

I also have a logger defined at the top of this file like this:

import logging
logger = logging.getLogger(__name__)

现在,除了向用户报告 ValidationErrors 之外,我还想捕获它们并将它们记录为错误.是否有一些通用且优雅的方法可以让记录器记录所有此类错误,而无需更改影响应用程序用户的任何其他行为?

Now, in addition to reporting to the user the ValidationErrors, I would like to catch them and log them as errors. Is there some generic and elegant way I can get the logger to log all such errors without changing any other behavior that affects the application's user?

推荐答案

您可以扩展您的 Forms 以在验证结束后立即记录错误:

You can extend your Forms to log the errors as soon as the validation ends:

class LoggingMixin(object):
    def full_clean(self):
        super(LoggingMixin, self).full_clean()
        for field, errors in self.errors.iteritems():
            logger.info('Form error in %s: %s', ', '.join(errors))

然后使用日志混合定义你的表单:

Then define your forms using the logging mixin:

class MyForm(LoggingMixin, forms.Form):
    ...

当 Django 1.7 发布时,您还可以在异常消息出现时捕获它们.这将为您提供已引发的原始异常(Form 进行更多检查):

When Django 1.7 is out, you will also be able to catch the exceptions messages as they are raised. This will give you the raw exceptions as they have been raised (the Form does some more checking):

class LoggingMixin(object):
    def add_error(self, field, error):
        if field:
            logger.info('Form error on field %s: %s', field, error)
        else:
            logger.info('Form error: %s', error)
        super(LoggingMixin, self).add_error(field, error)

警告:在 Django <= 1.6 中使用 add_error 将没有任何作用.

WARNING: Using add_error will do nothing in Django <= 1.6.

这篇关于如何记录所有 Django 表单验证错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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