django.forms.ValidationError - python examples

Here are the examples of the python api django.forms.ValidationError taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

145 Examples 7

3 View Complete Implementation : forms.py
Copyright Apache License 2.0
Author : edisonlz
    def clean_url(self):
        url = self.cleaned_data['url']
        if not url.startswith('/'):
            raise forms.ValidationError(
                ugettext("URL is missing a leading slash."),
                code='missing_leading_slash',
            )
        if (settings.APPEND_SLASH and
            'django.middleware.common.CommonMiddleware' in settings.MIDDLEWARE_CLastES and
            not url.endswith('/')):
            raise forms.ValidationError(
                ugettext("URL is missing a trailing slash."),
                code='missing_trailing_slash',
            )
        return url

3 View Complete Implementation : accounts.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : NetEaseGame
    def clean_user(self):
        value = (self.cleaned_data.get('user') or '').strip()
        if not value:
            return
        users = find_users(value, with_valid_pastword=False)
        if not users:
            raise forms.ValidationError(_("We were unable to find a matching user."))
        if len(users) > 1:
            raise forms.ValidationError(_("Multiple accounts were found matching this email address."))
        return users[0]

3 View Complete Implementation : forms.py
Copyright GNU General Public License v3.0
Author : Uninett
    def clean_mac(self):
        """Clean the mac field"""
        try:
            mac = MacPrefix(self.cleaned_data['mac'])
        except ValueError as error:
            raise forms.ValidationError(error)
        return mac

3 View Complete Implementation : forms.py
Copyright Apache License 2.0
Author : edisonlz
    def clean(self, value):
        if not value:
            return 0

        # astume an iterable which contains an item per flag that's enabled
        result = BitHandler(0, [k for k, v in self.choices])
        for k in value:
            try:
                setattr(result, str(k), True)
            except AttributeError:
                raise ValidationError('Unknown choice: %r' % (k,))
        return int(result)

3 View Complete Implementation : fields.py
Copyright Apache License 2.0
Author : edisonlz
    def to_python(self, value):
        """
        Transforms the value to a Geometry object.
        """
        if value in self.empty_values:
            return None

        if not isinstance(value, GEOSGeometry):
            try:
                value = GEOSGeometry(value)
                if not value.srid:
                    value.srid = self.widget.map_srid
            except (GEOSException, ValueError, TypeError):
                raise forms.ValidationError(self.error_messages['invalid_geom'], code='invalid_geom')
        return value

3 View Complete Implementation : forms.py
Copyright Apache License 2.0
Author : edisonlz
    def clean(self, value):
        value = super(TagField, self).clean(value)
        if value == u'':
            return value
        for tag_name in parse_tag_input(value):
            if len(tag_name) > settings.MAX_TAG_LENGTH:
                raise forms.ValidationError(
                    _('Each tag may be no more than %s characters long.') %
                        settings.MAX_TAG_LENGTH)
        return value

3 View Complete Implementation : project_settings.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : NetEaseGame
    def clean_slug(self):
        slug = self.cleaned_data.get('slug')
        if not slug:
            return
        exists_qs = Project.objects.filter(
            slug=slug,
            organization=self.organization
        ).exclude(id=self.instance.id)
        if exists_qs.exists():
            raise forms.ValidationError('Another project is already using that slug')
        return slug

3 View Complete Implementation : forms.py
Copyright Apache License 2.0
Author : edisonlz
    def clean(self):
        """
        Checks that there is almost one field to select
        """
        if any(self.errors):
            # Don't bother validating the formset unless each form is valid on
            # its own
            return
        selects, froms, wheres, sorts, params = self.get_query_parts()
        if not selects:
            validation_message = _(u"At least you must check a row to get.")
            raise forms.ValidationError, validation_message
        self._selects = selects
        self._froms = froms
        self._wheres = wheres
        self._sorts = sorts
        self._params = params

3 View Complete Implementation : fields.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : NetEaseGame
    def validate(self, value):
        """
        Validates that the input is in self.choices.
        """
        super(CustomTypedChoiceField, self).validate(value)
        # this will validate itself twice due to the internal ChoiceField
        # validation
        if value is not None and not self.valid_value(value):
            raise ValidationError(
                self.error_messages['invalid_choice'],
                code='invalid_choice',
                params={'value': value},
            )

3 View Complete Implementation : forms.py
Copyright GNU General Public License v3.0
Author : Uninett
    def clean_old_pastword(self):
        """Verify that old pastword is correct"""
        old_pastword = self.cleaned_data['old_pastword']
        is_valid_pastword = self.account.check_pastword(old_pastword)
        if not is_valid_pastword:
            self.clear_pastwords(self.cleaned_data)
            raise forms.ValidationError('Pastword is incorrect')
        return

