django.forms.ValidationError

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.

200 Examples 7

Example 1

Project: django-user-accounts
Source File: forms.py
View license
    def clean_email(self):
        value = self.cleaned_data["email"]
        if self.initial.get("email") == value:
            return value
        qs = EmailAddress.objects.filter(email__iexact=value)
        if not qs.exists() or not settings.ACCOUNT_EMAIL_UNIQUE:
            return value
        raise forms.ValidationError(_("A user is registered with this email address."))

Example 2

Project: pretix
Source File: __init__.py
View license
    def clean(self, *args, **kwargs):
        data = super().clean(*args, **kwargs)
        if data:
            filename = data.name
            ext = os.path.splitext(filename)[1]
            ext = ext.lower()
            if ext not in self.ext_whitelist:
                raise forms.ValidationError(_("Filetype not allowed!"))
        return data

Example 3

Project: pycon
Source File: forms.py
View license
    def clean_web_description(self):
        value = self.cleaned_data['web_description']
        word_count = len(re.findall(r"[-\w']+", value.lower()))
        if word_count > 100:
            raise forms.ValidationError(
                _(u"Your description is {} words long;"
                  " please reduce it to 100 or less.".format(word_count))
            )
        return value

Example 4

Project: wiggum
Source File: forms.py
View license
    def clean_email(self):
        email = self.cleaned_data['email']

        if User.objects.filter(email=email).exists():
            raise forms.ValidationError(
                self.error_messages['duplicate_email'],
                code='duplicate_email')
        return email

Example 5

Project: qualitio
Source File: forms.py
View license
    def clean_username(self):
        data = self.cleaned_data['username']

        try:
            user = auth.User.objects.get(username=data)
        except auth.User.DoesNotExist:
            raise forms.ValidationError("User does not exist.")

        return data

Example 6

Project: rapidpro
Source File: views.py
View license
    def clean_keyword(self):
        keyword = self.cleaned_data.get('keyword', '').strip()

        if keyword and not regex.match('^\w+$', keyword, flags=regex.UNICODE | regex.V0):
            raise forms.ValidationError(_("Keywords must be a single word containing only letter and numbers"))

        # make sure it is unique on this org
        org = self.user.get_org()
        if keyword and org:
            existing = Trigger.objects.filter(org=org, keyword__iexact=keyword, is_archived=False, is_active=True)
            if self.instance:
                existing = existing.exclude(pk=self.instance.pk)

            if existing:
                raise forms.ValidationError(_("Another active trigger uses this keyword, keywords must be unique"))

        return keyword.lower()

Example 7

Project: Resmin
Source File: forms.py
View license
    def clean(self):
        valid_slots = 0
        for slot in self.cleaned_data['slot_data']:
            if 'cPk' in slot:
                valid_slots += 1
                break

        if not valid_slots:
            raise forms.ValidationError("Story must have at least 1 image.")

        if not self.owner.is_authenticated():
            raise forms.ValidationError("You have to login to answer "
                                        "a question.")
        return self.cleaned_data

Example 8

Project: reviewboard
Source File: forms.py
View license
    def clean_attachment_history(self):
        """Validate that the specified file attachment history exists.

        Returns:
            reviewboard.attachments.models.FileAttachmentHistory:
            The history model.
        """
        history = self.cleaned_data['attachment_history']

        if (history is not None and
            not self.review_request.file_attachment_histories.filter(
                pk=history.pk).exists()):
            raise forms.ValidationError(
                'The FileAttachmentHistory provided is not part of this '
                'review request.')

        return history

Example 9

Project: villagescc
Source File: mail.py
View license
def is_valid_email(email):
    try:
        validate_email(email)
    except forms.ValidationError:
        return False
    else:
        return True

Example 10

Project: classic.rhizome.org
Source File: forms.py
View license
    def clean_double_verify(self):
        # anti-spam 
        double_verify = self.cleaned_data.get('double_verify')
        if double_verify:
            raise forms.ValidationError('This field must be empty')
        return double_verify

Example 11

Project: Django--an-app-at-a-time
Source File: forms.py
View license
    def confirm_login_allowed(self, user):
        if not user.is_active or not user.is_staff:
            raise forms.ValidationError(
                self.error_messages['invalid_login'],
                code='invalid_login',
                params={'username': self.username_field.verbose_name}
            )

Example 12

Project: snowy
Source File: __init__.py
View license
    def clean(self, value):
        resp = captcha.submit(value.get('challenge', None),
                              value.get('response', None),
                              settings.RECAPTCHA_PRIVATE_KEY,
                              value.get('ip', None))
        if not resp.is_valid:
            self.widget.attrs['error'] = resp.error_code 
            raise ValidationError(resp.error_code)

Example 13

Project: django-smuggler
Source File: forms.py
View license
    def validate(self, data):
        super(MultiFixtureField, self).validate(data)
        for upload in data:
            file_format = os.path.splitext(upload.name)[1][1:].lower()
            if file_format not in get_serializer_formats():
                raise forms.ValidationError(
                    _('Invalid file extension: .%(extension)s.') % {
                        'extension': file_format
                    })
        return data

Example 14

Project: dpaste
Source File: forms.py
View license
    def clean(self):
        """
        The `title` field is a hidden honeypot field. If its filled,
        this is likely spam.
        """
        if self.cleaned_data.get('title'):
            raise forms.ValidationError('This snippet was identified as Spam.')
        return self.cleaned_data

Example 15

View license
    def clean_password2(self):
        # Check that the two password entries match
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError("Passwords don't match")
        return password2

Example 16

Project: shuup
Source File: permissions.py
View license
    def clean_old_password(self):
        """
        Validates that the old_password field is correct.
        """
        old_password = self.cleaned_data["old_password"]
        if not self.changing_user.check_password(old_password):
            raise forms.ValidationError(
                _("Your old password was entered incorrectly. Please enter it again."),
                code='password_incorrect',
            )
        return old_password

Example 17

Project: django-page-cms
Source File: forms.py
View license
def unique_slug_required(form, slug):
    """Enforce a unique slug accross all pages and websistes."""

    if hasattr(form, 'instance') and form.instance.id:
        if Content.objects.exclude(page=form.instance).filter(
            body=slug, type="slug").count():
            raise forms.ValidationError(error_dict['another_page_error'])
    elif Content.objects.filter(body=slug, type="slug").count():
        raise forms.ValidationError(error_dict['another_page_error'])
    return slug

Example 18

Project: SmartElect
Source File: forms.py
View license
    def clean_name(self):
        """
        Ensure that there are no newlines in the name. This is not needed in the admin because you
        can't insert newlines in a CharField
        """
        if '\n' in self.cleaned_data['name']:
            raise forms.ValidationError(_('Newlines are not allowed.'))
        return self.cleaned_data['name']

Example 19

Project: SpisTresci
Source File: admin.py
View license
    def clean_username(self):
        username = self.cleaned_data["username"]
        try:
            User.objects.get(username=username)
        except User.DoesNotExist:
            return username
        raise forms.ValidationError(self.error_messages['duplicate_username'])

Example 20

Project: Bundestagger
Source File: forms.py
View license
    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

Example 21

Project: seriesly
Source File: forms.py
View license
    def clean_subkey(self):
        subkey = self.cleaned_data["subkey"]
        if subkey:
            try:
                subscription = Subscription.objects.get(subkey=subkey)
            except Subscription.DoesNotExist:
                raise forms.ValidationError("You don't have a valid Seriesly Subscription")
            else:
                self._subscription = subscription
        return subkey

Example 22

Project: mezzanine
Source File: forms.py
View license
    def clean(self):
        username = self.cleaned_data.get("username")
        username_or_email = Q(username=username) | Q(email=username)
        try:
            user = User.objects.get(username_or_email, is_active=True)
        except User.DoesNotExist:
            raise forms.ValidationError(
                             ugettext("Invalid username/email"))
        else:
            self._user = user
        return self.cleaned_data

Example 23

Project: django-userprofiles
Source File: forms.py
View license
    def clean_new_email(self):
        new_email = self.cleaned_data['new_email']

        user_emails = User.objects.filter(email__iexact=new_email).count()
        verification_emails = EmailVerification.objects.filter(
            new_email__iexact=new_email, is_expired=False).count()
        if user_emails + verification_emails > 0:
            raise forms.ValidationError(_(
                'This email address is already in use. Please supply a different email address.'))

        return new_email

Example 24

Project: web
Source File: forms.py
View license
    def clean_document(self):
        document = self.cleaned_data['document']
        if hasattr(document, '_size'):
            if document.size > settings.MAX_UPLOAD_SIZE:
                error_msg = 'Bitte Dateigrösse unter %s halten. Aktuelle Dateigrösse ist %s'
                sizes = filesizeformat(settings.MAX_UPLOAD_SIZE), filesizeformat(document._size)
                raise forms.ValidationError(error_msg % sizes)
        return document

Example 25

Project: confista
Source File: forms.py
View license
    def compress(self, data_list):
        if data_list:
            # Raise a validation error if time or date is empty
            # (possible if SplitDateTimeField has required=False).
            if data_list[0] in (None, '') or data_list[1] in (None, ''):
                raise forms.ValidationError(self.error_messages['invalid_time'])
            return time(int(data_list[0]),int(data_list[1]))
        return None

Example 26

Project: django-couchdb-utils
Source File: forms.py
View license
    def clean_email(self):
        email = self.cleaned_data.get('email', '')
        try:
            email_count = User.view('%s/users_by_email' % User._meta.app_label, key = email).count()
        except ResourceNotFound:
            email_count = 0
        if self.no_duplicate_emails and email_count > 0:
            raise forms.ValidationError, self.duplicate_email_error
        return email

Example 27

Project: gallery
Source File: forms.py
View license
    def clean_email(self):
        """
        Validates that the email address entered does not already exist in the
        database. We need to exclude the current email address otherwise
        this check will always fail.
        """
        email = self.cleaned_data['email']
        if User._default_manager.exclude(
                email=self.instance.email).filter(email=email):
            raise forms.ValidationError(self.error_messages['duplicate_email'])
        return email

Example 28

Project: wagtail
Source File: forms.py
View license
    def clean_foo(self):
        if 'foo' not in self.cleaned_data:
            return

        value = self.cleaned_data['foo']
        if value != 'bar':
            raise forms.ValidationError('Field foo must be bar')
        return value

Example 29

Project: treeio
Source File: forms.py
View license
    def clean_name(self):
        "Clean name"
        data = self.cleaned_data['name']
        existing = User.objects.filter(name=data).exclude(pk=self.instance.id)
        if existing:
            raise forms.ValidationError(
                _("User with username %s already exists.") % data)
        return data

Example 30

Project: daywatch
Source File: fields.py
View license
    def clean(self, value):
        if not value and self.required:
            raise forms.ValidationError(self.error_messages['required'])
        if value and self.max_choices and len(value) > self.max_choices:
            msg = 'You must select a maximum of choices.'
            raise forms.ValidationError(msg)
        return value

Example 31

Project: django-courriers
Source File: forms.py
View license
    def clean_email(self):
        email = self.cleaned_data['email']

        if not self.backend.subscribed(email, newsletter_list=self.newsletter_list):
            raise forms.ValidationError(_(u"You are not subscribed to this newsletter."))

        return email

Example 32

Project: django-safety
Source File: forms.py
View license
    def clean_new_password2(self):
        password2 = super(PasswordChangeForm, self).clean_new_password2()

        if self.user.check_password(password2):
            raise forms.ValidationError(
                self.error_messages['same_password'],
                code='same_password')

        return password2

Example 33

Project: django-dockit
Source File: fields.py
View license
    def to_python(self, value):
        if value in EMPTY_VALUES:
            return None
        try:
            value = self.queryset.get(pk=value)
        except (ValueError):#, self.queryset.model.DoesNotExist): #TODO catch the propr does not exist error
            raise ValidationError(self.error_messages['invalid_choice'])
        return value

Example 34

Project: explorer
Source File: forms.py
View license
    def clean_search_string(self):
        search_string = self.cleaned_data['search_string'].strip()
        # process possible Wallet Names
        if is_valid_wallet_name(search_string):
            return search_string

        # get rid of non alphanumerics
        search_string = re.sub(r'[^a-zA-Z0-9]+', '', search_string)

        if is_valid_hash(search_string) or is_valid_address(search_string) or is_valid_block_num(search_string):
            return search_string
        else:
            err_msg = _('Not a valid address, transaction hash, or block number')
            raise forms.ValidationError(err_msg)

Example 35

Project: django-timezones
Source File: tests.py
View license
    def test_forms_clean_bad_value(self):
        f = timezones.forms.TimeZoneField()
        try:
            f.clean("BAD VALUE")
        except forms.ValidationError, e:
            self.assertEqual(e.messages, ["Select a valid choice. BAD VALUE is not one of the available choices."])

Example 36

Project: django-password-reset
Source File: forms.py
View license
    def clean_username_or_email(self):
        username = self.cleaned_data['username_or_email']
        cleaner = getattr(self, 'get_user_by_%s' % self.label_key)
        self.cleaned_data['user'] = user = cleaner(username)

        user_is_active = getattr(user, 'is_active', True)
        recovery_only_active_users = getattr(settings,
                                             'RECOVER_ONLY_ACTIVE_USERS',
                                             False)

        if recovery_only_active_users and not user_is_active:
            raise forms.ValidationError(_("Sorry, inactive users can't "
                                        "recover their password."))

        return username

Example 37

Project: hello-social-registration
Source File: forms.py
View license
    def clean_username(self):
        try:
            user = User.objects.get(username__iexact=self.cleaned_data['username'])
        except User.DoesNotExist:
            return self.cleaned_data['username']
        raise forms.ValidationError('This username is already in use.')

Example 38

Project: cadasta-platform
Source File: forms.py
View license
    def clean_username(self):
        username = self.data.get('username')
        if username.lower() in settings.CADASTA_INVALID_ENTITY_NAMES:
            raise forms.ValidationError(
                _("Username cannot be “add” or “new”."))
        return username

Example 39

Project: django-flaggit
Source File: forms.py
View license
    def clean(self):
        content_type = self.cleaned_data['content_type']
        Model = content_type.model_class()
        id = self.cleaned_data['object_id']
        try:
            obj = Model.objects.get(id=id)
        except Model.DoesNotExist:
            raise forms.ValidationError("No such %s object with id %s" % (Model, id))
        
        self.cleaned_data['object'] = obj
        return self.cleaned_data

Example 40

Project: django-mysql
Source File: forms.py
View license
    def to_python(self, value):
        if value in self.empty_values:
            return None
        try:
            return json.loads(value)
        except ValueError:
            raise forms.ValidationError(
                self.error_messages['invalid'],
                code='invalid',
                params={'value': value},
            )

Example 41

Project: colab
Source File: forms.py
View license
    def clean_username(self):
        if not alnum_re.search(self.cleaned_data["username"]):
            raise forms.ValidationError(_("Usernames can only contain letters, numbers and underscores."))
        try:
            user = User.objects.get(username__iexact=self.cleaned_data["username"])
        except User.DoesNotExist:
            return self.cleaned_data["username"]
        raise forms.ValidationError(_("This username is already taken. Please choose another."))

Example 42

