Python django.forms.ValidationError() Examples

The following are 30 code examples for showing how to use django.forms.ValidationError(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.forms , or try the search function .

Example 1
Project: Servo   Author: fpsw   File: admin.py    License: 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 2
Project: django-payfast   Author: PiDelport   File: forms.py    License: 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 3
Project: pyconkr-2015   Author: pythonkr   File: forms.py    License: 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 4
Project: django-username-email   Author: tmm   File: forms.py    License: 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 5
Project: coursys   Author: sfu-fas   File: mc.py    License: GNU General Public License v3.0 6 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 6
Project: coursys   Author: sfu-fas   File: forms.py    License: GNU General Public License v3.0 6 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 7
Project: coursys   Author: sfu-fas   File: forms.py    License: 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 8
Project: coursys   Author: sfu-fas   File: gittag.py    License: 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 9
Project: coursys   Author: sfu-fas   File: url.py    License: 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 10
Project: pinax-documents   Author: pinax   File: forms.py    License: MIT License 5 votes vote down vote up
def clean(self):
        name = self.cleaned_data["name"]
        parent = self.cleaned_data.get("parent")
        if Folder.already_exists(name, parent):
            raise forms.ValidationError(f"{name} already exists.") 
Example 11
Project: pinax-documents   Author: pinax   File: forms.py    License: MIT License 5 votes vote down vote up
def clean_file(self):
        value = self.cleaned_data["file"]
        if (value.size + self.storage.bytes_used) > self.storage.bytes_total:
            raise forms.ValidationError("File will exceed storage capacity.")
        return value 
Example 12
Project: pinax-documents   Author: pinax   File: forms.py    License: MIT License 5 votes vote down vote up
def clean(self):
        if "file" in self.cleaned_data:
            name = self.cleaned_data.get("file").name
            folder = self.cleaned_data.get("folder")
            if Document.already_exists(name, folder):
                raise forms.ValidationError(
                    hookset.already_exists_validation_message(name, folder)
                ) 
Example 13
Project: Servo   Author: fpsw   File: customer.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def clean(self):
        cd = super(CustomerSearchForm, self).clean()

        for k, v in cd.items():
            if v not in ['', None]:
                return cd

        raise forms.ValidationError(_('Please specify at least one parameter')) 
Example 14
Project: Servo   Author: fpsw   File: customer.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def clean_datafile(self):
        d = self.cleaned_data.get('datafile')
        if not d.content_type.startswith('text'):
            raise forms.ValidationError(_('Data file should be in text format'))
        return d 
Example 15
Project: Servo   Author: fpsw   File: repairs.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def clean(self, *args, **kwargs):
        cd = super(GsxRepairForm, self).clean(*args, **kwargs)
        if self.instance.has_serialized_parts():
            if cd.get('mark_complete') and not cd.get('replacement_sn'):
                error = _('Replacement serial number must be set when completing repair.')
                raise forms.ValidationError(error)

        return cd 
Example 16
Project: Servo   Author: fpsw   File: repairs.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def clean_attachment(self):
        max_filesize = 10 * 1024 * 1024  # 10MB
        from django.template.defaultfilters import filesizeformat
        f = self.cleaned_data.get('attachment')
        if f and f.size > max_filesize:
            size = filesizeformat(max_filesize)
            error = _('Attachment should be no larger than %s') % size
            raise forms.ValidationError(error)

        return f 
Example 17
Project: Servo   Author: fpsw   File: account.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def clean(self):
        cd = super(ProfileForm, self).clean()

        if cd.get('gsx_password') == "":
            del(cd['gsx_password'])

        cd['tech_id'] = cd['tech_id'].upper()

        if cd.get('password1'):
            if cd['password1'] != cd['password2']:
                raise forms.ValidationError(_("Password and confirmation do not match!"))

        return cd 
Example 18
Project: Servo   Author: fpsw   File: admin.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def save(self, **kwargs):
        from django.db.utils import IntegrityError

        try:
            location = super(LocationForm, self).save(**kwargs)
        except IntegrityError:
            msg = _('A location with that name already exists')
            self._errors['title'] = self.error_class([msg])
            raise forms.ValidationError(msg)

        return location 
Example 19
Project: Servo   Author: fpsw   File: admin.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def clean_order_template(self):
        from servo.lib.utils import file_type
        tpl = self.cleaned_data.get('order_template')

        if tpl is None: # file was not uploaded
            return

        ftype = file_type(tpl.file.read())

        if ftype != 'text/html':
            raise forms.ValidationError(_('Print tempates must be in HTML format'))

        return tpl 
Example 20
Project: Servo   Author: fpsw   File: admin.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def clean_content(self):
        content = self.cleaned_data.get('content')
        try:
            template.Template(content)
        except template.TemplateSyntaxError, e:
            raise forms.ValidationError(_('Syntax error in template: %s') % e) 
Example 21
Project: Servo   Author: fpsw   File: admin.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def clean_pct_margin(self, *args, **kwargs):
        margin = self.cleaned_data.get('pct_margin')
        if re.match('^\d[\-=;\d]*\d$', margin):
            return margin

        raise forms.ValidationError(_('Invalid margin format')) 
Example 22
Project: django-payfast   Author: PiDelport   File: forms.py    License: MIT License 5 votes vote down vote up
def clean_merchant_id(self):
        merchant_id = self.cleaned_data['merchant_id']
        if merchant_id != conf.MERCHANT_ID:
            raise forms.ValidationError('Invalid merchant id (%s).' % merchant_id)
        return merchant_id 
Example 23
Project: django-payfast   Author: PiDelport   File: forms.py    License: MIT License 5 votes vote down vote up
def clean_amount_gross(self):
        received = self.cleaned_data['amount_gross']
        if conf.REQUIRE_AMOUNT_MATCH:
            requested = self.instance.amount_gross
            if requested != received:
                raise forms.ValidationError('Amount is not the same: %s != %s' % (
                                            requested, received,))
        return received 
Example 24
Project: djreservation   Author: luisza   File: forms.py    License: GNU General Public License v3.0 5 votes vote down vote up
def clean(self):
        if hasattr(self, 'request'):
            if hasattr(self.request, "reservation"):
                raise forms.ValidationError(
                    _("You can not create reservation with active reservation"))
            cleaned_data = super(ReservationForm, self).clean() 
Example 25
Project: djreservation   Author: luisza   File: forms.py    License: GNU General Public License v3.0 5 votes vote down vote up
def clean(self):
        cleaned_data = super(ProductForm, self).clean()

        if cleaned_data['amount'] <= 0:
            raise forms.ValidationError(
                _("You amount correct, requested 0 or negative value"))

        if cleaned_data['amount'] > cleaned_data['available_amount']:
            raise forms.ValidationError(
                _("You requested more than product available")) 
Example 26
Project: oxidizr   Author: pixlie   File: forms.py    License: GNU General Public License v2.0 5 votes vote down vote up
def clean(self):
        super(RegistrationForm, self).clean()
        if 'password' in self.cleaned_data and 'repeat_password' in self.cleaned_data:
            if self.cleaned_data['password'] != self.cleaned_data['repeat_password']:
                raise forms.ValidationError(
                    _('Passwords do not match.'),
                    code='invalid'
                )
        return self.cleaned_data 
Example 27
Project: oxidizr   Author: pixlie   File: forms.py    License: GNU General Public License v2.0 5 votes vote down vote up
def clean_code(self):
        code = self.cleaned_data['code']
        if self._verification_code and code != self._verification_code:
            raise forms.ValidationError(_('The code did not match what we sent you in Email.'))
        return code 
Example 28
Project: oxidizr   Author: pixlie   File: forms.py    License: GNU General Public License v2.0 5 votes vote down vote up
def clean(self):
        data = super(ResetPasswordForm, self).clean()
        if data['password'] != data['repeat_password']:
            raise forms.ValidationError(
                _('Passwords do not match.'),
                code='invalid'
            )
        return data 
Example 29
Project: django-username-email   Author: tmm   File: forms.py    License: MIT License 5 votes vote down vote up
def get_invalid_login_error(self):
        return forms.ValidationError(
            self.error_messages['invalid_login'],
            code='invalid_login',
            params={'username': self.username_field.verbose_name},
        ) 
Example 30
Project: django-username-email   Author: tmm   File: forms.py    License: MIT License 5 votes vote down vote up
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'],
                code='password_mismatch',
            )
        return password2