本文整理汇总了Python中django.core.exceptions.ValidationError类的典型用法代码示例。如果您正苦于以下问题:Python ValidationError类的具体用法?Python ValidationError怎么用?Python ValidationError使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ValidationError类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: validate
def validate(data, schema):
"""
Validates the data against given schema and checks validity of ds_id and ds_spirit.
:param data: The data to validate
:param schema: The JSON schema to use for validation.
:return: Valid data
"""
if isinstance(data, dict):
properties = data
elif isinstance(data, Individual):
properties = data.properties
else:
raise ValidationError(
"An Individual can only work with a dict as data and got {} instead".format(type(data))
)
if "_id" in properties:
del properties["_id"]
try:
jsonschema.validate(properties, schema)
except SchemaValidationError as exc:
django_exception = ValidationError(exc.message)
django_exception.schema = exc.schema
raise django_exception
示例2: ValidationError
def 加外語資料(cls, 內容):
try:
原本外語 = cls._找外語資料(內容)
錯誤 = ValidationError('已經有相同的外語資料了')
錯誤.平臺項目編號 = 原本外語.編號()
raise 錯誤
except ObjectDoesNotExist:
pass
外語 = 外語表.加資料(cls._補預設欄位(內容, 字詞))
return cls.objects.create(外語=外語)
示例3: validate_unique
def validate_unique(self, exclude=None):
if not self.id:
try:
Flowvisor.objects.get(name=self.name)
e = ValidationError(_("%(model_name)s with this %(field_label)s already exists.") % {"field_label": self._meta.get_field('name').verbose_name, "model_name": self._meta.verbose_name})
e.message_dict = {}
e.message_dict["name"] = e.messages
raise e
except Flowvisor.DoesNotExist:
return self.name
super(Flowvisor, self).validate_unique(exclude)
示例4: save
def save(self, image, save=True):
try:
super(FieldWallet, self).save(image)
except IOError:
# Пока никакой интернационализации, только хардкор.
e = ValidationError(u"Неверный формат изображения.")
e.message_dict = { self.field.name: [u"Выберите другой файл."] }
raise e
if self.field.process_all_formats:
self.process_all_formats()
if save:
self.instance.save()
示例5: clean
def clean(self):
try:
self.dataSource = DataSource(self.fgdb_path)
except:
raise ValidationError(self.fgdb_path + " could not be opened by GDAL")
else:
validator = GdbValidator(self.dataSource)
valid = validator.isValid()
if not valid:
err = ValidationError(validator.validationMessage())
err.asJson = validator.logs.asJson()
raise err
示例6: add_error
def add_error(self, field, error):
"""
Update the content of `self._errors`.
The `field` argument is the name of the field to which the errors
should be added. If its value is None the errors will be treated as
NON_FIELD_ERRORS.
The `error` argument can be a single error, a list of errors, or a
dictionary that maps field names to lists of errors. What we define as
an "error" can be either a simple string or an instance of
ValidationError with its message attribute set and what we define as
list or dictionary can be an actual `list` or `dict` or an instance
of ValidationError with its `error_list` or `error_dict` attribute set.
If `error` is a dictionary, the `field` argument *must* be None and
errors will be added to the fields that correspond to the keys of the
dictionary.
"""
if not isinstance(error, ValidationError):
# Normalize to ValidationError and let its constructor
# do the hard work of making sense of the input.
error = ValidationError(error)
if hasattr(error, 'error_dict'):
if field is not None:
raise TypeError(
"The argument `field` must be `None` when the `error` "
"argument contains errors for multiple fields."
)
else:
error = error.error_dict
else:
error = {field or NON_FIELD_ERRORS: error.error_list}
for field, error_list in error.items():
if field not in self.errors:
if field != NON_FIELD_ERRORS and field not in self.fields:
raise ValueError(
"'%s' has no field named '%s'." % (self.__class__.__name__, field))
if field == NON_FIELD_ERRORS:
self._errors[field] = self.error_class(error_class='nonfield')
else:
self._errors[field] = self.error_class()
self._errors[field].extend(error_list)
if field in self.cleaned_data:
del self.cleaned_data[field]
示例7: add_error
def add_error(self, field, error):
"""
Standard django form does not support more structured errors
(for example error dict that contains another error dict).
For this purpose pyston creates RESTError class and we must rewrite this method to allow these
complex error messages.
"""
if isinstance(error, RESTError):
if not field:
raise ValueError('Field must be set for RESTError')
self._errors[field] = error
else:
if not isinstance(error, ValidationError):
# Normalize to ValidationError and let its constructor
# do the hard work of making sense of the input.
error = ValidationError(error)
if hasattr(error, 'error_dict'):
if field is not None:
raise TypeError(
"The argument `field` must be `None` when the `error` "
"argument contains errors for multiple fields."
)
else:
error = error.error_dict
else:
error = {field or NON_FIELD_ERRORS: error.error_list}
for field, error_list in error.items():
if field not in self.errors:
if field == NON_FIELD_ERRORS:
self._errors[field] = self.error_class(error_class='nonfield')
else:
self._errors[field] = self.error_class()
self._errors[field].extend(error_list)
if field in self.cleaned_data:
del self.cleaned_data[field]
示例8: setUp
def setUp(self):
# Create a ValidationEror with a mix of field-specific and non-field-specific errors
self.non_field_errors = ValidationError(['Error 1', 'Error 2', 'Error 3'])
self.field_errors = ValidationError({
'name': ['Error 4', 'Error 5'],
'birthday': ['Error 6', 'Error 7'],
})
combined_error_dict = self.non_field_errors.update_error_dict(
self.field_errors.error_dict.copy()
)
e = ValidationError(combined_error_dict)
# Create an InvalidRow instance to use in tests
self.obj = InvalidRow(
number=1,
validation_error=e,
values={'name': 'ABC', 'birthday': '123'}
)
示例9: InvalidRowTest
class InvalidRowTest(TestCase):
def setUp(self):
# Create a ValidationEror with a mix of field-specific and non-field-specific errors
self.non_field_errors = ValidationError(['Error 1', 'Error 2', 'Error 3'])
self.field_errors = ValidationError({
'name': ['Error 4', 'Error 5'],
'birthday': ['Error 6', 'Error 7'],
})
combined_error_dict = self.non_field_errors.update_error_dict(
self.field_errors.error_dict.copy()
)
e = ValidationError(combined_error_dict)
# Create an InvalidRow instance to use in tests
self.obj = InvalidRow(
number=1,
validation_error=e,
values={'name': 'ABC', 'birthday': '123'}
)
def test_error_count(self):
self.assertEqual(self.obj.error_count, 7)
def test_non_field_specific_errors(self):
result = self.obj.non_field_specific_errors
self.assertIsInstance(result, list)
self.assertEqual(result, ['Error 1', 'Error 2', 'Error 3'])
def test_field_specific_errors(self):
result = self.obj.field_specific_errors
self.assertIsInstance(result, dict)
self.assertEqual(len(result), 2)
self.assertEqual(result['name'], ['Error 4', 'Error 5'])
self.assertEqual(result['birthday'], ['Error 6', 'Error 7'])
def test_creates_error_dict_from_error_list_if_validation_error_only_has_error_list(self):
obj = InvalidRow(
number=1,
validation_error=self.non_field_errors,
values={}
)
self.assertIsInstance(obj.error_dict, dict)
self.assertIn(NON_FIELD_ERRORS, obj.error_dict)
self.assertEqual(obj.error_dict[NON_FIELD_ERRORS], ['Error 1', 'Error 2', 'Error 3'])
示例10: __init__
def __init__(self):
ValidationError.__init__(self,
_(u"El problema no tiene registrada ninguna ciudad."))
示例11: __init__
def __init__(self, field_name, message):
self.field_name = field_name
print('Field error', self.field_name, message)
_ValidationError.__init__(self, message)
示例12: __init__
def __init__(self, field_name, message):
self.field_name = field_name
_ValidationError.__init__(self, message)
示例13: _pages_from_json
def _pages_from_json(request, offering, data):
with django.db.transaction.atomic():
try:
data = data.decode('utf-8-sig')
except UnicodeDecodeError:
raise ValidationError("Bad UTF-8 data in file.")
try:
data = json.loads(data)
except ValueError as e:
raise ValidationError('JSON decoding error. Exception was: "' + str(e) + '"')
if not isinstance(data, dict):
raise ValidationError('Outer JSON data structure must be an object.')
if 'userid' not in data or 'token' not in data:
raise ValidationError('Outer JSON data object must contain keys "userid" and "token".')
if 'pages' not in data:
raise ValidationError('Outer JSON data object must contain keys "pages".')
if not isinstance(data['pages'], list):
raise ValidationError('Value for "pages" must be a list.')
try:
user = Person.objects.get(userid=data['userid'])
member = Member.objects.exclude(role='DROP').get(person=user, offering=offering)
except (Person.DoesNotExist, Member.DoesNotExist):
raise ValidationError('Person with that userid does not exist.')
if 'pages-token' not in user.config or user.config['pages-token'] != data['token']:
e = ValidationError('Could not validate authentication token.')
e.status = 403
raise e
# if we get this far, the user is authenticated and we can start processing the pages...
for i, pdata in enumerate(data['pages']):
if not isinstance(pdata, dict):
raise ValidationError('Page #%i entry structure must be an object.' % (i))
if 'label' not in pdata:
raise ValidationError('Page #%i entry does not have a "label".' % (i))
# handle changes to the Page object
pages = Page.objects.filter(offering=offering, label=pdata['label'])
if pages:
page = pages[0]
old_ver = page.current_version()
else:
page = Page(offering=offering, label=pdata['label'])
old_ver = None
# check write permissions
# mock the request object enough to satisfy _check_allowed()
class FakeRequest(object):
is_authenticated = True
fake_request = FakeRequest()
fake_request.user = FakeRequest()
fake_request.user.username = user.userid
if old_ver:
m = _check_allowed(fake_request, offering, page.can_write, page.editdate())
else:
m = _check_allowed(fake_request, offering, offering.page_creators())
if not m:
raise ValidationError('You can\'t edit page #%i.' % (i))
# handle Page attributes
if 'can_read' in pdata:
if type(pdata['can_read']) != str or pdata['can_read'] not in ACL_DESC:
raise ValidationError('Page #%i "can_read" value must be one of %s.'
% (i, ','.join(list(ACL_DESC.keys()))))
page.can_read = pdata['can_read']
if 'can_write' in pdata:
if type(pdata['can_write']) != str or pdata['can_write'] not in WRITE_ACL_DESC:
raise ValidationError('Page #%i "can_write" value must be one of %s.'
% (i, ','.join(list(WRITE_ACL_DESC.keys()))))
if m.role == 'STUD':
raise ValidationError('Page #%i: students can\'t change can_write value.' % (i))
page.can_write = pdata['can_write']
if 'new_label' in pdata:
if type(pdata['new_label']) != str:
raise ValidationError('Page #%i "new_label" value must be a string.' % (i))
if m.role == 'STUD':
raise ValidationError('Page #%i: students can\'t change label value.' % (i))
if Page.objects.filter(offering=offering, label=pdata['new_label']):
raise ValidationError('Page #%i: there is already a page with that "new_label".' % (i))
page.label = pdata['new_label']
page.save()
# handle PageVersion changes
ver = PageVersion(page=page, editor=member)
if 'title' in pdata:
if type(pdata['title']) != str:
raise ValidationError('Page #%i "title" value must be a string.' % (i))
#.........这里部分代码省略.........
示例14: ValidationError
for name, field in self.api_fields.iteritems():
if not name in obj:
value = None
else:
value = obj[name]
try:
cleaned_value = field.unserialize(value)
new_dict[name] = cleaned_value
except ValidationError, e:
errors[name] = e.messages
if errors:
error = ValidationError("There were multiple errors when validating the data.")
error.messages = errors
raise error
return new_dict
def _content_types_urlconf(self):
types = "|".join(self.serializer.content_types.keys())
return r"(?P<content_type>(%s))" % (types, )
def _determine_content_type_from_request(self, request, content_type=None):
request_ct = request.META.get("HTTP_ACCEPT", None)
allowed_formats = self.serializer.content_types.keys()
示例15: clean
def clean(self):
#ToDo: non comments, how to make it better? Overload Validation Error?
if not (self.parent or self.title):
error = ValidationError("")
error.message_dict = {u"title": u"Field is required."}
raise error