Python django.core.validators.ValidationError() Examples

The following are 30 code examples of django.core.validators.ValidationError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.core.validators , or try the search function .
Example #1
Source File: views.py    From ideascube with GNU Affero General Public License v3.0 6 votes vote down vote up
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 
Example #2
Source File: hooks.py    From polemarch with GNU Affero General Public License v3.0 6 votes vote down vote up
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) 
Example #3
Source File: __init__.py    From polemarch with GNU Affero General Public License v3.0 6 votes vote down vote up
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.') 
Example #4
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
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) 
Example #5
Source File: serializers.py    From drf-user with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #6
Source File: verify_user.py    From zing with GNU General Public License v3.0 6 votes vote down vote up
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)) 
Example #7
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_setattr_raises_validation_error_non_field(self):
        """
        A model ValidationError not using the dict form should put the error
        message into __all__ (i.e. non-field errors) on the form.
        """
        form_class = modelform_factory(model=StrictAssignmentAll, fields=['title'])
        form = form_class(data={'title': 'testing setattr'}, files=None)
        # This line turns on the ValidationError; it avoids the model erroring
        # when its own __init__() is called when creating form.instance.
        form.instance._should_error = True
        self.assertFalse(form.is_valid())
        self.assertEqual(form.errors, {
            '__all__': ['Cannot set attribute'],
            'title': ['This field cannot be blank.']
        }) 
Example #8
Source File: projects.py    From polemarch with GNU Affero General Public License v3.0 5 votes vote down vote up
def check_path(self, inventory) -> NoReturn:
        if not isinstance(inventory, str):  # nocv
            return
        path = "{}/{}".format(self.path, inventory)
        path = os.path.abspath(os.path.expanduser(path))
        if self.path not in path:  # nocv
            raise ValidationError(dict(inventory="Inventory should be in project dir.")) 
Example #9
Source File: __init__.py    From polemarch with GNU Affero General Public License v3.0 5 votes vote down vote up
def validate_crontab(instance: PeriodicTask, **kwargs) -> NoReturn:
    if 'loaddata' in sys.argv or kwargs.get('raw', False):  # nocv
        return
    try:
        instance.get_schedule()
    except ValueError as ex:
        msg = dict(schedule=["{}".format(ex)])
        raise ValidationError(msg) 
Example #10
Source File: __init__.py    From polemarch with GNU Affero General Public License v3.0 5 votes vote down vote up
def validate_template_keys(instance: Template, **kwargs) -> NoReturn:
    if 'loaddata' in sys.argv or kwargs.get('raw', False):  # noce
        return
    # Deprecated, because moved to serializers
    if instance.kind not in instance.template_fields.keys():
        raise UnknownTypeException(instance.kind)
    errors = {}
    for key in instance.data.keys():
        if key not in instance.template_fields[instance.kind]:
            errors[key] = "Unknown key. Keys should be {}".format(
                instance.template_fields[instance.kind]
            )
    if errors:
        raise ValidationError(errors) 
Example #11
Source File: __init__.py    From polemarch with GNU Affero General Public License v3.0 5 votes vote down vote up
def check_hook(instance: Hook, **kwargs) -> NoReturn:
    if 'loaddata' in sys.argv or kwargs.get('raw', False):  # noce
        return
    errors = instance.handlers.validate(instance)
    if errors:
        raise ValidationError(errors) 
Example #12
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_exclude_and_validation(self):
        # This Price instance generated by this form is not valid because the quantity
        # field is required, but the form is valid because the field is excluded from
        # the form. This is for backwards compatibility.
        class PriceFormWithoutQuantity(forms.ModelForm):
            class Meta:
                model = Price
                exclude = ('quantity',)

        form = PriceFormWithoutQuantity({'price': '6.00'})
        self.assertTrue(form.is_valid())
        price = form.save(commit=False)
        msg = "{'quantity': ['This field cannot be null.']}"
        with self.assertRaisesMessage(ValidationError, msg):
            price.full_clean()

        # The form should not validate fields that it doesn't contain even if they are
        # specified using 'fields', not 'exclude'.
        class PriceFormWithoutQuantity(forms.ModelForm):
            class Meta:
                model = Price
                fields = ('price',)
        form = PriceFormWithoutQuantity({'price': '6.00'})
        self.assertTrue(form.is_valid())

        # The form should still have an instance of a model that is not complete and
        # not saved into a DB yet.
        self.assertEqual(form.instance.price, Decimal('6.00'))
        self.assertIsNone(form.instance.quantity)
        self.assertIsNone(form.instance.pk) 
