Skip to content

Instantly share code, notes, and snippets.

@hirokiky
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hirokiky/a125eb9676295332fdb9 to your computer and use it in GitHub Desktop.
Save hirokiky/a125eb9676295332fdb9 to your computer and use it in GitHub Desktop.
Adding methods for django's ErrorDict. (by ugly way). I can't prefigure what will happen by using this. maybe some interfaces are lacking.
class ErrorDict(object):
def __init__(self, errordict):
self.errordict = errordict
def __getitem__(self, item):
return self.errordict[item]
def __setitem__(self, key, value):
self.errordict[key] = value
def __str__(self):
return self.as_ul()
def __bool__(self):
return bool(self.errordict)
def get(self, key):
return self.errordict.get(key)
def as_ul(self):
return self.errordict.as_ul()
def as_text(self):
return self.errordict.items()
def method_you_like(self):
return ''
class MyForm(forms.Form):
@property
def errors(self):
return ErrorDict(super(MyForm, self).errors)
# Or This way seems better.
# Because ExtendedErrorDict won't break interfaces belonging to default ErrorDict.
from django.forms.util import ErrorDict
from django.utils.encoding import force_text
class ExtendedErrorDict(ErrorDict):
def as_inline_text(self):
return ', '.join([k + ': [' + ', '.join([force_text(i) for i in v]) + ']'
for k, v in self.items()])
class MyForm(forms.Form):
@property
def errors(self):
default_errors = super(MyForm, self).errors
errors = ExtendedErrorDict()
errors.update(default_errors)
return errors
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment