Created
July 23, 2011 21:25
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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