Python django.forms.ValidationError() Examples

The following are 30 code examples of django.forms.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.forms , or try the search function .
Example #1
Source File: mc.py    From coursys with GNU General Public License v3.0 7 votes vote down vote up
def config_to_form(self, data, points):
        # undo the .clean just so it can be re-done for validation
        formdata = super().config_to_form(data, points)
        if 'options' not in formdata:
            raise forms.ValidationError(' missing ["options"]')
        options = formdata['options']
        del formdata['options']

        for i, (opt, marks) in enumerate(options):
            formdata['options_%i' % (i,)] = str(opt)
            try:
                formdata['options_%i' % (MAX_MC_CHOICES+i,)] = Decimal(marks)
            except ValueError:
                raise forms.ValidationError(' marks must be an integer (or decimal represented as a string).')

        if 'permute' not in formdata:
            formdata['permute'] = 'keep'
        if 'show_no_answer' not in formdata:
            formdata['show_no_answer'] = 'noshow'

        return formdata 
Example #2
Source File: forms.py    From coursys with GNU General Public License v3.0 7 votes vote down vote up
def clean_letter_review(self):
        review = self.cleaned_data['letter_review']
        if review:
            # cannot set to true if other required fields not filled in
            case = self.instance
            step = case.next_step()
            if step in PRE_LETTER_STEPS:
                raise forms.ValidationError(
                    mark_safe('Cannot finalize letter: have not entered <a href="%s">%s</a>.'
                        % (reverse('offering:discipline:edit_case_info',
                            kwargs={'field': STEP_VIEW[step], 'course_slug':case.offering.slug, 'case_slug':case.slug}),
                        STEP_DESC[step])))

            # cannot set to true if too many attachments
            if case.public_attachments_size() > MAX_ATTACHMENTS:
                raise forms.ValidationError('Total size of public attachments must be at most %s because of email limitations. Please make some of the attachments private.' % (MAX_ATTACHMENTS_TEXT))


        return review 
Example #3
Source File: url.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def clean_url(self):
            url = self.cleaned_data['url']
            if self.check_is_empty(url):
                raise forms.ValidationError("No URL given.")

            if self.component.prefix:
                # check that the URL starts with the provided prefix
                if not url.startswith(self.component.prefix):
                    raise forms.ValidationError('Submitted URL must start with "%s".' % (self.component.prefix))

            if self.component.check:
                # instructor asked to check that URLs really exist: do it.
                validator = QuickURLValidator()
                try:
                    validator(url) # throws ValidationError if there's a problem
                except forms.ValidationError:
                    # re-throw to produce a better error message
                    raise forms.ValidationError("The submitted URL doesn't seem to exist: please check the URL and resubmit.")
            return url 
Example #4
Source File: admin.py    From Servo with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def clean_username(self):
        reserved = (
            'admin',
            'orders',
            'sales',
            'devices',
            'customers',
            'notes',
            'api',
            'checkin',
            'feedback',
        )
        username = self.cleaned_data.get('username')
        if username in reserved:
            raise forms.ValidationError(_(u'"%s" cannot be used as a username') % username)

        return username 
Example #5
Source File: forms.py    From django-payfast with MIT License 6 votes vote down vote up
def clean(self):
        self.ip = self.request.META.get(conf.IP_HEADER, None)
        if not is_payfast_ip_address(self.ip):
            raise forms.ValidationError('untrusted ip: %s' % self.ip)

        # Verify signature
        sig = api.itn_signature(self.data)
        if sig != self.cleaned_data['signature']:
            raise forms.ValidationError('Signature is invalid: %s != %s' % (
                sig, self.cleaned_data['signature'],))

        if conf.USE_POSTBACK:
            is_valid = api.data_is_valid(self.request.POST, conf.SERVER)
            if is_valid is None:
                raise forms.ValidationError('Postback fails')
            if not is_valid:
                raise forms.ValidationError('Postback validation fails')

        return self.cleaned_data 
Example #6
Source File: gittag.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def clean_tag(self):
            # https://www.kernel.org/pub/software/scm/git/docs/git-check-ref-format.html
            tag = self.cleaned_data['tag']

            if '..' in tag or tag[-1] == '.':
                raise forms.ValidationError('Tag names cannot contain ".." or end with a dot.')

            if not all(_tag_allowed(c) for c in tag):
                raise forms.ValidationError('Tag name contains an illegal character.')

            if tag[0] == '/' or tag[-1] == '/' or '//' in tag:
                raise forms.ValidationError('Tags cannot start or end with a slash, or contain consecutive slashes.')

            if '@{' in tag:
                raise forms.ValidationError('Tags cannot contain "@{".')

            if tag == '@':
                raise forms.ValidationError('"@" is not a valid tag name.')

            return tag 
Example #7
Source File: forms.py    From pyconkr-2015 with MIT License 6 votes vote down vote up
def clean_image(self):
        image = self.cleaned_data.get('image')
        if image:
            try:
                if image._size > settings.SPEAKER_IMAGE_MAXIMUM_FILESIZE_IN_MB * 1024 * 1024:
                    raise forms.ValidationError(
                        _('Maximum size is %d MB')
                        % settings.SPEAKER_IMAGE_MAXIMUM_FILESIZE_IN_MB
                    )
            except AttributeError:
                pass

            w, h = get_image_dimensions(image)
            if w < settings.SPEAKER_IMAGE_MINIMUM_DIMENSION[0] \
                    or h < settings.SPEAKER_IMAGE_MINIMUM_DIMENSION[1]:
                raise forms.ValidationError(
                    _('Minimum dimension is %d x %d')
                    % settings.SPEAKER_IMAGE_MINIMUM_DIMENSION
                )

        return image 
Example #8
Source File: forms.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def clean(self):
        letter_sent = self.cleaned_data.get('letter_sent', '')
        date = self.cleaned_data.get('letter_date', '')
        text = self.cleaned_data.get('letter_text', '')
        case = self.instance

        if letter_sent=="MAIL":
            if not case.letter_review:
                raise forms.ValidationError(
                    mark_safe('Cannot send letter: it has not <a href="%s">been reviewed</a>.'
                        % (reverse('offering:discipline:edit_case_info',
                            kwargs={'field': 'letter_review', 'course_slug':case.offering.slug, 'case_slug':case.slug}))))
            self.instance.send_letter_now = True # trigger email sending in view logic
        elif letter_sent=="OTHR":
            if not text.strip():
                raise forms.ValidationError('Please enter details of the letter delivery.')
            if not date:
                raise forms.ValidationError('Please enter the date the letter was sent.')

        return self.cleaned_data 
Example #9
Source File: forms.py    From django-username-email with MIT License 6 votes vote down vote up
def confirm_login_allowed(self, user):
        """
        Controls whether the given User may log in. This is a policy setting,
        independent of end-user authentication. This default behavior is to
        allow login by active users, and reject login by inactive users.

        If the given user cannot log in, this method should raise a
        ``forms.ValidationError``.

        If the given user may log in, this method should return None.
        """
        if not user.is_active:
            raise forms.ValidationError(
                self.error_messages['inactive'],
                code='inactive',
            ) 
Example #10
Source File: forms.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def clean_case(self):
        if self.cleaned_data['case'] != self.case:
            raise forms.ValidationError("Wrong case.")
        return self.cleaned_data['case'] 
Example #11
Source File: code.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def clean_code(self):
            data = self.cleaned_data['code']
            if self.check_is_empty(data):
                raise forms.ValidationError("No file submitted.")
            if not self.check_size(data):
                raise forms.ValidationError("File size exceeded max size, component can not be uploaded.")
            self.check_filename(data)

            # get allowed file types
            upload_ext = splitext(data.name)[1]
            t = CodeComponent.objects.filter(id=self.prefix)
            allowed_list = t[0].allowed.split(",")
            name_okay = False
            if not any([data.name.endswith(ext) for ext in allowed_list]):
                msg = None
                msg_allowed = "Allowed types are:"
                for k in CODE_TYPES:
                    if k[0] in allowed_list:
                        msg_allowed = msg_allowed + " " + k[1] + ","
                    if k[0] == upload_ext:
                        msg = "File extension incorrect.  File appears to be %s." % (k[1])
                if msg is None:
                    msg = "Unable to determine file type (%s)." % upload_ext
                raise forms.ValidationError(msg + " " +msg_allowed[:-1] + ".")
            else:
                return data 
Example #12
Source File: text.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def clean_max_size(self):
            max_size = self.cleaned_data['max_size']
            if max_size > MAX_TEXT_KB:
                raise forms.ValidationError('Cannot be more than %i kB.' % (MAX_TEXT_KB))
            return max_size 
Example #13
Source File: gittag.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def __call__(self, value):
        value = force_text(value)
        if value.startswith('http://') or value.startswith('https://'):
            # HTTP(S) URLs: superclass can handle it.
            return super(GitURLValidator, self).__call__(value)

        # or try to validate it as a git scp-style URL
        if not self.ssh_regex.match(value):
            raise ValidationError('Enter a valid "http://", "https://", or "user@host:path" URL.') 
Example #14
Source File: forms.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def clean_name(self):
        # can't have another group in the course with the same name
        name = self.cleaned_data['name']
        others = Group.objects.filter(courseoffering=self.instance.courseoffering, name=name) \
                .exclude(id=self.instance.id)
        if others:
            raise forms.ValidationError("There is already another group with that name.")

        return name 
Example #15
Source File: forms.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def clean_student(self):
        student = self.cleaned_data['student']
        # ensure uniqueness of the quiz/student pair
        if TimeSpecialCase.objects.filter(quiz=self.quiz, student=student).exists():
            raise forms.ValidationError('This student already has a special case: you must delete it before adding another.')
        return student 