Example #13
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_model_multiple_choice_required_false(self):
        f = forms.ModelMultipleChoiceField(Category.objects.all(), required=False)
        self.assertIsInstance(f.clean([]), EmptyQuerySet)
        self.assertIsInstance(f.clean(()), EmptyQuerySet)
        with self.assertRaises(ValidationError):
            f.clean(['0'])
        with self.assertRaises(ValidationError):
            f.clean([str(self.c3.id), '0'])
        with self.assertRaises(ValidationError):
            f.clean([str(self.c1.id), '0'])

        # queryset can be changed after the field is created.
        f.queryset = Category.objects.exclude(name='Third')
        self.assertEqual(list(f.choices), [
            (self.c1.pk, 'Entertainment'),
            (self.c2.pk, "It's a test")])
        self.assertQuerysetEqual(f.clean([self.c2.id]), ["It's a test"])
        with self.assertRaises(ValidationError):
            f.clean([self.c3.id])
        with self.assertRaises(ValidationError):
            f.clean([str(self.c2.id), str(self.c3.id)])

        f.queryset = Category.objects.all()
        f.label_from_instance = lambda obj: "multicategory " + str(obj)
        self.assertEqual(list(f.choices), [
            (self.c1.pk, 'multicategory Entertainment'),
            (self.c2.pk, "multicategory It's a test"),
            (self.c3.pk, 'multicategory Third')]) 
Example #14
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_clean_false_required(self):
        """
        If the ``clean`` method on a required FileField receives False as the
        data, it has the same effect as None: initial is returned if non-empty,
        otherwise the validation catches the lack of a required value.
        """
        f = forms.FileField(required=True)
        self.assertEqual(f.clean(False, 'initial'), 'initial')
        with self.assertRaises(ValidationError):
            f.clean(False) 
Example #15
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_choices_type(self):
        # Choices on CharField and IntegerField
        f = ArticleForm()
        with self.assertRaises(ValidationError):
            f.fields['status'].clean('42')

        f = ArticleStatusForm()
        with self.assertRaises(ValidationError):
            f.fields['status'].clean('z') 
Example #16
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_setattr_raises_validation_error_field_specific(self):
        """
        A model ValidationError using the dict form should put the error
        message into the correct key of form.errors.
        """
        form_class = modelform_factory(model=StrictAssignmentFieldSpecific, fields=['title'])
        form = form_class(data={'title': 'testing setattr'}, files=None)
        # This line turns on the ValidationError; it avoids the model erroring
        # when its own __init__() is called when creating form.instance.
        form.instance._should_error = True
        self.assertFalse(form.is_valid())
        self.assertEqual(form.errors, {
            'title': ['Cannot set attribute', 'This field cannot be blank.']
        }) 
Example #17
Source File: tasks.py    From polemarch with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_execute_args_setter(self):
        with self.assertRaises(ValidationError):
            self.testHistory.execute_args = "something" 
