How to log all Django form validation errors?

In my Django application, I have a forms.py file in which I define the loads of classes corresponding to the form input screens. Each of these classes does some testing both in the _clean () functions for the attribute / field, and in the general clean () function for the form class. If the check fails in any of these clean () functions, I raise this error:

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

If such an error occurs, the application detects the error and displays it in the form for the user.

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

import logging
logger = logging.getLogger(__name__)

Now, in addition to telling the user ValidationErrors, I would like to catch them and register them as errors. Is there any general and elegant way to get the registrar to log all such errors without changing any other behavior that affects the application user?

+4
source share
1 answer

You can expand yours Formsto register errors as soon as the completion of the check is completed:

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 mixing logging:

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

When Django 1.7 is missing, you will also be able to catch exception messages as they occur. This will give you unhandled exceptions as they have been raised ( Formdoes some 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.

+2

All Articles