Python django.forms 模块,ValidationError() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.forms.ValidationError()

项目:NearBeach    作者:robotichead    | 项目源码 | 文件源码
def clean_update_profile_picture(self):
        profile_picture=self.cleaned_data['update_profile_picture']

        try:
            """
            We only want to limit pictures to being under 400kb
            """
            picture_errors=""

            main, sub=profile_picture.content_type.split('/')
            if not (main == 'image' and sub in ['jpeg','gif','png']):
                picture_errors += 'Please use a JPEG, GIF or PNG image'

            if len(profile_picture) > (MAX_PICTURE_SIZE): #400kb
                picture_errors += '\nPicture profile exceeds 400kb'

            if not picture_errors == "":
                raise forms.ValidationError(picture_errors)

        except AttributeError:
            pass

        return profile_picture
项目:NearBeach    作者:robotichead    | 项目源码 | 文件源码
def clean(self):
        #Get login data
        username=self.cleaned_data.get("username")
        password=self.cleaned_data.get("password")

        #Checking authentication
        if username and password:
            user=authenticate(username=username, password=password)
            """
            The following bunch of if, else if statements will return errors if the following
            cases are met
            -- Login is not valid
            -- Login is currently not active
            -- If the user does not have groups associated with them
            """
            if ((not user) or (not user.check_password(password))):
                raise forms.ValidationError("The login details are incorrect")
            elif (not user.is_active):
                raise forms.ValidationError("Please contact your system administrator. Your account has been disabled")
            elif (user_groups.objects.filter(username_id=user.id, is_deleted='FALSE').count() == 0):
                raise forms.ValidationError("Please contact your system administrator. Your account has no group access")
        return super(login_form, self).clean()
项目:NearBeach    作者:robotichead    | 项目源码 | 文件源码
def clean_update_profile_picture(self):
        profile_picture=self.cleaned_data['update_profile_picture']

        try:
            """
            We only want to limit pictures to being under 400kb
            """
            picture_errors=""

            main, sub=profile_picture.content_type.split('/')
            if not (main == 'image' and sub in ['jpeg', 'gif', 'png']):
                picture_errors += 'Please use a JPEG, GIF or PNG image'

            if len(profile_picture) > (MAX_PICTURE_SIZE):  # 400kb
                picture_errors += '\nPicture profile exceeds 400kb'

            if not picture_errors == "":
                raise forms.ValidationError(picture_errors)

        except AttributeError:
            pass

        return profile_picture
项目:Instagram    作者:Fastcampus-WPS-5th    | 项目源码 | 文件源码
def clean(self):
        # clean()???? ??? ???? dict? ???
        # cleaned_data = super().clean()
        # username, password? ??? ????? ??
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')

        # username, password? ??? ??? authenticate
        user = authenticate(
            username=username,
            password=password
        )
        # ??? ??? ??, Form? cleaned_data? 'user'
        # ?? ??? User??? ??
        if user is not None:
            self.cleaned_data['user'] = user
        # ??? ??? ??, is_valid()? ???? ????
        # ValidationError? ????
        else:
            raise forms.ValidationError(
                'Login credentials not valid'
            )
        return self.cleaned_data
项目:django-powerpages    作者:Open-E-WEB    | 项目源码 | 文件源码
def clean_alias(self):
        """
        Force alias to be null instead of empty string
        (protection against breaking uniqueness constraint).
        """
        alias = self.cleaned_data.get('alias')
        if not alias:
            return None
        # uniqueness validation (not handled by default, because of null=True)
        page_query = Page.objects.all()
        if self.instance and self.instance.pk:
            page_query = page_query.exclude(pk=self.instance.pk)
        try:
            page = page_query.get(alias=alias)
        except Page.DoesNotExist:
            pass
        else:
            raise forms.ValidationError(
                'The "alias" field have to be unique or blank, but the same '
                'alias value has been found in page: %s.' % page
            )
        return alias
