summaryrefslogtreecommitdiff
path: root/django/newforms/util.py
diff options
context:
space:
mode:
authorRobin Munn <robin.munn@gmail.com>2006-11-08 04:50:01 +0000
committerRobin Munn <robin.munn@gmail.com>2006-11-08 04:50:01 +0000
commitdadfca08c0db567ce33284aaa8eb388cf667a836 (patch)
treeab7255eeee1bbe03d95652cc74a3843fa052d8ac /django/newforms/util.py
parent0b059aa4eadc1d95ceca3a32821b65a9fb2a53e8 (diff)
sqlalchemy: Merged revisions 3918 to 4053 from trunk.
git-svn-id: http://code.djangoproject.com/svn/django/branches/sqlalchemy@4054 bcc190cf-cafb-0310-a4f2-bffc1f526a37
Diffstat (limited to 'django/newforms/util.py')
-rw-r--r--django/newforms/util.py55
1 files changed, 55 insertions, 0 deletions
diff --git a/django/newforms/util.py b/django/newforms/util.py
new file mode 100644
index 0000000000..3887010c85
--- /dev/null
+++ b/django/newforms/util.py
@@ -0,0 +1,55 @@
+# Default encoding for input byte strings.
+DEFAULT_ENCODING = 'utf-8' # TODO: First look at django.conf.settings, then fall back to this.
+
+def smart_unicode(s):
+ if not isinstance(s, unicode):
+ s = unicode(s, DEFAULT_ENCODING)
+ return s
+
+class ErrorDict(dict):
+ """
+ A collection of errors that knows how to display itself in various formats.
+
+ The dictionary keys are the field names, and the values are the errors.
+ """
+ def __str__(self):
+ return self.as_ul()
+
+ def as_ul(self):
+ if not self: return u''
+ return u'<ul class="errorlist">%s</ul>' % ''.join([u'<li>%s%s</li>' % (k, v) for k, v in self.items()])
+
+ def as_text(self):
+ return u'\n'.join([u'* %s\n%s' % (k, u'\n'.join([u' * %s' % i for i in v])) for k, v in self.items()])
+
+class ErrorList(list):
+ """
+ A collection of errors that knows how to display itself in various formats.
+ """
+ def __str__(self):
+ return self.as_ul()
+
+ def as_ul(self):
+ if not self: return u''
+ return u'<ul class="errorlist">%s</ul>' % ''.join([u'<li>%s</li>' % e for e in self])
+
+ def as_text(self):
+ if not self: return u''
+ return u'\n'.join([u'* %s' % e for e in self])
+
+class ValidationError(Exception):
+ def __init__(self, message):
+ "ValidationError can be passed a string or a list."
+ if isinstance(message, list):
+ self.messages = ErrorList([smart_unicode(msg) for msg in message])
+ else:
+ assert isinstance(message, basestring), ("%s should be a basestring" % repr(message))
+ message = smart_unicode(message)
+ self.messages = ErrorList([message])
+
+ def __str__(self):
+ # This is needed because, without a __str__(), printing an exception
+ # instance would result in this:
+ # AttributeError: ValidationError instance has no attribute 'args'
+ # See http://www.python.org/doc/current/tut/node10.html#handling
+ return repr(self.messages)