本文整理汇总了Python中django.core.validators.ValidationError方法的典型用法代码示例。如果您正苦于以下问题:Python validators.ValidationError方法的具体用法?Python validators.ValidationError怎么用?Python validators.ValidationError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.core.validators
的用法示例。
在下文中一共展示了validators.ValidationError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: validate_url
# 需要导入模块: from django.core import validators [as 别名]
# 或者: from django.core.validators import ValidationError [as 别名]
def validate_url(request):
assert request.method == "GET"
assert request.is_ajax()
url = request.GET.get('url')
assert url
try:
URLValidator(url)
except ValidationError:
raise AssertionError()
assert 'HTTP_REFERER' in request.META
toproxy = urlparse(url)
assert toproxy.hostname
if settings.DEBUG:
return url
referer = urlparse(request.META.get('HTTP_REFERER'))
assert referer.hostname == request.META.get('SERVER_NAME')
assert toproxy.hostname != "localhost"
try:
# clean this when in python 3.4
ipaddress = socket.gethostbyname(toproxy.hostname)
except:
raise AssertionError()
assert not ipaddress.startswith('127.')
assert not ipaddress.startswith('192.168.')
return url
示例2: handle
# 需要导入模块: from django.core import validators [as 别名]
# 或者: from django.core.validators import ValidationError [as 别名]
def handle(self, **options):
if bool(options["user"]) == options["all"]:
raise CommandError(
"Either provide a 'user' to verify or "
"use '--all' to verify all users"
)
if options["all"]:
for user in get_user_model().objects.hide_meta():
try:
utils.verify_user(user)
self.stdout.write("Verified user '%s'" % user.username)
except (ValueError, ValidationError) as e:
self.stderr.write(str(e))
if options["user"]:
for user in options["user"]:
try:
utils.verify_user(self.get_user(user))
self.stdout.write("User '%s' has been verified" % user)
except (ValueError, ValidationError) as e:
self.stderr.write(str(e))
示例3: get_user
# 需要导入模块: from django.core import validators [as 别名]
# 或者: from django.core.validators import ValidationError [as 别名]
def get_user(email: str, mobile: str):
try:
user = User.objects.get(email=email)
except User.DoesNotExist:
try:
user = User.objects.get(mobile=mobile)
except User.DoesNotExist:
user = None
if user:
if user.email != email:
raise serializers.ValidationError(_(
"Your account is registered with {mobile} does not has "
"{email} as registered email. Please login directly via "
"OTP with your mobile.".format(mobile=mobile, email=email)
))
if user.mobile != mobile:
raise serializers.ValidationError(_(
"Your account is registered with {email} does not has "
"{mobile} as registered mobile. Please login directly via "
"OTP with your email.".format(mobile=mobile, email=email)))
return user
示例4: test_script
# 需要导入模块: from django.core import validators [as 别名]
# 或者: from django.core.validators import ValidationError [as 别名]
def test_script(self):
self.recipients = ['test.sh', 'send.sh']
with self.assertRaises(ValidationError):
Hook.objects.create(
type='SCRIPT', recipients="some.sh", when="error_on"
)
hook = Hook.objects.create(
type='SCRIPT', recipients=" | ".join(self.recipients)
)
with patch('subprocess.check_output') as cmd:
self.count = 0
cmd.side_effect = self.check_output_run
self.assertEqual(hook.run(message=dict(test="test")), "Ok\nOk")
self.assertEqual(cmd.call_count, 2)
hook.run('on_error', message=dict(test="test"))
self.assertEqual(cmd.call_count, 2)
cmd.side_effect = self.check_output_error
self.assertEqual(hook.run(message=dict(test="test")), "Err\nErr")
self.assertEqual(cmd.call_count, 4)
示例5: check_project_variables_values
# 需要导入模块: from django.core import validators [as 别名]
# 或者: from django.core.validators import ValidationError [as 别名]
def check_project_variables_values(instance: Variable, *args, **kwargs) -> NoReturn:
if 'loaddata' in sys.argv or kwargs.get('raw', False): # nocv
return
if not isinstance(instance.content_object, Project):
return
project_object = instance.content_object
is_ci_var = instance.key.startswith('ci_')
key_startswith = instance.key.startswith('env_') or is_ci_var
if not key_startswith and instance.key not in Project.VARS_KEY:
msg = 'Unknown variable key \'{}\'. Key must be in {} or starts from \'env_\' or \'ci_\'.'
raise ValidationError(msg.format(instance.key, Project.VARS_KEY))
is_ci_template = instance.key == 'ci_template'
qs_variables = project_object.variables.all()
if is_ci_var and qs_variables.filter(key__startswith='repo_sync_on_run').exists():
raise Conflict('Couldnt install CI/CD to project with "repo_sync_on_run" settings.')
if instance.key.startswith('repo_sync_on_run') and project_object.get_vars_prefixed('ci'):
raise Conflict('Couldnt install "repo_sync_on_run" settings for CI/CD project.')
if is_ci_template and not project_object.template.filter(pk=instance.value).exists():
raise ValidationError('Template does not exists in this project.')
示例6: test_override_clean
# 需要导入模块: from django.core import validators [as 别名]
# 或者: from django.core.validators import ValidationError [as 别名]
def test_override_clean(self):
"""
Regression for #12596: Calling super from ModelForm.clean() should be
optional.
"""
class TripleFormWithCleanOverride(forms.ModelForm):
class Meta:
model = Triple
fields = '__all__'
def clean(self):
if not self.cleaned_data['left'] == self.cleaned_data['right']:
raise forms.ValidationError('Left and right should be equal')
return self.cleaned_data
form = TripleFormWithCleanOverride({'left': 1, 'middle': 2, 'right': 1})
self.assertTrue(form.is_valid())
# form.instance.left will be None if the instance was not constructed
# by form.full_clean().
self.assertEqual(form.instance.left, 1)
示例7: validate_org
# 需要导入模块: from django.core import validators [as 别名]
# 或者: from django.core.validators import ValidationError [as 别名]
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
示例8: validate_username
# 需要导入模块: from django.core import validators [as 别名]
# 或者: from django.core.validators import ValidationError [as 别名]
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
示例9: validate_role
# 需要导入模块: from django.core import validators [as 别名]
# 或者: from django.core.validators import ValidationError [as 别名]
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
示例10: get_user_from_uid
# 需要导入模块: from django.core import validators [as 别名]
# 或者: from django.core.validators import ValidationError [as 别名]
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
示例11: validate_email
# 需要导入模块: from django.core import validators [as 别名]
# 或者: from django.core.validators import ValidationError [as 别名]
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
示例12: validate
# 需要导入模块: from django.core import validators [as 别名]
# 或者: from django.core.validators import ValidationError [as 别名]
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
示例13: _extract_uuid
# 需要导入模块: from django.core import validators [as 别名]
# 或者: from django.core.validators import ValidationError [as 别名]
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
示例14: clean_url
# 需要导入模块: from django.core import validators [as 别名]
# 或者: from django.core.validators import ValidationError [as 别名]
def clean_url(url):
"""
Takes in a string and returns it as a cleaned url, or empty if the string is not a valid URL.
"""
url = clean_text(url, True)
url = url.replace(' ', '%20')
if not re.match(r'^\w+?://', url):
url = 'http://' + url
try:
URLValidator()(url)
return url
except ValidationError:
logger.warning('URL not valid: ' + url)
return None
示例15: cron_validator
# 需要导入模块: from django.core import validators [as 别名]
# 或者: from django.core.validators import ValidationError [as 别名]
def cron_validator(crontab: str):
try:
Crontab(crontab)
except ValueError as exc:
raise validators.ValidationError(
'Invalid crontab expression: {} ({})'.format(crontab, exc))