项目:Bitpoll    作者:fsinfuhh    | 项目源码 | 文件源码
def clean_invitees(self):
        self.invitee_users = []
        data = self.cleaned_data['invitees']
        invitees = [s.strip() for s in data.split(',')]
        for invitee in invitees:
            User = get_user_model()
            try:
                invitee_user = User.objects.get(username=invitee)
                self.invitee_users.append(invitee_user)
            except User.DoesNotExist:
                raise forms.ValidationError(_('There is no user "%s."')
                                            % invitee)

            has_invitation = bool(GroupInvitation.objects.filter(
                    group=self.group, invitee=invitee_user))
            if has_invitation:
                raise forms.ValidationError(
                    _('"%s" already has an invitation.') % invitee)

            already_member = \
                invitee_user.groups.filter(name=self.group.name).exists()
            if already_member:
                raise forms.ValidationError(
                    _('"%s" is already a member of this group.')
                    % invitee)
项目:ecs_sclm    作者:meaningful    | 项目源码 | 文件源码
def clean_rename_format(self):
        try:
            self.cleaned_data['rename_format'] % {
                'original_filename': 'filename',
                'original_basename': 'basename',
                'original_extension': 'ext',
                'current_filename': 'filename',
                'current_basename': 'basename',
                'current_extension': 'ext',
                'current_folder': 'folder',
                'counter': 42,
                'global_counter': 42,
            }
        except KeyError as e:
            raise forms.ValidationError(_('Unknown rename format value key "%(key)s".') % {'key': e.args[0]})
        except Exception as e:
            raise forms.ValidationError(_('Invalid rename format: %(error)s.') % {'error': e})
        return self.cleaned_data['rename_format']
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def clean(self):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')

        if username and password:
            self.user_cache = authenticate(username=username,
                                           password=password)
            if self.user_cache is None:
                raise forms.ValidationError(
                    self.error_messages['invalid_login'],
                    code='invalid_login',
                    params={'username': self.username_field.verbose_name},
                )
            else:
                self.confirm_login_allowed(self.user_cache)

        return self.cleaned_data
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
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',
            )
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def clean(self):
        url = self.cleaned_data.get('url')
        sites = self.cleaned_data.get('sites')

        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()
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
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)
            except (GEOSException, ValueError, TypeError):
                raise forms.ValidationError(self.error_messages['invalid_geom'], code='invalid_geom')

        # Try to set the srid
        if not value.srid:
            try:
                value.srid = self.widget.map_srid
            except AttributeError:
                if self.srid:
                    value.srid = self.srid
        return value
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def clean(self, value):
        """
        Validates that the input value can be converted to a Geometry
        object (which is returned).  A ValidationError is raised if
        the value cannot be instantiated as a Geometry.
        """
        geom = super(GeometryField, self).clean(value)
        if geom is None:
            return geom

        # Ensuring that the geometry is of the correct type (indicated
        # using the OGC string label).
        if str(geom.geom_type).upper() != self.geom_type and not self.geom_type == 'GEOMETRY':
            raise forms.ValidationError(self.error_messages['invalid_geom_type'], code='invalid_geom_type')

        # Transforming the geometry if the SRID was set.
        if self.srid and self.srid != -1 and self.srid != geom.srid:
            try:
                geom.transform(self.srid)
            except GEOSException:
                raise forms.ValidationError(
                    self.error_messages['transform_error'], code='transform_error')

        return geom
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def has_changed(self, initial, data):
        """ Compare geographic value of data with its initial value. """

        try:
            data = self.to_python(data)
            initial = self.to_python(initial)
        except forms.ValidationError:
            return True

        # Only do a geographic comparison if both values are available
        if initial and data:
            data.transform(initial.srid)
            # If the initial value was not added by the browser, the geometry
            # provided may be slightly different, the first time it is saved.
            # The comparison is done with a very low tolerance.
            return not initial.equals_exact(data, tolerance=0.000001)
        else:
            # Check for change of state of existence
            return bool(initial) != bool(data)
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def clean(self):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')

        if username and password:
            self.user_cache = authenticate(username=username, password=password)
            if self.user_cache is None:
                raise forms.ValidationError(
                    self.error_messages['invalid_login'],
                    code='invalid_login',
                    params={'username': self.username_field.verbose_name},
                )
            else:
                self.confirm_login_allowed(self.user_cache)

        return self.cleaned_data
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
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',
            )
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
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 (
                (settings.MIDDLEWARE and 'django.middleware.common.CommonMiddleware' in settings.MIDDLEWARE) or
                'django.middleware.common.CommonMiddleware' in settings.MIDDLEWARE_CLASSES) and
                not url.endswith('/')):
            raise forms.ValidationError(
                ugettext("URL is missing a trailing slash."),
                code='missing_trailing_slash',
            )
        return url
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def clean(self):
        url = self.cleaned_data.get('url')
        sites = self.cleaned_data.get('sites')

        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()
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
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)
            except (GEOSException, ValueError, TypeError):
                raise forms.ValidationError(self.error_messages['invalid_geom'], code='invalid_geom')

        # Try to set the srid
        if not value.srid:
            try:
                value.srid = self.widget.map_srid
            except AttributeError:
                if self.srid:
                    value.srid = self.srid
        return value
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def clean(self, value):
        """
        Validates that the input value can be converted to a Geometry
        object (which is returned).  A ValidationError is raised if
        the value cannot be instantiated as a Geometry.
        """
        geom = super(GeometryField, self).clean(value)
        if geom is None:
            return geom

        # Ensuring that the geometry is of the correct type (indicated
        # using the OGC string label).
        if str(geom.geom_type).upper() != self.geom_type and not self.geom_type == 'GEOMETRY':
            raise forms.ValidationError(self.error_messages['invalid_geom_type'], code='invalid_geom_type')

        # Transforming the geometry if the SRID was set.
        if self.srid and self.srid != -1 and self.srid != geom.srid:
            try:
                geom.transform(self.srid)
            except GEOSException:
                raise forms.ValidationError(
                    self.error_messages['transform_error'], code='transform_error')

        return geom
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def has_changed(self, initial, data):
        """ Compare geographic value of data with its initial value. """

        try:
            data = self.to_python(data)
            initial = self.to_python(initial)
        except forms.ValidationError:
            return True

        # Only do a geographic comparison if both values are available
        if initial and data:
            data.transform(initial.srid)
            # If the initial value was not added by the browser, the geometry
            # provided may be slightly different, the first time it is saved.
            # The comparison is done with a very low tolerance.
            return not initial.equals_exact(data, tolerance=0.000001)
        else:
            # Check for change of state of existence
            return bool(initial) != bool(data)
项目:pyconjp-website    作者:pyconjp    | 项目源码 | 文件源码
def clean_email(self):
        value = self.cleaned_data["email"]
        # django-selectable returns the user
        if isinstance(value, UserLookup.model):
            value = value.email
        if value == self.proposal.speaker.email:
            raise forms.ValidationError(
                _("You have submitted the Proposal author's email address. Please" \
                " select another email address.")
            )
        exists = self.proposal.additional_speakers.filter(
            Q(user=None, invite_email=value) |
            Q(user__email=value)
        ).exists()
        if exists:
            raise forms.ValidationError(
                _("This email address has already been invited to your talk proposal")
            )
        return value
项目:tecken    作者:mozilla-services    | 项目源码 | 文件源码
def clean_count(self):
        values = self.cleaned_data['count']
        if not values:
            return []
        operators = re.compile('<=|>=|<|>|=')
        counts = []
        for block in [x.strip() for x in values.split(',') if x.strip()]:
            if operators.findall(values):
                operator, = operators.findall(block)
            else:
                operator = '='
            rest = operators.sub('', block)
            try:
                rest = int(rest)
            except ValueError:
                raise forms.ValidationError(f'{rest!r} is not a number')
            counts.append((operator, rest))
        return counts
项目:zing    作者:evernote    | 项目源码 | 文件源码
def dispatch(self, request, *args, **kwargs):
        form = self.get_form()
        if not form.is_valid():
            raise Http404(ValidationError(form.errors))

        path = form.cleaned_data['path']
        lang_code, proj_code, dir_path, filename = split_pootle_path(path)

        kwargs.update({
            'language_code': lang_code,
            'project_code': proj_code,
            'dir_path': dir_path,
            'filename': filename,
        })
        kwargs.update(**form.cleaned_data)

        view_class = self.get_view_class(lang_code, proj_code, dir_path, filename)
        return view_class.as_view()(request, *args, **kwargs)
项目:zing    作者:evernote    | 项目源码 | 文件源码
def get_units(request):
    """Based on the vector of uids and the vector of header uids,
    return a dictionary of lightweight results for the view rows.

    :return: A JSON-encoded string containing the dictionary
    """
    form = UnitViewRowsForm(request.GET, user=request.user)

    if not form.is_valid():
        errors = form.errors.as_data()
        if 'uids' in errors:
            for error in errors['uids']:
                if error.code in ['invalid', 'required']:
                    raise Http400(error.message)
        raise Http404(forms.ValidationError(form.errors).messages)

    units = search_backend.get(Unit)(
        request.user, **form.cleaned_data
    ).get_units()

    return JsonResponse(ViewRowResults(units, form.cleaned_data['headers']).data)
项目:zing    作者:evernote    | 项目源码 | 文件源码
def clean_path(self):
        lang_code, proj_code = split_pootle_path(
            self.cleaned_data["path"])[:2]
        if not (lang_code or proj_code):
            permission_context = Directory.objects.projects
        elif proj_code and not lang_code:
            try:
                permission_context = Project.objects.select_related(
                    "directory").get(code=proj_code).directory
            except Project.DoesNotExist:
                raise forms.ValidationError("Unrecognized path")
        else:
            # no permission checking on lang translate views
            return self.cleaned_data["path"]
        if self.request_user.is_superuser:
            return self.cleaned_data["path"]
        can_view_path = check_user_permission(
            self.request_user, "administrate", permission_context)
        if can_view_path:
            return self.cleaned_data["path"]
        raise forms.ValidationError("Unrecognized path")
项目:CoBL-public    作者:lingdb    | 项目源码 | 文件源码
def validate_loanword(form, field):
        fieldList = ['parallelLoanEvent',
                     'loanSourceCognateClass',
                     'loan_source',
                     'loanEventTimeDepthBP',
                     'sourceFormInLoanLanguage',
                     'loan_notes ']
        if field.data:
            # loanword -> any(fieldList)
            for fieldName in fieldList:
                if fieldName in form.data:
                    fieldData = form.data[fieldName]
                    if fieldData or isinstance(fieldData, bool):
                        break
            else:
                raise ValidationError(
                    'Loanword is %s, but none of the fields %s is set.' %
                    (field.data, fieldList))
项目:CoBL-public    作者:lingdb    | 项目源码 | 文件源码
def post(self, request, pk, **kwargs):
        instance = CognateClassCitation.objects.get(id=pk)
        form = EditCognateClassCitationForm(request.POST, instance=instance)
        try:
            # validate {ref foo ...}
            s = Source.objects.all().filter(deprecated=False)
            pattern = re.compile(r'(\{ref +([^\{]+?)(:[^\{]+?)? *\})')
            for m in re.finditer(pattern, form.data['comment']):
                foundSet = s.filter(shorthand=m.group(2))
                if not foundSet.count() == 1:
                    raise ValidationError('In field “Comment” source shorthand “%(name)s” is unknown.', 
                                                params={'name': m.group(2)})
            form.save()
        except ValidationError as e:
            messages.error(
                request,
                'Sorry, the server had problems updating the cognate citation. %s' % e)
            return self.render_to_response({"form": form})
        return HttpResponseRedirect(reverse('cognate-class-citation-detail', args=[pk]))