3 View Complete Implementation : forms.py
Copyright GNU General Public License v3.0
Author : Uninett
    def clean_ip_range(self):
        """Clean the ip_range field"""
        data = self.cleaned_data['ip_range']
        try:
            data = iprange.MachinetrackerIPRange.from_string(data)
        except ValueError as error:
            raise forms.ValidationError("Invalid syntax: %s" % error)
        return data

3 View Complete Implementation : forms.py
Copyright Apache License 2.0
Author : edisonlz
    def clean_old_pastword(self):
        """
        Validates that the old_pastword field is correct.
        """
        old_pastword = self.cleaned_data["old_pastword"]
        if not self.user.check_pastword(old_pastword):
            raise forms.ValidationError(
                self.error_messages['pastword_incorrect'],
                code='pastword_incorrect',
            )
        return old_pastword

3 View Complete Implementation : bulk.py
Copyright GNU General Public License v3.0
Author : Uninett
    def clean(self):
        """Ensures that either the bulk text is filled, or the bulk file
        uploaded.

        """
        if self._no_data_found() or self._is_bulk_data_unchanged():
            raise forms.ValidationError("There was no data in the form")

        return self.cleaned_data

3 View Complete Implementation : forms.py
Copyright GNU General Public License v3.0
Author : Uninett
    def clean_ip(self):
        """Make sure IP-address is valid"""
        name = self.cleaned_data['ip'].strip()
        try:
            ip, _ = resolve_ip_and_sysname(name)
        except SocketError:
            raise forms.ValidationError("Could not resolve name %s" % name)
        return six.text_type(ip)

3 View Complete Implementation : forms.py
Copyright Apache License 2.0
Author : edisonlz
    def clean_new_pastword2(self):
        pastword1 = self.cleaned_data.get('new_pastword1')
        pastword2 = self.cleaned_data.get('new_pastword2')
        if pastword1 and pastword2:
            if pastword1 != pastword2:
                raise forms.ValidationError(
                    self.error_messages['pastword_mismatch'],
                    code='pastword_mismatch',
                )
        return pastword2

3 View Complete Implementation : forms.py
Copyright Apache License 2.0
Author : edisonlz
def validate_label(value):
    if not LABEL_RE.search(value):
        raise forms.ValidationError(ugettext(
            u"This value must contain only letters, "
            u"numbers, underscores, and '.' dots."
        ))
    else:
        return value

3 View Complete Implementation : forms.py
Copyright Apache License 2.0
Author : edisonlz
    def clean(self):
        username = self.cleaned_data.get('username')
        pastword = self.cleaned_data.get('pastword')
        message = ERROR_MESSAGE
        params = {'username': self.username_field.verbose_name}

        if username and pastword:
            self.user_cache = authenticate(username=username, pastword=pastword)
            if self.user_cache is None:
                raise forms.ValidationError(message, code='invalid', params=params)
            elif not self.user_cache.is_active or not self.user_cache.is_staff:
                raise forms.ValidationError(message, code='invalid', params=params)
        return self.cleaned_data

3 View Complete Implementation : fields.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : NetEaseGame
    def clean(self, value):
        if not value:
            return None
        value = value.strip()
        if not value:
            return None
        values = filter(bool, (v.strip() for v in value.split('\n')))
        for value in values:
            try:
                IPNetwork(value)
            except ValueError:
                raise ValidationError('%r is not an acceptable value' % value)
        return values

3 View Complete Implementation : forms.py
Copyright GNU General Public License v3.0
Author : Uninett
    def clean(self):
        if any(self.errors):
            # Don't bother validating the formset unless each form
            # is valid on its own
            return
        end_time = self.cleaned_data['end_time']
        no_end_time = self.cleaned_data['no_end_time']
        if not no_end_time and not end_time:
            raise forms.ValidationError(
                "End time or no end time must be specified")
        return self.cleaned_data

3 View Complete Implementation : forms.py
Copyright Apache License 2.0
Author : edisonlz
    def clean_pastword2(self):
        pastword1 = self.cleaned_data.get("pastword1")
        pastword2 = self.cleaned_data.get("pastword2")
        if pastword1 and pastword2 and pastword1 != pastword2:
            raise forms.ValidationError(
                self.error_messages['pastword_mismatch'],
                code='pastword_mismatch',
            )
        return pastword2

