我们从Python开源项目中,提取了以下48个代码示例,用于说明如何使用django.core.validators.ValidationError()。
def get_value(self, data): """Retrieves value from data with fallback to defaults""" # Retrieve raw config value, with fallback to default # when value is not defined try: raw_config_value = data[self.name] except KeyError: value = self.get_default_value() else: try: if self.multiple: value = self.get_multiple_values(raw_config_value) else: value = self.get_single_value(raw_config_value) except ValidationError: value = self.get_default_value() return value
def run_basic_validation(self, data): """ Validates presence of variable and conversion. Returns converted value on success. """ # Check presence of value try: raw_config_value = data[self.name] except KeyError: if self.required: raise ValidationError(self.error_messages['required']) value = self.get_default_value() else: # Validation errors are passed: if self.multiple: value = self.get_multiple_values(raw_config_value) else: value = self.get_single_value(raw_config_value) return value
def test_verify_user_empty_email(trans_member): """Test verifying user using `verify_user` function""" # Member has no EmailAddress set with pytest.raises(EmailAddress.DoesNotExist): EmailAddress.objects.get(user=trans_member) # Email is not set on User either assert trans_member.email == '' # Verify user - raises ValidationError with pytest.raises(ValidationError): accounts.utils.verify_user(trans_member) # User still has no email with pytest.raises(EmailAddress.DoesNotExist): EmailAddress.objects.get(user=trans_member)
def suitable_for_url_wtforms(form, field): """WTForm proxy for suitable_for_url""" return suitable_for_url(field.data) # this cannot be serialized by django 1.8 # https://docs.djangoproject.com/en/1.8/topics/migrations/#serializing-values # def reserved_names(*names): # # reserved_names =["all", "all-alpha"] # def test_reserved_names(value): # if value in names: # raise ValidationError( # "The name `%s' is reserved for system-internal use. "\ # "Please choose another." # % value) # return # return test_reserved_names
def get_manifest(self, archive): try: with ZipFile(archive.temporary_file_path()) as plugin: print(plugin.namelist()) prefix = self.get_prefix(plugin) prefix = prefix + '/' if len(prefix) else '' with plugin.open('{}manifest.json'.format(prefix)) as myfile: manifest = json.loads(myfile.read()) validate_manifest(manifest) return manifest except BadZipFile: raise ValidationError('Bad .zip format') except FileNotFoundError: raise ValidationError('Error with upload, please try again') except KeyError: raise ValidationError('No manifest.json found in archive') except json.JSONDecodeError: raise ValidationError('Error with manifest.json, bad Json Format') except avasdk.exceptions.ValidationError as e: raise ValidationError('Error in manifest.json ({})'.format(e))
def generate_unique_username(txts, regex=None): from .account.adapter import get_adapter adapter = get_adapter() username = _generate_unique_username_base(txts, regex) max_length = get_username_max_length() i = 0 while True: try: if i: pfx = str(i + 1) else: pfx = '' ret = username[0:max_length - len(pfx)] + pfx return adapter.clean_username(ret) except ValidationError: i += 1
def test_name(self): plugin = Plugin() # check default value assert plugin.name is None # and that field validation fails on empty name with pytest.raises(ValidationError): plugin.full_clean() # trying to save a None name should raise a database error with pytest.raises(ValidationError): plugin.save() # also empty string must no be allowed plugin.name = '' # whereby saving empty name strings to database unfortunately works, # so never forget to call .full_clean() before custom .save() calls with pytest.raises(ValidationError): plugin.full_clean() plugin.name = 'test' plugin.full_clean()
def filter_email(organizations): """Filter the list of addresses to make sure it's an email-address""" valid_emails = [] for organization in organizations: try: validate_email(organization.contact) except ValidationError: for extracted_email in organization.extract_emails(): try: validate_email(extracted_email) except ValidationError: continue else: valid_emails.append(extracted_email) else: valid_emails.append(organization.contact) return list(set(valid_emails))
def validate_org(self, attrs, source): org = attrs[source].lower() if org in RegistrationFormUserProfile._reserved_usernames: raise ValidationError( u"%s is a reserved name, please choose another" % org) elif not RegistrationFormUserProfile.legal_usernames_re.search(org): raise ValidationError( u'organization may only contain alpha-numeric characters and ' u'underscores') try: User.objects.get(username=org) except User.DoesNotExist: attrs[source] = org return attrs raise ValidationError(u'%s already exists' % org)
def validate(self): """ Checks the data against validation settings for each variable. """ errors = [] for name, variable in self.variable_by_name.items(): try: variable.validate_value(self.data) except ValidationError as e: for message in e.messages: errors.append('{0}: {1}'.format(name, message)) if errors: raise ValidationError(errors)
def get_single_value(self, raw_config_value): """Retrieves single value""" if self.choices: # Choices applied: # Map the value using choices, with fallback to the default # when value is not in available choices reversed_choice_dict = dict((v, k) for (k, v) in self.choices) try: value = reversed_choice_dict[raw_config_value] except KeyError: raise ValidationError( self.error_messages['invalid_choice'] % { 'value': raw_config_value } ) else: # Converter applied: # Map the value using converter, # with fallback to the default when conversion fails try: value = self.converter(raw_config_value) except Exception as e: raise ValidationError( self.error_messages['unable_to_process'] % { 'exc_type': e.__class__.__name__, 'exc_message': e.message } ) if callable(value): # may be callable value = value() return value
def get_multiple_values(self, raw_config_values): """Retrieves multiple values""" try: iter(raw_config_values) except TypeError as e: raise ValidationError( self.error_messages['unable_to_process'] % { 'exc_type': e.__class__.__name__, 'exc_message': e.message } ) return [ self.get_single_value(raw_config_value) for raw_config_value in raw_config_values ]
def test_verify_user_duplicate_email(trans_member, member_with_email): """Test verifying user using `verify_user` function""" # trans_member steals member_with_email's email trans_member.email = member_with_email.email # And can't verify with it with pytest.raises(ValidationError): accounts.utils.verify_user(trans_member) # Email not verified with pytest.raises(EmailAddress.DoesNotExist): EmailAddress.objects.get(user=trans_member, primary=True, verified=True)
def test_update_user_email_bad_invalid_email(member_with_email): with pytest.raises(ValidationError): accounts.utils.update_user_email(member_with_email, "NOT_AN_EMAIL_ADDRESS")
def handle(self, **options): try: accounts.utils.update_user_email(self.get_user(options['user']), options['email']) except ValidationError as e: raise CommandError(e) self.stdout.write("Email updated: %s, %s\n" % (options['user'], options['email']))
def validate_email_unique(email, for_user=None): """Validates an email to ensure it does not already exist in the system. :param email: Email address to validate for uniqueness. :param for_user: Optionally check an email address is unique to this user """ existing_accounts = get_user_model().objects.filter(email=email) existing_email = EmailAddress.objects.filter(email=email) if for_user is not None: existing_accounts = existing_accounts.exclude(pk=for_user.pk) existing_email = existing_email.exclude(user=for_user) if existing_accounts.exists() or existing_email.exists(): raise ValidationError("A user with that email address already exists")
def suitable_for_url(value): """Test that value contains onlys unreserved characters according to RFC3986/2.3: unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" """ # also used by the clean_value_for_url function in forms.py regex = re.compile(r"^[a-zA-Z0-9_.~-]+$") match = regex.match(value) if not match: raise ValidationError("""This field can only include characters which are legal in a url: letters, digits and - . _ ~""")
def standard_reserved_names(value): reserved_names = ["all", "all-alpha"] if value in reserved_names: raise ValidationError( "The name `%s' is reserved for system-internal use. " "Please choose another." % value)
def test_reserved_names_validator(self): # validator = reserved_names("all", "all-alpha") for name in ["foo", "bar"]: # good names self.assertIsNone(standard_reserved_names(name)) for name in ["all", "all-alpha"]: # bad names self.assertRaises(ValidationError, standard_reserved_names, name)
def test_suitable_for_url_validator(self): for name in ["aaa", "a-a", "a_a", "a~"]: # good names self.assertIsNone(suitable_for_url(name)) for name in ["A/A", u"??", "A A"]: # bad names self.assertRaises(ValidationError, suitable_for_url, name)
def _is_url(path): try: URLValidator()(path) return True except ValidationError: return False
def __call__(self, value): super().__call__(value) if not zipfile.is_zipfile(value.temporary_file_path()): raise ValidationError(self.message_wrong_archive)
def get_readme(self, archive): try: with ZipFile(archive.temporary_file_path()) as plugin: prefix = self.get_prefix(plugin) with plugin.open('{}/README.md'.format(prefix)) as myfile: readme = myfile.read() return readme except FileNotFoundError: raise ValidationError('Error with upload, please try again') except KeyError: return None
def test_max_choice(self): validator = MaxChoicesValidator(2) self.assertIsNone(validator('[0]')) self.assertIsNone(validator('[0, 1]')) with self.assertRaises(ValidationError): validator('[0, 1, 2]')
def test_min_choice(self): validator = MinChoicesValidator(2) self.assertIsNone(validator('[0, 1]')) self.assertIsNone(validator('[0, 1, 2]')) with self.assertRaises(ValidationError): validator('[0]')
def test_every_choice(self): validator = EverythingCheckedValidator(2) self.assertIsNone(validator('[0, 1]')) with self.assertRaises(ValidationError): validator('[0]') with self.assertRaises(ValidationError): validator('[0, 1, 2]')
def from_db_value(self, value, *args, **kwargs): if not value: return None if isinstance(value, Geoposition): return value if isinstance(value, list): return Geoposition(value[0], value[1]) try: latitude, longitude = value.split(",") return Geoposition(latitude, longitude) except Exception: #pylint: disable=broad-except raise ValidationError(self.error_messages['invalid'], code='invalid')
def _extract_uuid(text): if isinstance(text, six.string_types): form_id_parts = text.split('/') if form_id_parts.__len__() < 2: raise ValidationError(_(u"Invalid formId %s." % text)) text = form_id_parts[1] text = text[text.find("@key="):-1].replace("@key=", "") if text.startswith("uuid:"): text = text.replace("uuid:", "") return text
def validate_username(self, value): """Check that the username exists""" try: User.objects.get(username=value) except User.DoesNotExist: raise ValidationError(_(u"User '%(value)s' does not exist." % {"value": value})) return value
def validate_role(self, value): """check that the role exists""" if value not in ROLES: raise ValidationError(_(u"Unknown role '%(role)s'." % {"role": value})) return value
def get_user_from_uid(uid): if uid is None: raise ValidationError(_("uid is required!")) try: uid = urlsafe_base64_decode(uid) user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): raise ValidationError(_(u"Invalid uid %s") % uid) return user
def validate_email(self, value): users = User.objects.filter(email__iexact=value) if users.count() == 0: raise ValidationError(_(u"User '%(value)s' does not exist.") % {"value": value}) return value
def validate(self, attrs): user = get_user_from_uid(attrs.get('uid')) value = attrs['token'] if not default_token_generator.check_token(user, value): raise ValidationError(_("Invalid token: %s") % value) return attrs
def validate_org(self, value): org = value.lower() if org in RegistrationFormUserProfile._reserved_usernames: raise ValidationError( u"%s is a reserved name, please choose another" % org) elif not RegistrationFormUserProfile.legal_usernames_re.search(org): raise ValidationError( u'organization may only contain alpha-numeric characters and ' u'underscores') if User.objects.filter(username=org).exists(): raise ValidationError(u'%s already exists' % org) return value
def to_python(self,value): try: value = super(self.__class__,self).to_python(value) except (ValueError, ValidationError): key = self.to_field_name or 'pk' value = InvoiceItem.objects.filter(**{key: value}) if not value.exists(): raise ValidationError(self.error_messages['invalid_choice'], code='invalid_choice') else: value = value.first() return value
def valid_email_or_none(email): ret = None try: if email: validate_email(email) if len(email) <= EmailField().max_length: ret = email except ValidationError: pass return ret
def test_validation(self): repo = Repository(user=self.user) # don't allow empty strings repo.full_name = '' repo.provider = '' with pytest.raises(ValidationError): repo.full_clean()
def test_user(self): repo = Repository(full_name=self.full_name, provider=self.provider) # Don't allow saving if not linked to a user with pytest.raises(ValidationError): repo.full_clean()
def _check_remote_availability(self, config): """ Check if remote ABACUS environment is ready. """ try: validator = URLValidator() for url in config.get('ABACUS_REMOTE_SERVERS', ['']): validator(url) return True except ValidationError: return False
def cron_validator(crontab: str): try: Crontab(crontab) except ValueError as exc: raise validators.ValidationError( 'Invalid crontab expression: {} ({})'.format(crontab, exc))
def validate_unique(self, exclude=None): if self.pk is None: queryset = OAuthUser.objects.filter(email__iexact=self.email) else: queryset = OAuthUser.objects.filter(email__iexact=self.email).exclude(pk=self.pk) if len(queryset) != 0: raise ValidationError(u'Email not unique')
def clean(self): if self.field.type != CF_TYPE_SELECT: raise ValidationError("Custom field choices can only be assigned to selection fields.")
def validate_username(self, attrs, source): """Check that the username exists""" value = attrs[source] try: User.objects.get(username=value) except User.DoesNotExist: raise ValidationError(_(u"User '%(value)s' does not exist." % {"value": value})) return attrs
def validate_role(self, attrs, source): """check that the role exists""" value = attrs[source] if value not in ROLES: raise ValidationError(_(u"Unknown role '%(role)s'." % {"role": value})) return attrs