项目:blog_django    作者:chnpmy    | 项目源码 | 文件源码
def clean(self):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')
        message = ERROR_MESSAGE

        if username and password:
            self.user_cache = authenticate(
                username=username, password=password)
            if self.user_cache is None:
                if u'@' in username:
                    User = get_user_model()
                    # Mistakenly entered e-mail address instead of username? Look it up.
                    try:
                        user = User.objects.get(email=username)
                    except (User.DoesNotExist, User.MultipleObjectsReturned):
                        # Nothing to do here, moving along.
                        pass
                    else:
                        if user.check_password(password):
                            message = _("Your e-mail address is not your username."
                                        " Try '%s' instead.") % user.username
                raise forms.ValidationError(message)
            elif not self.user_cache.is_active or not self.user_cache.is_staff:
                raise forms.ValidationError(message)
        return self.cleaned_data
项目:SpongeAuth    作者:lukegb    | 项目源码 | 文件源码
def clean_response(self):
        code = self.cleaned_data['response']
        verifier = oath.TOTP(base64.b32decode(self.device.base32_secret), drift=self.device.drift)
        # lock verifier to now
        verifier.time = verifier.time
        last_t = self.device.last_t or -1
        ok = verifier.verify(code, tolerance=TOTP_TOLERANCE, min_t=last_t + 1)
        if not ok:
            raise forms.ValidationError(_('That code could not be verified.'))

        # persist data
        self.device.last_t = verifier.t()
        self.device.drift = verifier.drift
        self.device.last_used_at = timezone.now()
        self.device.save()

        return code
项目:SpongeAuth    作者:lukegb    | 项目源码 | 文件源码
def clean_response(self):
        code = self.cleaned_data['response']
        try:
            code_obj = self.device.codes.get(code=code)
        except models.PaperCode.DoesNotExist:
            raise forms.ValidationError(_('That code is incorrect.'))

        if code_obj.used_at:
            raise forms.ValidationError(_('That code has already been used.'))

        # mark as used
        code_obj.used_at = timezone.now()
        code_obj.save()
        self.device.last_used_at = timezone.now()
        self.device.save()

        return code
项目:SpongeAuth    作者:lukegb    | 项目源码 | 文件源码
def clean(self):
        cleaned_data = super().clean()
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')
        email = self.cleaned_data.get('email')
        if username and password and email:
            user = models.User(
                username=username,
                password=password,
                email=email)
            try:
                django.contrib.auth.password_validation.validate_password(
                    password, user=user)
            except forms.ValidationError as ve:
                self.add_error('password', ve)
        return cleaned_data
项目:Scrum    作者:prakharchoudhary    | 项目源码 | 文件源码
def clean(self):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')

        if username is not None and password:
            self.user_cache = authenticate(self.request, username=username, password=password)
            if self.user_cache is None:
                raise forms.ValidationError(
                    self.error_messages['invalid_login'],
                    code='invalid_login',
                    params={'username': self.username_field.verbose_name},
                )
            else:
                self.confirm_login_allowed(self.user_cache)

        return self.cleaned_data
项目:Scrum    作者:prakharchoudhary    | 项目源码 | 文件源码
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',
            )
项目:Scrum    作者:prakharchoudhary    | 项目源码 | 文件源码
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 (
                (settings.MIDDLEWARE and 'django.middleware.common.CommonMiddleware' in settings.MIDDLEWARE) or
                'django.middleware.common.CommonMiddleware' in settings.MIDDLEWARE_CLASSES) and
                not url.endswith('/')):
            raise forms.ValidationError(
                ugettext("URL is missing a trailing slash."),
                code='missing_trailing_slash',
            )
        return url
项目:Scrum    作者:prakharchoudhary    | 项目源码 | 文件源码
def clean(self):
        url = self.cleaned_data.get('url')
        sites = self.cleaned_data.get('sites')

        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()
项目:Scrum    作者:prakharchoudhary    | 项目源码 | 文件源码
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)
            except (GEOSException, ValueError, TypeError):
                raise forms.ValidationError(self.error_messages['invalid_geom'], code='invalid_geom')

        # Try to set the srid
        if not value.srid:
            try:
                value.srid = self.widget.map_srid
            except AttributeError:
                if self.srid:
                    value.srid = self.srid
        return value
项目:Scrum    作者:prakharchoudhary    | 项目源码 | 文件源码
def clean(self, value):
        """
        Validates that the input value can be converted to a Geometry
        object (which is returned).  A ValidationError is raised if
        the value cannot be instantiated as a Geometry.
        """
        geom = super(GeometryField, self).clean(value)
        if geom is None:
            return geom

        # Ensuring that the geometry is of the correct type (indicated
        # using the OGC string label).
        if str(geom.geom_type).upper() != self.geom_type and not self.geom_type == 'GEOMETRY':
            raise forms.ValidationError(self.error_messages['invalid_geom_type'], code='invalid_geom_type')

        # Transforming the geometry if the SRID was set.
        if self.srid and self.srid != -1 and self.srid != geom.srid:
            try:
                geom.transform(self.srid)
            except GEOSException:
                raise forms.ValidationError(
                    self.error_messages['transform_error'], code='transform_error')

        return geom
项目:Scrum    作者:prakharchoudhary    | 项目源码 | 文件源码
def has_changed(self, initial, data):
        """ Compare geographic value of data with its initial value. """

        try:
            data = self.to_python(data)
            initial = self.to_python(initial)
        except forms.ValidationError:
            return True

        # Only do a geographic comparison if both values are available
        if initial and data:
            data.transform(initial.srid)
            # If the initial value was not added by the browser, the geometry
            # provided may be slightly different, the first time it is saved.
            # The comparison is done with a very low tolerance.
            return not initial.equals_exact(data, tolerance=0.000001)
        else:
            # Check for change of state of existence
            return bool(initial) != bool(data)
项目:DCRM    作者:82Flex    | 项目源码 | 文件源码
def clean_zip_file(self):
        """Open the zip file a first time, to check that it is a valid zip archive.
        We'll open it again in a moment, so we have some duplication, but let's focus
        on keeping the code easier to read!
        """
        zip_file = self.cleaned_data['zip_file']
        try:
            zip = zipfile.ZipFile(zip_file)
        except BadZipFile as e:
            raise forms.ValidationError(str(e))
        bad_file = zip.testzip()
        if bad_file:
            zip.close()
            raise forms.ValidationError('"%s" in the .zip archive is corrupt.' % bad_file)
        zip.close()  # Close file in all cases.
        return zip_file
项目:dream_blog    作者:fanlion    | 项目源码 | 文件源码
def clean(self):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')
        message = ERROR_MESSAGE

        if username and password:
            self.user_cache = authenticate(
                username=username, password=password)
            if self.user_cache is None:
                if u'@' in username:
                    User = get_user_model()
                    # Mistakenly entered e-mail address instead of username? Look it up.
                    try:
                        user = User.objects.get(email=username)
                    except (User.DoesNotExist, User.MultipleObjectsReturned):
                        # Nothing to do here, moving along.
                        pass
                    else:
                        if user.check_password(password):
                            message = _("Your e-mail address is not your username."
                                        " Try '%s' instead.") % user.username
                raise forms.ValidationError(message)
            elif not self.user_cache.is_active or not self.user_cache.is_staff:
                raise forms.ValidationError(message)
        return self.cleaned_data
项目:MxOnline    作者:myTeemo    | 项目源码 | 文件源码
def clean(self):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')
        message = ERROR_MESSAGE

        if username and password:
            self.user_cache = authenticate(
                username=username, password=password)
            if self.user_cache is None:
                if u'@' in username:
                    User = get_user_model()
                    # Mistakenly entered e-mail address instead of username? Look it up.
                    try:
                        user = User.objects.get(email=username)
                    except (User.DoesNotExist, User.MultipleObjectsReturned):
                        # Nothing to do here, moving along.
                        pass
                    else:
                        if user.check_password(password):
                            message = _("Your e-mail address is not your username."
                                        " Try '%s' instead.") % user.username
                raise forms.ValidationError(message)
            elif not self.user_cache.is_active or not self.user_cache.is_staff:
                raise forms.ValidationError(message)
        return self.cleaned_data
