1 from django
.utils
.html
import escape
2 from django
.utils
.encoding
import smart_unicode
, StrAndUnicode
, force_unicode
3 from django
.utils
.functional
import Promise
4 from django
.utils
.safestring
import mark_safe
8 Convert a dictionary of attributes to a single string.
9 The returned string will contain a leading space followed by key="value",
10 XML-style pairs. It is assumed that the keys do not need to be XML-escaped.
11 If the passed dictionary is empty, then return an empty string.
13 return u
''.join([u
' %s="%s"' % (k
, escape(v
)) for k
, v
in attrs
.items()])
15 class ErrorDict(dict, StrAndUnicode
):
17 A collection of errors that knows how to display itself in various formats.
19 The dictionary keys are the field names, and the values are the errors.
21 def __unicode__(self
):
25 if not self
: return u
''
26 return mark_safe(u
'<ul class="errorlist">%s</ul>'
27 % ''.join([u
'<li>%s%s</li>' % (k
, force_unicode(v
))
28 for k
, v
in self
.items()]))
31 return u
'\n'.join([u
'* %s\n%s' % (k
, u
'\n'.join([u
' * %s' % force_unicode(i
) for i
in v
])) for k
, v
in self
.items()])
33 class ErrorList(list, StrAndUnicode
):
35 A collection of errors that knows how to display itself in various formats.
37 def __unicode__(self
):
41 if not self
: return u
''
42 return mark_safe(u
'<ul class="errorlist">%s</ul>'
43 % ''.join([u
'<li>%s</li>' % force_unicode(e
) for e
in self
]))
46 if not self
: return u
''
47 return u
'\n'.join([u
'* %s' % force_unicode(e
) for e
in self
])
50 return repr([force_unicode(e
) for e
in self
])
52 class ValidationError(Exception):
53 def __init__(self
, message
):
55 ValidationError can be passed any object that can be printed (usually
56 a string) or a list of objects.
58 if isinstance(message
, list):
59 self
.messages
= ErrorList([smart_unicode(msg
) for msg
in message
])
61 message
= smart_unicode(message
)
62 self
.messages
= ErrorList([message
])
65 # This is needed because, without a __str__(), printing an exception
66 # instance would result in this:
67 # AttributeError: ValidationError instance has no attribute 'args'
68 # See http://www.python.org/doc/current/tut/node10.html#handling
69 return repr(self
.messages
)