Example #18
Source File: test_modelchoicefield.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_basics(self):
        f = forms.ModelChoiceField(Category.objects.all())
        self.assertEqual(list(f.choices), [
            ('', '---------'),
            (self.c1.pk, 'Entertainment'),
            (self.c2.pk, 'A test'),
            (self.c3.pk, 'Third'),
        ])
        with self.assertRaises(ValidationError):
            f.clean('')
        with self.assertRaises(ValidationError):
            f.clean(None)
        with self.assertRaises(ValidationError):
            f.clean(0)

        # Invalid types that require TypeError to be caught.
        with self.assertRaises(ValidationError):
            f.clean([['fail']])
        with self.assertRaises(ValidationError):
            f.clean([{'foo': 'bar'}])

        self.assertEqual(f.clean(self.c2.id).name, 'A test')
        self.assertEqual(f.clean(self.c3.id).name, 'Third')

        # Add a Category object *after* the ModelChoiceField has already been
        # instantiated. This proves clean() checks the database during clean()
        # rather than caching it at  instantiation time.
        c4 = Category.objects.create(name='Fourth', url='4th')
        self.assertEqual(f.clean(c4.id).name, 'Fourth')

        # Delete a Category object *after* the ModelChoiceField has already been
        # instantiated. This proves clean() checks the database during clean()
        # rather than caching it at instantiation time.
        Category.objects.get(url='4th').delete()
        msg = "['Select a valid choice. That choice is not one of the available choices.']"
        with self.assertRaisesMessage(ValidationError, msg):
            f.clean(c4.id) 
Example #19
Source File: test_modelchoicefield.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_choices(self):
        f = forms.ModelChoiceField(Category.objects.filter(pk=self.c1.id), required=False)
        self.assertIsNone(f.clean(''))
        self.assertEqual(f.clean(str(self.c1.id)).name, 'Entertainment')
        with self.assertRaises(ValidationError):
            f.clean('100')

        # len() can be called on choices.
        self.assertEqual(len(f.choices), 2)

        # queryset can be changed after the field is created.
        f.queryset = Category.objects.exclude(name='Third')
        self.assertEqual(list(f.choices), [
            ('', '---------'),
            (self.c1.pk, 'Entertainment'),
            (self.c2.pk, 'A test'),
        ])
        self.assertEqual(f.clean(self.c2.id).name, 'A test')
        with self.assertRaises(ValidationError):
            f.clean(self.c3.id)

        # Choices can be iterated repeatedly.
        gen_one = list(f.choices)
        gen_two = f.choices
        self.assertEqual(gen_one[2], (self.c2.pk, 'A test'))
        self.assertEqual(list(gen_two), [
            ('', '---------'),
            (self.c1.pk, 'Entertainment'),
            (self.c2.pk, 'A test'),
        ])

        # Overriding label_from_instance() to print custom labels.
        f.queryset = Category.objects.all()
        f.label_from_instance = lambda obj: 'category ' + str(obj)
        self.assertEqual(list(f.choices), [
            ('', '---------'),
            (self.c1.pk, 'category Entertainment'),
            (self.c2.pk, 'category A test'),
            (self.c3.pk, 'category Third'),
        ]) 
Example #20
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_exclude_and_validation(self):
        # This Price instance generated by this form is not valid because the quantity
        # field is required, but the form is valid because the field is excluded from
        # the form. This is for backwards compatibility.
        class PriceFormWithoutQuantity(forms.ModelForm):
            class Meta:
                model = Price
                exclude = ('quantity',)

        form = PriceFormWithoutQuantity({'price': '6.00'})
        self.assertTrue(form.is_valid())
        price = form.save(commit=False)
        msg = "{'quantity': ['This field cannot be null.']}"
        with self.assertRaisesMessage(ValidationError, msg):
            price.full_clean()

        # The form should not validate fields that it doesn't contain even if they are
        # specified using 'fields', not 'exclude'.
        class PriceFormWithoutQuantity(forms.ModelForm):
            class Meta:
                model = Price
                fields = ('price',)
        form = PriceFormWithoutQuantity({'price': '6.00'})
        self.assertTrue(form.is_valid())

        # The form should still have an instance of a model that is not complete and
        # not saved into a DB yet.
        self.assertEqual(form.instance.price, Decimal('6.00'))
        self.assertIsNone(form.instance.quantity)
        self.assertIsNone(form.instance.pk) 
