1 from django
.utils
.html
import conditional_escape
2 from django
.utils
.encoding
import smart_unicode
, StrAndUnicode
, force_unicode
3 from django
.utils
.safestring
import mark_safe
7 Convert a dictionary of attributes to a single string.
8 The returned string will contain a leading space followed by key="value",
9 XML-style pairs. It is assumed that the keys do not need to be XML-escaped.
10 If the passed dictionary is empty, then return an empty string.
12 return u
''.join([u
' %s="%s"' % (k
, conditional_escape(v
)) for k
, v
in attrs
.items()])
14 class ErrorDict(dict, StrAndUnicode
):
16 A collection of errors that knows how to display itself in various formats.
18 The dictionary keys are the field names, and the values are the errors.
20 def __unicode__(self
):
24 if not self
: return u
''
25 return mark_safe(u
'<ul class="errorlist">%s</ul>'
26 % ''.join([u
'<li>%s%s</li>' % (k
, force_unicode(v
))
27 for k
, v
in self
.items()]))
30 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()])
32 class ErrorList(list, StrAndUnicode
):
34 A collection of errors that knows how to display itself in various formats.
36 def __unicode__(self
):
40 if not self
: return u
''
41 return mark_safe(u
'<ul class="errorlist">%s</ul>'
42 % ''.join([u
'<li>%s</li>' % force_unicode(e
) for e
in self
]))
45 if not self
: return u
''
46 return u
'\n'.join([u
'* %s' % force_unicode(e
) for e
in self
])
49 return repr([force_unicode(e
) for e
in self
])
51 class ValidationError(Exception):
52 def __init__(self
, message
):
54 ValidationError can be passed any object that can be printed (usually
55 a string) or a list of objects.
57 if isinstance(message
, list):
58 self
.messages
= ErrorList([smart_unicode(msg
) for msg
in message
])
60 message
= smart_unicode(message
)
61 self
.messages
= ErrorList([message
])
64 # This is needed because, without a __str__(), printing an exception
65 # instance would result in this:
66 # AttributeError: ValidationError instance has no attribute 'args'
67 # See http://www.python.org/doc/current/tut/node10.html#handling
68 return repr(self
.messages
)