Example #16
Source File: forms.py    From donation-tracker with Apache License 2.0 5 votes vote down vote up
def clean_password(self):
        if not self.cleaned_data['password']:
            raise forms.ValidationError('Password must not be blank.')
        return self.cleaned_data['password'] 
Example #17
Source File: mc.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def clean(self):
            data = self.cleaned_data
            if 'points' in data and 'options' in data:
                points = data['points']
                marks = [float(m) for o,m in data['options']]
                if max(marks) > points:
                    raise forms.ValidationError('Auto-marking value greater than question max points.')
                if min(marks) < -points:
                    raise forms.ValidationError('Auto-marking penalty greater than question total max points.')
            return data 
Example #18
Source File: mc.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def clean(self, value):
        choices = super().clean(value)
        if len(choices) < 2:
            raise forms.ValidationError('Must give at least two options.')
        options = [o for o,_ in choices]
        if len(options) != len(set(options)):
            raise forms.ValidationError('Choices must be unique')
        return choices 
Example #19
Source File: file.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def clean(self, data, initial=None):
        cleaned = super().clean(data)
        if cleaned and cleaned.size > self.max_size * 1024:
            raise forms.ValidationError('Submitted files can be at most %i kilobytes in size.' % (self.max_size,))
        return cleaned 
Example #20
Source File: file.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def value_from_datadict(self, data, files, name):
        # override to accept the case "clear + file upload" without ValidationError
        upload = super().value_from_datadict(data, files, name)
        if not self.is_required and forms.CheckboxInput().value_from_datadict(
                data, files, self.clear_checkbox_name(name)):

            #if upload:
            #    return FILE_INPUT_CONTRADICTION

            # False signals to clear any existing value, as opposed to just None
            return False
        return upload 
Example #21
Source File: forms.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def clean_week(self):
        week = self.cleaned_data['week']
        if week is not None and week < 0:
            raise forms.ValidationError('Week number must be positive.')
        if week is not None and week > 16:
            raise forms.ValidationError('Week number can be no more than 16.')
        return week 
Example #22
Source File: forms.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def to_python(self, value):
        try:
            st= Person.objects.get(emplid=value)
        except (ValueError, Person.DoesNotExist):
            raise forms.ValidationError("Unknown person selected")
        return st 
Example #23
Source File: forms.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def clean_hours(self):
        data = self.cleaned_data['hours']
        if self.cleaned_data['pay_frequency'] == 'L':
            return data

        if int(data) > 168:
            raise forms.ValidationError("There are only 168 hours in a week.")
        if int(data) < 0:
            raise forms.ValidationError("One cannot work negative hours.")
        return data 
Example #24
Source File: forms.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def clean_sin(self):
        sin = self.cleaned_data['sin']
        try:
            emplid = int(self['person'].value())
        except ValueError:
            raise forms.ValidationError("The correct format for a SIN is XXXXXXXXX, all numbers, no spaces or dashes.")
        people = Person.objects.filter(emplid=emplid)
        if people:
            person = people[0]
            person.set_sin(sin)
            person.save()
        return sin 
Example #25
Source File: forms.py    From open-synthesis with GNU General Public License v3.0 5 votes vote down vote up
def clean(self):
        """Validate that a date is provided if a URL is provided."""
        cleaned_data = super(EvidenceSourceForm, self).clean()
        if cleaned_data.get('source_url') and not cleaned_data.get('source_date'):
            raise ValidationError(_('Provide a date for the source.'), code='invalid') 
Example #26
Source File: forms.py    From openvpn-admin with MIT License 5 votes vote down vote up
def clean_import_zip(self):
        import_zip = self.cleaned_data.get('import_zip')

        if import_zip:
            if not zipfile.is_zipfile(import_zip.file):
                raise forms.ValidationError("Enter a zip file.")
        return import_zip 
Example #27
Source File: forms.py    From donation-tracker with Apache License 2.0 5 votes vote down vote up
def clean_count(self):
        count = int(self.cleaned_data['count'])
        if count > self.instance.pendingcount:
            raise forms.ValidationError('Error, count cannot exceed total')
        return count 
Example #28
Source File: forms.py    From donation-tracker with Apache License 2.0 5 votes vote down vote up
def clean_total(self):
        if self.instance.pendingcount != self.cleaned_data['total']:
            raise forms.ValidationError(
                'It seems something changed in your status since you loaded the page. Please review and try again.'
            )
        return self.instance.pendingcount 
Example #29
Source File: forms.py    From donation-tracker with Apache License 2.0 5 votes vote down vote up
def save(self, commit=True):
        if self.user:
            self.user.username = self.cleaned_data['username']
            self.user.set_password(self.cleaned_data['password'])
            self.user.is_active = True
            if commit is True:
                self.user.save()
        else:
            raise forms.ValidationError('Could not save user.')
        return self.user 
Example #30
Source File: forms.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def clean_offering(self):
        if self.cleaned_data['offering'] != self.offering:
            raise forms.ValidationError("Wrong course offering.")
        return self.cleaned_data['offering']