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

查看:45
本文介绍了如何记录所有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?

推荐答案

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

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发布时,您还可以在异常消息发出时捕获它们。这将为您提起原始异常(表格进行更多检查):

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)

警告:使用 add_error 在Django< = 1.6中什么也不做。

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

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

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