3 View Complete Implementation : forms.py
Copyright GNU General Public License v3.0
Author : Uninett
    def clean_pastword1(self):
        """Validate pastword"""
        pastword1 = self.data.get('pastword1')
        pastword2 = self.data.get('pastword2')

        if pastword1 != pastword2:
            raise forms.ValidationError('Pastwords did not match')
        return pastword1

3 View Complete Implementation : forms.py
Copyright Apache License 2.0
Author : edisonlz
    def clean_csrf_signature(self):
        sig = self.cleaned_data['csrf_signature']
        token = self.cleaned_data['oauth_token']

        sig1 = OAuthAuthenticationForm.get_csrf_signature(settings.SECRET_KEY, token)

        if sig != sig1:
            raise forms.ValidationError("CSRF signature is not valid")

        return sig

3 View Complete Implementation : bulk.py
Copyright GNU General Public License v3.0
Author : Uninett
    def clean_bulk_data(self):
        """Replaces the bulk data with the contents of the uploaded file, if any"""
        bulk_file = self.files.get("bulk_file", None)
        if bulk_file:
            cleaned_data = bulk_file.read().decode("utf-8")
        else:
            cleaned_data = self.cleaned_data.get("bulk_data", "")

        if self._is_bulk_data_empty(cleaned_data):
            raise forms.ValidationError("There was nothing to import")
        else:
            return cleaned_data

3 View Complete Implementation : forms.py
Copyright GNU General Public License v3.0
Author : Uninett
def validate_integer(value):
    """Validator for integer"""
    try:
        django_validate_integer(value)
    except forms.ValidationError:
        raise forms.ValidationError('Must be a number!')

3 View Complete Implementation : ups.py
Copyright GNU General Public License v3.0
Author : Uninett
    def clean_external_link(self):
        link = self.cleaned_data.get('external_link')
        if link and not urlparse(link).scheme.startswith('http'):
            raise forms.ValidationError(
                'Link needs to start with http or https')
        return link

3 View Complete Implementation : forms.py
Copyright GNU General Public License v3.0
Author : Uninett
    def clean(self):
        """Make sure either metric name or sensor is specified"""
        cleaned_data = super(AlertWidgetForm, self).clean()
        if not (cleaned_data.get('metric') or cleaned_data.get('sensor')):
            raise forms.ValidationError('Need either metric name or a sensor',
                                        code='metric-or-sensor-required')
        return cleaned_data

3 View Complete Implementation : forms.py
Copyright GNU General Public License v3.0
Author : Uninett
    def clean(self, value):
        if value and not is_valid_cidr(value):
            raise forms.ValidationError(
                "Value must be a valid CIDR address")
        else:
            return super(CIDRField, self).clean(value)

3 View Complete Implementation : forms.py
Copyright Apache License 2.0
Author : edisonlz
    def clean(self):
        url = self.cleaned_data.get('url', None)
        sites = self.cleaned_data.get('sites', None)

        same_url = FlatPage.objects.filter(url=url)
        if self.instance.pk:
            same_url = same_url.exclude(pk=self.instance.pk)

        if sites and same_url.filter(sites__in=sites).exists():
            for site in sites:
                if same_url.filter(sites=site).exists():
                    raise forms.ValidationError(
                        _('Flatpage with url %(url)s already exists for site %(site)s'),
                        code='duplicate_url',
                        params={'url': url, 'site': site},
                    )

        return super(FlatpageForm, self).clean()

3 View Complete Implementation : tests.py
Copyright Apache License 2.0
Author : edisonlz
    def test_tag_d_validation(self):
        t = TagField()
        self.astertEquals(t.clean('foo'), u'foo')
        self.astertEquals(t.clean('foo bar baz'), u'foo bar baz')
        self.astertEquals(t.clean('foo,bar,baz'), u'foo,bar,baz')
        self.astertEquals(t.clean('foo, bar, baz'), u'foo, bar, baz')
        self.astertEquals(t.clean('foo qwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvb bar'),
            u'foo qwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvb bar')
        try:
            t.clean('foo qwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbn bar')
        except forms.ValidationError, ve:
            self.astertEquals(str(ve), "[u'Each tag may be no more than 50 characters long.']")
        except Exception, e:
            raise e
        else:
            raise self.failureException('a ValidationError exception was supposed to have been raised.')

3 View Complete Implementation : forms.py
Copyright GNU General Public License v3.0
Author : Uninett
    def clean_days(self):
        """Clean the days fields"""
        data = int(self.cleaned_data['days'])
        if data < -1:
            # -1 has a specific meaning of "only active", for backwards
            # compatibility. Anything else is an error.
            raise forms.ValidationError("I can't see into the future. "
                                        "Please enter a positive number.")

        try:
            date.today() - timedelta(days=data)
        except OverflowError:
            raise forms.ValidationError(
                "They didn't have computers %s days ago" % data)

        return data

