Django log form ValidationErrors

Forms are the primary way your users communicate with your website. Hopefully, the users are always entering data in the correct format, and the form always accepts their submissions. In the real world, users often encounter form validation errors.

In some ways, this is a good thing. At least you're getting valid data, in the end. However, too many validation errors can lead to form abandonment, ie the user may give up. When that happens, don't you want to know?

In Django, there is a relatively easy way to log any form validation errors that happen. Simply over-ride the is_valid() function on your forms.

class MyForm(Form):
    def is_valid(self):
        is_valid = super(MyForm, self).is_valid(self)
        if not is_valid:
            for field in self.errors.keys():
                print "ValidationError: %s[%s] <- \"%s\" %s" % (
                    type(self),
                    field,
                    self.data[field],
                    self.errors[field].as_text()
                )
        return is_valid

This will produce the following output in your logs, which you can then grep and even email to yourself on a regular basis if you so desire.

ValidationError: <class 'website.views.profiles.Step1Form'>[password] <- "" * This field is required.
ValidationError: <class 'website.views.profiles.Step1Form'>[email] <- "aaa" * Enter a valid e-mail address.


I'm currently working at NerdWallet, a startup in San Francisco trying to bring clarity to all of life's financial decisions. We're hiring like crazy. Hit me up on Twitter, I would love to talk.

Follow @chase_seibert on Twitter