Project: cdr-stats
Source File: forms.py
View license
    def clean_multiple_email(self):
        """Check that the field contains one or more comma-separated emails
        and normalizes the data to a list of the email strings.
        """
        emails = self.cleaned_data['multiple_email'].split(',')
        mail_list = []
        for email in emails:
            email = email.strip()
            try:
                validate_email(email)
                mail_list.append(str(email))
            except:
                raise forms.ValidationError('%s is not a valid e-mail address.' % email)

        # Always return the cleaned data.
        mail_list = ','.join(mail_list)
        return mail_list

Example 43

Project: django-markdownx
Source File: forms.py
View license
    def clean(self):
        upload = self.cleaned_data.get('image')
        if upload:
            content_type = upload.content_type
            if content_type in MARKDOWNX_UPLOAD_CONTENT_TYPES:
                if upload._size > MARKDOWNX_UPLOAD_MAX_SIZE:
                    raise forms.ValidationError(_('Please keep filesize under %(max)s. Current filesize %(current)s') % {'max':filters.filesizeformat(MARKDOWNX_UPLOAD_MAX_SIZE), 'current':filters.filesizeformat(upload._size)})
            else:
                raise forms.ValidationError(_('File type is not supported'))

            return upload

Example 44

Project: ADL_LRS
Source File: forms.py
View license
    def clean(self):
        cleaned = super(RegisterForm, self).clean()
        p1 = cleaned.get("password")
        p2 = cleaned.get("password2")
        if p1 and p2:
            if p1 == p2:
                return cleaned
        raise forms.ValidationError("Passwords did not match")

Example 45

View license
    def clean(self):
        cleaned_data = super(CandidateCommitmentFormBase, self).clean()
        if self.candidate.election:
            if self.candidate.election.area != self.proposal.area:
                raise forms.ValidationError(_(u'El candidato no pertenece al area'))
        else:
            raise forms.ValidationError(_(u'El candidato no pertenece al area'))
        return cleaned_data

Example 46

Project: django-relationships
Source File: forms.py
View license
    def duplicate_slug_check(self, status_slug):
        status_qs = RelationshipStatus.objects.filter(
            Q(from_slug=status_slug) |
            Q(to_slug=status_slug) |
            Q(symmetrical_slug=status_slug)
        )

        if self.instance.pk:
            status_qs = status_qs.exclude(pk=self.instance.pk)

        if status_qs.exists():
            raise forms.ValidationError('"%s" slug already in use on %s' %
                (status_slug, unicode(status_qs[0])))

Example 47

Project: 1flow
Source File: forms.py
View license
    def clean_password2(self):
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError(
                self.error_messages['password_mismatch'])
        return password2

Example 48

View license
    def to_python(self, value):
        if value in self.empty_values:
            return

        if isinstance(value, six.string_types) and ISO_8601 in self.input_formats:
            try:
                return parse(value)
            except ValueError:
                raise forms.ValidationError(self.error_messages['invalid'], code='invalid')

        return super(ISO8601DateTimeField, self).to_python(value)

Example 49

Project: wikinotes
Source File: courses.py
View license
    def clean(self):
        # Make sure we don't already have this course
        cleaned_data = super(CourseForm, self).clean()
        department = cleaned_data.get('department')
        number = cleaned_data.get('number')
        matching = Course.objects.filter(department=department, number=number)

        if matching.exists():
            course = matching[0]
            course_url = course.get_absolute_url()
            course_link = '<a href="%s">%s</a>' % (course_url, course)
            raise forms.ValidationError(mark_safe("The course you're trying to"
                " create already exists: %s." % course_link))

        return cleaned_data

Example 50

Project: storybase
Source File: admin.py
View license
    def clean(self):
        cleaned_data = self.cleaned_data
        parent = cleaned_data.get("parent")
        child = cleaned_data.get("child")

        if parent.geolevel != child.geolevel.parent:
            raise forms.ValidationError(
                _("You tried to set a parent with the wrong GeoLevel. "
                  "You need to pick one with a GeoLevel of %s" % 
                  child.geolevel.parent))

        return cleaned_data