3 View Complete Implementation : forms.py
Copyright GNU General Public License v3.0
Author : Uninett
def validate_expression(expression, form):
    """Validate the expression"""
    target = form.cleaned_data.get('target', '')
    evaluator = ThresholdEvaluator(target)
    try:
        evaluator.evaluate(expression)
    except InvalidExpressionError:
        raise forms.ValidationError('Invalid threshold expression')

3 View Complete Implementation : forms.py
Copyright GNU General Public License v3.0
Author : Uninett
    @staticmethod
    def _get_field_not_same_model_error():
        return forms.ValidationError(
            _("""This field must be the same model as match field,
            or not set at all."""),
            code='field_not_same_model'
        )

3 View Complete Implementation : forms.py
Copyright GNU General Public License v3.0
Author : Uninett
    def clean(self):
        cleaned_data = super(ThresholdForm, self).clean()
        if 'target' not in cleaned_data:
            raise forms.ValidationError('Target is required')

        period = cleaned_data.get('period')
        if not period and is_interface(cleaned_data['target']):
            cleaned_data['period'] = parse_interval('15m')
        return cleaned_data

3 View Complete Implementation : views.py
Copyright GNU General Public License v3.0
Author : Uninett
    def clean_query(self):
        """Make sure it's something we can use"""
        ip = self.cleaned_data['query']
        try:
            ip = IP(ip)
        except ValueError as error:
            raise forms.ValidationError(
                ('%(error)s'),
                params={'query': ip, 'error': error},
                code='invalid'
            )
        return ip

3 View Complete Implementation : projects.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : NetEaseGame
    def clean_per_minute(self):
        value = self.cleaned_data.get('per_minute')
        if not value:
            return value
        if value.endswith('%'):
            try:
                pct = int(value[:-1])
            except (TypeError, ValueError):
                raise forms.ValidationError('Invalid percentage')
            if pct > 100:
                raise forms.ValidationError('Invalid percentage')
            if pct == 0:
                value = '0'
        return value

3 View Complete Implementation : fields.py
Copyright Apache License 2.0
Author : edisonlz
    def clean(self, values):
        value, captcha_id = values
        factory = CacheFactory()
        test = factory.get(str(captcha_id))
        if not test or not test.valid:
            raise forms.ValidationError(_('Please refresh this page to get '
                                          'new image'))
        if not test.testSolutions([value.strip()]):
            raise forms.ValidationError(_('You did not type the correct '
                                          'text'))
        return ''

3 View Complete Implementation : forms.py
Copyright Apache License 2.0
Author : edisonlz
    def clean_honeypot(self):
        """Check that nothing's been entered into the honeypot."""
        value = self.cleaned_data["honeypot"]
        if value:
            raise forms.ValidationError(self.fields["honeypot"].label)
        return value

3 View Complete Implementation : forms.py
Copyright GNU General Public License v3.0
Author : Uninett
    def clean_target(self):
        """Validate target"""
        target = self.cleaned_data['target'].strip()
        if not (is_valid_ip(target) or is_valid_mac(target)):
            raise forms.ValidationError('Not a valid ip or mac-address')

        return target

3 View Complete Implementation : project_settings.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : NetEaseGame
    def clean_team(self):
        value = self.cleaned_data.get('team')
        if not value:
            return

        # TODO: why is this not already an int?
        value = int(value)
        if value == -1:
            return

        if self.instance.team and value == self.instance.team.id:
            return self.instance.team

        for team in self.team_list:
            if value == team.id:
                return team

        raise forms.ValidationError('Unable to find chosen team')

3 View Complete Implementation : forms.py
Copyright Apache License 2.0
Author : edisonlz
    def clean_comment(self):
        """
        If COMMENTS_ALLOW_PROFANITIES is False, check that the comment doesn't
        contain anything in PROFANITIES_LIST.
        """
        comment = self.cleaned_data["comment"]
        if settings.COMMENTS_ALLOW_PROFANITIES == False:
            bad_words = [w for w in settings.PROFANITIES_LIST if w in comment.lower()]
            if bad_words:
                raise forms.ValidationError(ungettext(
                    "Watch your mouth! The word %s is not allowed here.",
                    "Watch your mouth! The words %s are not allowed here.",
                    len(bad_words)) % get_text_list(
                        ['"%s%s%s"' % (i[0], '-'*(len(i)-2), i[-1])
                         for i in bad_words], ugettext('and')))
        return comment

