32
32
"""Some kind of problem with a model field."""
35
NON_FIELD_ERRORS = '__all__'
35
36
class ValidationError(Exception):
36
37
"""An error while validating data."""
38
def __init__(self, message, code=None, params=None):
40
from django.utils.encoding import force_unicode
42
ValidationError can be passed any object that can be printed (usually
43
a string), a list of objects or a dictionary.
45
if isinstance(message, dict):
46
self.message_dict = message
47
# Reduce each list of messages into a single list.
48
message = reduce(operator.add, message.values())
50
if isinstance(message, list):
51
self.messages = [force_unicode(msg) for msg in message]
55
message = force_unicode(message)
56
self.messages = [message]
59
# This is needed because, without a __str__(), printing an exception
60
# instance would result in this:
61
# AttributeError: ValidationError instance has no attribute 'args'
62
# See http://www.python.org/doc/current/tut/node10.html#handling
63
if hasattr(self, 'message_dict'):
64
return repr(self.message_dict)
65
return repr(self.messages)
68
if hasattr(self, 'message_dict'):
69
return 'ValidationError(%s)' % repr(self.message_dict)
70
return 'ValidationError(%s)' % repr(self.messages)
72
def update_error_dict(self, error_dict):
73
if hasattr(self, 'message_dict'):
75
for k, v in self.message_dict.items():
76
error_dict.setdefault(k, []).extend(v)
78
error_dict = self.message_dict
80
error_dict[NON_FIELD_ERRORS] = self.messages