Skip to content

Instantly share code, notes, and snippets.

@tmhedberg
Created July 23, 2011 21:25
Show Gist options
  • Save tmhedberg/1101901 to your computer and use it in GitHub Desktop.
Save tmhedberg/1101901 to your computer and use it in GitHub Desktop.
Monkey-patch a Django Field instance in order to automatically add a CSS class to its widget when validation fails
import types
from django.core import exceptions
def auto_error_class(field, error_class="error"):
inner_clean = field.clean
def wrap_clean(self, *args, **kwargs):
try:
return inner_clean(*args, **kwargs)
except exceptions.ValidationError as ex:
self.widget.attrs["class"] = self.widget.attrs.get(
"class", ""
) + " " + error_class
raise ex
field.clean = types.MethodType(wrap_clean, field, field.__class__)
return field
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment