30 |
30 |
31 class FieldError(Exception): |
31 class FieldError(Exception): |
32 """Some kind of problem with a model field.""" |
32 """Some kind of problem with a model field.""" |
33 pass |
33 pass |
34 |
34 |
|
35 NON_FIELD_ERRORS = '__all__' |
35 class ValidationError(Exception): |
36 class ValidationError(Exception): |
36 """An error while validating data.""" |
37 """An error while validating data.""" |
37 pass |
38 def __init__(self, message, code=None, params=None): |
|
39 import operator |
|
40 from django.utils.encoding import force_unicode |
|
41 """ |
|
42 ValidationError can be passed any object that can be printed (usually |
|
43 a string), a list of objects or a dictionary. |
|
44 """ |
|
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()) |
|
49 |
|
50 if isinstance(message, list): |
|
51 self.messages = [force_unicode(msg) for msg in message] |
|
52 else: |
|
53 self.code = code |
|
54 self.params = params |
|
55 message = force_unicode(message) |
|
56 self.messages = [message] |
|
57 |
|
58 def __str__(self): |
|
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) |
|
66 |
|
67 def __repr__(self): |
|
68 if hasattr(self, 'message_dict'): |
|
69 return 'ValidationError(%s)' % repr(self.message_dict) |
|
70 return 'ValidationError(%s)' % repr(self.messages) |
|
71 |
|
72 def update_error_dict(self, error_dict): |
|
73 if hasattr(self, 'message_dict'): |
|
74 if error_dict: |
|
75 for k, v in self.message_dict.items(): |
|
76 error_dict.setdefault(k, []).extend(v) |
|
77 else: |
|
78 error_dict = self.message_dict |
|
79 else: |
|
80 error_dict[NON_FIELD_ERRORS] = self.messages |
|
81 return error_dict |
|
82 |