Example #21
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_model_multiple_choice_required_false(self):
        f = forms.ModelMultipleChoiceField(Category.objects.all(), required=False)
        self.assertIsInstance(f.clean([]), EmptyQuerySet)
        self.assertIsInstance(f.clean(()), EmptyQuerySet)
        with self.assertRaises(ValidationError):
            f.clean(['0'])
        with self.assertRaises(ValidationError):
            f.clean([str(self.c3.id), '0'])
        with self.assertRaises(ValidationError):
            f.clean([str(self.c1.id), '0'])

        # queryset can be changed after the field is created.
        f.queryset = Category.objects.exclude(name='Third')
        self.assertEqual(list(f.choices), [
            (self.c1.pk, 'Entertainment'),
            (self.c2.pk, "It's a test")])
        self.assertQuerysetEqual(f.clean([self.c2.id]), ["It's a test"])
        with self.assertRaises(ValidationError):
            f.clean([self.c3.id])
        with self.assertRaises(ValidationError):
            f.clean([str(self.c2.id), str(self.c3.id)])

        f.queryset = Category.objects.all()
        f.label_from_instance = lambda obj: "multicategory " + str(obj)
        self.assertEqual(list(f.choices), [
            (self.c1.pk, 'multicategory Entertainment'),
            (self.c2.pk, "multicategory It's a test"),
            (self.c3.pk, 'multicategory Third')]) 
Example #22
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_clean_false_required(self):
        """
        If the ``clean`` method on a required FileField receives False as the
        data, it has the same effect as None: initial is returned if non-empty,
        otherwise the validation catches the lack of a required value.
        """
        f = forms.FileField(required=True)
        self.assertEqual(f.clean(False, 'initial'), 'initial')
        with self.assertRaises(ValidationError):
            f.clean(False) 
Example #23
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_choices_type(self):
        # Choices on CharField and IntegerField
        f = ArticleForm()
        with self.assertRaises(ValidationError):
            f.fields['status'].clean('42')

        f = ArticleStatusForm()
        with self.assertRaises(ValidationError):
            f.fields['status'].clean('z') 
Example #24
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_setattr_raises_validation_error_field_specific(self):
        """
        A model ValidationError using the dict form should put the error
        message into the correct key of form.errors.
        """
        form_class = modelform_factory(model=StrictAssignmentFieldSpecific, fields=['title'])
        form = form_class(data={'title': 'testing setattr'}, files=None)
        # This line turns on the ValidationError; it avoids the model erroring
        # when its own __init__() is called when creating form.instance.
        form.instance._should_error = True
        self.assertFalse(form.is_valid())
        self.assertEqual(form.errors, {
            'title': ['Cannot set attribute', 'This field cannot be blank.']
        }) 
Example #25
Source File: test_modelchoicefield.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_basics(self):
        f = forms.ModelChoiceField(Category.objects.all())
        self.assertEqual(list(f.choices), [
            ('', '---------'),
            (self.c1.pk, 'Entertainment'),
            (self.c2.pk, 'A test'),
            (self.c3.pk, 'Third'),
        ])
        with self.assertRaises(ValidationError):
            f.clean('')
        with self.assertRaises(ValidationError):
            f.clean(None)
        with self.assertRaises(ValidationError):
            f.clean(0)

        # Invalid types that require TypeError to be caught.
        with self.assertRaises(ValidationError):
            f.clean([['fail']])
        with self.assertRaises(ValidationError):
            f.clean([{'foo': 'bar'}])

        self.assertEqual(f.clean(self.c2.id).name, 'A test')
        self.assertEqual(f.clean(self.c3.id).name, 'Third')

        # Add a Category object *after* the ModelChoiceField has already been
        # instantiated. This proves clean() checks the database during clean()
        # rather than caching it at  instantiation time.
        c4 = Category.objects.create(name='Fourth', url='4th')
        self.assertEqual(f.clean(c4.id).name, 'Fourth')

        # Delete a Category object *after* the ModelChoiceField has already been
        # instantiated. This proves clean() checks the database during clean()
        # rather than caching it at instantiation time.
        Category.objects.get(url='4th').delete()
        msg = "['Select a valid choice. That choice is not one of the available choices.']"
        with self.assertRaisesMessage(ValidationError, msg):
            f.clean(c4.id) 
Example #26
Source File: test_modelchoicefield.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_choices(self):
        f = forms.ModelChoiceField(Category.objects.filter(pk=self.c1.id), required=False)
        self.assertIsNone(f.clean(''))
        self.assertEqual(f.clean(str(self.c1.id)).name, 'Entertainment')
        with self.assertRaises(ValidationError):
            f.clean('100')

        # len() can be called on choices.
        self.assertEqual(len(f.choices), 2)

        # queryset can be changed after the field is created.
        f.queryset = Category.objects.exclude(name='Third')
        self.assertEqual(list(f.choices), [
            ('', '---------'),
            (self.c1.pk, 'Entertainment'),
            (self.c2.pk, 'A test'),
        ])
        self.assertEqual(f.clean(self.c2.id).name, 'A test')
        with self.assertRaises(ValidationError):
            f.clean(self.c3.id)

        # Choices can be iterated repeatedly.
        gen_one = list(f.choices)
        gen_two = f.choices
        self.assertEqual(gen_one[2], (self.c2.pk, 'A test'))
        self.assertEqual(list(gen_two), [
            ('', '---------'),
            (self.c1.pk, 'Entertainment'),
            (self.c2.pk, 'A test'),
        ])

        # Overriding label_from_instance() to print custom labels.
        f.queryset = Category.objects.all()
        f.label_from_instance = lambda obj: 'category ' + str(obj)
        self.assertEqual(list(f.choices), [
            ('', '---------'),
            (self.c1.pk, 'category Entertainment'),
            (self.c2.pk, 'category A test'),
            (self.c3.pk, 'category Third'),
        ]) 
Example #27
Source File: utils.py    From personfinder with Apache License 2.0 5 votes vote down vote up
def validate_email(email):
    """Validates an email address, returning True on correct,
    False on incorrect, None on empty string."""
    # Note that google.appengine.api.mail.is_email_valid() is unhelpful;
    # it checks only for the empty string
    if not email:
        return None
    try:
        EMAIL_VALIDATOR(email)
        return True
    except ValidationError:
        return False 
Example #28
Source File: utils.py    From personfinder with Apache License 2.0 5 votes vote down vote up
def sanitize_urls(record):
    """Clean up URLs to protect against XSS.

    We check URLs submitted through Person Finder, but bad data might come in
    through the API.
    """
    url_validator = URLValidator(schemes=['http', 'https'])
    # Single-line URLs.
    for field in ['photo_url', 'source_url']:
        url = getattr(record, field, None)
        if not url:
            continue
        try:
            url_validator(url)
        except ValidationError:
            setattr(record, field, None)
    # Multi-line URLs.
    for field in ['profile_urls']:
        urls = (getattr(record, field, None) or '').splitlines()
        sanitized_urls = []
        for url in urls:
            if url:
                try:
                    url_validator(url)
                    sanitized_urls.append(url)
                except ValidationError:
                    logging.warning(
                        'Unsanitary URL in database on %s' % record.record_id)
        if len(urls) != len(sanitized_urls):
            setattr(record, field, '\n'.join(sanitized_urls)) 
Example #29
Source File: ascii.py    From coding-events with MIT License 5 votes vote down vote up
def validate_ascii_text(text):
    "Check if text is a text with ASCII-only characters."

    if not is_ascii(text):
        raise ValidationError(
            'Please use only ASCII (Latin) letters.',
            code='invalid',
            params={'text': text},
        ) 
Example #30
Source File: user.py    From zing with GNU General Public License v3.0 5 votes vote down vote up
def test_verify_user_duplicate_email(trans_member, member):
    """Test verifying user using `verify_user` function"""

    # trans_member steals member's email
    trans_member.email = member.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)