1
0
mirror of https://github.com/django/django.git synced 2025-07-07 11:19:12 +00:00

[soc2009/model-validation] Cleaned up some comments and whitespace.

git-svn-id: http://code.djangoproject.com/svn/django/branches/soc2009/model-validation@12038 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
Joseph Kocherhans 2010-01-01 20:30:17 +00:00
parent 201d171d9d
commit c2a2b51ac3
6 changed files with 17 additions and 18 deletions

View File

@ -44,6 +44,7 @@ class ValidationError(Exception):
""" """
if isinstance(message, dict): if isinstance(message, dict):
self.message_dict = message self.message_dict = message
# Reduce each list of messages into a single list.
message = reduce(operator.add, message.values()) message = reduce(operator.add, message.values())
if isinstance(message, list): if isinstance(message, list):

View File

@ -819,8 +819,9 @@ class Model(object):
error_list.append(message) error_list.append(message)
else: else:
error_list.extend(e.messages) error_list.extend(e.messages)
# Form.clean() is run even if other validation fails, so do the
# same with Model.validate() for consistency.
try: try:
# TODO: run this only if not errors??
self.validate() self.validate()
except ValidationError, e: except ValidationError, e:
if hasattr(e, 'message_dict'): if hasattr(e, 'message_dict'):

View File

@ -149,7 +149,6 @@ class Field(object):
for k in translated_keys: for k in translated_keys:
self.error_messages[k] = _(self.error_messages[k]) self.error_messages[k] = _(self.error_messages[k])
def __cmp__(self, other): def __cmp__(self, other):
# This is needed because bisect does not take a comparison function. # This is needed because bisect does not take a comparison function.
return cmp(self.creation_counter, other.creation_counter) return cmp(self.creation_counter, other.creation_counter)
@ -177,8 +176,8 @@ class Field(object):
errors = [] errors = []
for v in self.validators: for v in self.validators:
# don't run complex validators since they need obj # Don't run complex validators since they need the model instance
# and must therefore be run on the model level # and must therefore be run on the model level.
if not isinstance(v, validators.ComplexValidator): if not isinstance(v, validators.ComplexValidator):
try: try:
v(value) v(value)
@ -192,14 +191,14 @@ class Field(object):
errors.extend(e.messages) errors.extend(e.messages)
if errors: if errors:
raise exceptions.ValidationError(errors) raise exceptions.ValidationError(errors)
def validate(self, value, model_instance): def validate(self, value, model_instance):
""" """
Validates value and throws ValidationError. Subclasses should override Validates value and throws ValidationError. Subclasses should override
this to provide validation logic. this to provide validation logic.
""" """
if not self.editable: if not self.editable:
# skip validation for non-editable fields # Skip validation for non-editable fields.
return return
if self._choices and value: if self._choices and value:
if not value in dict(self.choices): if not value in dict(self.choices):
@ -208,15 +207,12 @@ class Field(object):
if value is None and not self.null: if value is None and not self.null:
raise exceptions.ValidationError(self.error_messages['null']) raise exceptions.ValidationError(self.error_messages['null'])
# cannot do if not value because of 0 passed to integer fields
if not self.blank and value in validators.EMPTY_VALUES: if not self.blank and value in validators.EMPTY_VALUES:
raise exceptions.ValidationError(self.error_messages['blank']) raise exceptions.ValidationError(self.error_messages['blank'])
def clean(self, value, model_instance): def clean(self, value, model_instance):
""" """
Convert the value's type and wun validation. Validation errors from to_python Convert the value's type and run validation. Validation errors from to_python
and validate are propagated. The correct value is returned if no error is and validate are propagated. The correct value is returned if no error is
raised. raised.
""" """
@ -493,7 +489,7 @@ class AutoField(Field):
return int(value) return int(value)
except (TypeError, ValueError): except (TypeError, ValueError):
raise exceptions.ValidationError(self.error_messages['invalid']) raise exceptions.ValidationError(self.error_messages['invalid'])
def validate(self, value, model_instance): def validate(self, value, model_instance):
pass pass
@ -1112,3 +1108,4 @@ class XMLField(TextField):
def __init__(self, verbose_name=None, name=None, schema_path=None, **kwargs): def __init__(self, verbose_name=None, name=None, schema_path=None, **kwargs):
self.schema_path = schema_path self.schema_path = schema_path
Field.__init__(self, verbose_name, name, **kwargs) Field.__init__(self, verbose_name, name, **kwargs)

View File

@ -284,14 +284,14 @@ class BaseForm(StrAndUnicode):
if name in self.cleaned_data: if name in self.cleaned_data:
del self.cleaned_data[name] del self.cleaned_data[name]
# run complex validators after the fields have been cleaned since they # Run complex validators after the fields have been cleaned since they
# need access to all_values # need access to all_values.
for name, field in self.fields.items(): for name, field in self.fields.items():
if not name in self.cleaned_data: if not name in self.cleaned_data:
continue continue
failed = False failed = False
for v in field.validators: for v in field.validators:
# skip noncomplex validators, they have already been run on the Field # Skip noncomplex validators, they have already been run on the field.
if not isinstance(v, ComplexValidator): if not isinstance(v, ComplexValidator):
continue continue
try: try:

View File

@ -2,8 +2,8 @@ from django.utils.html import conditional_escape
from django.utils.encoding import StrAndUnicode, force_unicode from django.utils.encoding import StrAndUnicode, force_unicode
from django.utils.safestring import mark_safe from django.utils.safestring import mark_safe
# import ValidationError so that it can be imported from this # Import ValidationError so that it can be imported from this
# module to maintain backwards compatibility # module to maintain backwards compatibility.
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
def flatatt(attrs): def flatatt(attrs):

View File

@ -39,7 +39,7 @@ class PerformUniqueChecksTest(unittest.TestCase):
super(PerformUniqueChecksTest, self).tearDown() super(PerformUniqueChecksTest, self).tearDown()
def test_primary_key_unique_check_performed_when_adding(self): def test_primary_key_unique_check_performed_when_adding(self):
"Check#12132" """Regression test for #12132"""
l = len(connection.queries) l = len(connection.queries)
mtv = ModelToValidate(number=10, name='Some Name') mtv = ModelToValidate(number=10, name='Some Name')
setattr(mtv, '_adding', True) setattr(mtv, '_adding', True)
@ -47,7 +47,7 @@ class PerformUniqueChecksTest(unittest.TestCase):
self.assertEqual(l+1, len(connection.queries)) self.assertEqual(l+1, len(connection.queries))
def test_primary_key_unique_check_not_performed_when_not_adding(self): def test_primary_key_unique_check_not_performed_when_not_adding(self):
"Check#12132" """Regression test for #12132"""
l = len(connection.queries) l = len(connection.queries)
mtv = ModelToValidate(number=10, name='Some Name') mtv = ModelToValidate(number=10, name='Some Name')
mtv.clean() mtv.clean()