项目:feincms3    作者:matthiask    | 项目源码 | 文件源码
def clean(self):
        data = super(MoveForm, self).clean()
        if not data.get('move_to'):
            return data

        if data.get('of') and data.get('of') == self.instance:
            raise forms.ValidationError({
                'of': _('Cannot move node to a position relative to itself.'),
            })

        if not data.get('of'):
            self.instance.parent = None
        elif data['move_to'] in ('left', 'right'):
            self.instance.parent = data.get('of').parent
        else:
            self.instance.parent = data.get('of')

        self.instance.full_clean()

        return data
项目:djangoblog    作者:liuhuipy    | 项目源码 | 文件源码
def clean(self):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')
        message = ERROR_MESSAGE

        if username and password:
            self.user_cache = authenticate(
                username=username, password=password)
            if self.user_cache is None:
                if u'@' in username:
                    User = get_user_model()
                    # Mistakenly entered e-mail address instead of username? Look it up.
                    try:
                        user = User.objects.get(email=username)
                    except (User.DoesNotExist, User.MultipleObjectsReturned):
                        # Nothing to do here, moving along.
                        pass
                    else:
                        if user.check_password(password):
                            message = _("Your e-mail address is not your username."
                                        " Try '%s' instead.") % user.username
                raise forms.ValidationError(message)
            elif not self.user_cache.is_active or not self.user_cache.is_staff:
                raise forms.ValidationError(message)
        return self.cleaned_data
项目:socialhome    作者:jaywink    | 项目源码 | 文件源码
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'])
项目:sentry-plugins    作者:getsentry    | 项目源码 | 文件源码
def clean_orgs(self):
        rv = [org for org in self.all_orgs if six.text_type(org.id) in self.cleaned_data['orgs']]
        if not rv:
            raise forms.ValidationError(
                'You need to select at least one '
                'organization to give access to.'
            )
        return rv
项目:Instagram    作者:Fastcampus-WPS-5th    | 项目源码 | 文件源码
def clean_username(self):
        username = self.cleaned_data.get('username')
        if username and User.objects.filter(username=username).exists():
            raise forms.ValidationError(
                'Username already exist'
            )
        return username
项目:Instagram    作者:Fastcampus-WPS-5th    | 项目源码 | 文件源码
def clean_nickname(self):
        nickname = self.cleaned_data.get('nickname')
        if nickname and User.objects.filter(nickname=nickname).exists():
            raise forms.ValidationError(
                'Nickname already exist'
            )
        return nickname
项目:Instagram    作者:Fastcampus-WPS-5th    | 项目源码 | 文件源码
def clean_email(self):
        email = self.cleaned_data.get('email')
        if email and User.objects.filter(email=email).exists():
            raise forms.ValidationError(
                'Email already exist'
            )
        return email
项目:Instagram    作者:Fastcampus-WPS-5th    | 项目源码 | 文件源码
def clean_password2(self):
        # password1? password2? ???? ??? ??
        # password2??? clean_<fieldname>? ???? ???,
        #   cleaned_data? password1? ?? ??? ??? ?? ??
        password1 = self.cleaned_data.get('password1')
        password2 = self.cleaned_data.get('password2')
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError(
                'Password mismatch',
            )
        return password2
项目:django-powerpages    作者:Open-E-WEB    | 项目源码 | 文件源码
def validate(self, request=None):
        """Check validity of configuration and Page template"""
        self.config.validate()
        try:
            context = self.get_validation_context(request=request)
            self.render(context)
        except:
            tb_info = traceback.format_exc()
            msg = (
                'An error occurred trying to render the Page:\n'
                '<br/><pre>{0}</pre>'.format(tb_info)
            )
            raise ValidationError(mark_safe(msg))