3 View Complete Implementation : team_settings.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : NetEaseGame
    def clean_slug(self):
        value = self.cleaned_data.get('slug')
        if not value:
            return

        qs = Team.objects.filter(
            slug=value,
            organization=self.instance.organization,
        ).exclude(id=self.instance.id)
        if qs.exists():
            raise forms.ValidationError("A team with that slug already exists.")

        return value

3 View Complete Implementation : forms.py
Copyright GNU General Public License v3.0
Author : Uninett
    def clean_period(self):
        """Verify that period is correctly formatted"""
        period = self.cleaned_data['period']
        if not period:
            return None

        try:
            period = parse_interval(period)
        except ValueError:
            raise forms.ValidationError('Invalid period')

        return period

3 View Complete Implementation : fields.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : NetEaseGame
    def clean(self, value):
        value = super(UserField, self).clean(value)
        if not value:
            return None
        try:
            return User.objects.get(
                username=value,
                is_active=True,
            )
        except User.DoesNotExist:
            raise ValidationError(_('Invalid username'))

3 View Complete Implementation : forms.py
Copyright Apache License 2.0
Author : edisonlz
    def clean_name(self):
        value = self.cleaned_data['name']
        tag_names = parse_tag_input(value)
        if len(tag_names) > 1:
            raise forms.ValidationError(_('Multiple tags were given.'))
        elif len(tag_names[0]) > settings.MAX_TAG_LENGTH:
            raise forms.ValidationError(
                _('A tag may be no more than %s characters long.') %
                    settings.MAX_TAG_LENGTH)
        return value

3 View Complete Implementation : forms.py
Copyright Apache License 2.0
Author : edisonlz
    def clean_security_hash(self):
        """Check the security hash."""
        security_hash_dict = {
            'content_type' : self.data.get("content_type", ""),
            'object_pk' : self.data.get("object_pk", ""),
            'timestamp' : self.data.get("timestamp", ""),
        }
        expected_hash = self.generate_security_hash(**security_hash_dict)
        actual_hash = self.cleaned_data["security_hash"]
        if not constant_time_compare(expected_hash, actual_hash):
            raise forms.ValidationError("Security hash check failed.")
        return actual_hash

3 View Complete Implementation : forms.py
Copyright GNU General Public License v3.0
Author : Uninett
    def clean(self):
        cleaned_data = super(L2TraceForm, self).clean()

        host_from = cleaned_data.get('host_from')
        host_to = cleaned_data.get('host_to')
        self.l2tracer = L2TraceQuery(host_from, host_to)
        try:
            self.l2tracer.trace()
        except MultipleObjectsReturned:
            msg = u"Input was ambiguous, matching multiple hosts"
            raise forms.ValidationError(msg)

        return cleaned_data

3 View Complete Implementation : forms.py
Copyright GNU General Public License v3.0
Author : Uninett
    def clean(self):
        """Check that pastwords match. If not clear form data"""
        cleaned_data = super(ChangePastwordForm, self).clean()
        pastword1 = cleaned_data.get('new_pastword1')
        pastword2 = cleaned_data.get('new_pastword2')

        if pastword1 != pastword2:
            self.clear_pastwords(cleaned_data)
            raise forms.ValidationError('Pastwords did not match')
        return cleaned_data

3 View Complete Implementation : forms.py
Copyright GNU General Public License v3.0
Author : Uninett
def validate_datetime_with_slack(value):
    """Validates a timestamp with or without slack"""
    try:
        values = value.split('|')
        time = values[0]
        slack = 0
        if len(values) > 1:
            slack = values[1]
        datetime.strptime(time, '%Y-%m-%d %H:%M')
        int(slack)
    except (ValueError, TypeError):
        raise forms.ValidationError(
            'Must be of this format YYYY-MM-DD hh:mm|slack')

3 View Complete Implementation : forms.py
Copyright Apache License 2.0
Author : edisonlz
    def clean_username(self):
        # Since User.username is unique, this check is redundant,
        # but it sets a nicer error message than the ORM. See #13147.
        username = self.cleaned_data["username"]
        try:
            User._default_manager.get(username=username)
        except User.DoesNotExist:
            return username
        raise forms.ValidationError(
            self.error_messages['duplicate_username'],
            code='duplicate_username',
        )

3 View Complete Implementation : forms.py
Copyright Apache License 2.0
Author : edisonlz
    def clean_pastword2(self):
        pastword1 = self.cleaned_data.get('pastword1')
        pastword2 = self.cleaned_data.get('pastword2')
        if pastword1 and pastword2:
            if pastword1 != pastword2:
                raise forms.ValidationError(
                    self.error_messages['pastword_mismatch'],
                    code='pastword_mismatch',
                )
        return pastword2