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

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

项目:socialhome    作者:jaywink    | 项目源码 | 文件源码
def get(self, request, *args, **kwargs):
        """See if we have a direct match. If so redirect, if not, search.

        Try fetching a remote profile if the search term is a handle.
        """
        try:
            q = safe_text(request.GET.get("q"))
            if q:
                q = q.strip()
            validate_email(q)
        except ValidationError:
            pass
        else:
            profile = None
            try:
                profile = Profile.objects.visible_for_user(request.user).get(handle=q)
            except Profile.DoesNotExist:
                # Try a remote search
                remote_profile = retrieve_remote_profile(q)
                if remote_profile:
                    profile = Profile.from_remote_profile(remote_profile)
            if profile:
                return redirect(reverse("users:profile-detail", kwargs={"guid": profile.guid}))
        return super().get(request, *args, **kwargs)
项目:socialhome    作者:jaywink    | 项目源码 | 文件源码
def share(self, profile):
        """Share this content as the profile given."""
        if self.content_type != ContentType.CONTENT:
            # TODO: support sharing replies too
            raise ValidationError("Can only share top level content.")
        if self.author == profile:
            raise ValidationError("Cannot share own content")
        if not self.visible_for_user(profile.user):
            raise ValidationError("Content to be shared is not visible to sharer.")
        if self.shares.filter(author=profile).exists():
            raise ValidationError("Profile has already shared this content.")
        # Use get or created as a safety to stop duplicates
        share, _created = Content.objects.get_or_create(author=profile, share_of=self, defaults={
            "visibility": self.visibility,
        })
        delete_memoized(Content.has_shared, self.id, profile.id)
        return share
项目:django-codenerix-products    作者:centrologic    | 项目源码 | 文件源码
def form_valid(self, form):
        if self.__product_pk:
            product_final = ProductFinal.objects.get(pk=self.__product_pk)
            self.request.product_final = product_final
            form.instance.product_final = product_final

        try:
            return super(ProductUniqueCreate, self).form_valid(form)
        except ValidationError as e:
            errors = form._errors.setdefault("value", ErrorList())
            errors.append(e)
            return super(ProductUniqueCreate, self).form_invalid(form)
        except IntegrityError:
            errors = form._errors.setdefault("value", ErrorList())
            errors.append(_("Value existing"))
            return super(ProductUniqueCreate, self).form_invalid(form)
项目:django-codenerix-products    作者:centrologic    | 项目源码 | 文件源码
def save(self, *args, **kwargs):
        product_final = ProductFinal.objects.filter(pk=self.product_final_id).first()
        # se comprueba que no se repite el valor de las caracteristicas especiales de los productos finales cuando sean unicas
        if product_final:
            if product_final.product.feature_special and product_final.product.feature_special.unique:
                if ProductUnique.objects.filter(
                    value=self.value,
                    product_final__product=product_final.product
                ).exists():
                    raise ValidationError(_('Ya existe un producto final con el valor de la caracteristicas especial'))
        else:
            raise ValidationError(_("Product don't seleted"))

        # save and update stock of product final
        with transaction.atomic():
            r = super(ProductUnique, self).save(*args, **kwargs)
            product_final.stock_real = ProductUnique.objects.filter(product_final=product_final).aggregate(stock=Sum('stock_real'))['stock']
            product_final.save()
            return r


# producto estrella (solo un registro publico)
项目:Plamber    作者:OlegKlimenko    | 项目源码 | 文件源码
def upload_avatar(request):
    """
    Sets new user's avatar.
    """
    with transaction.atomic():
        profile_user = get_object_or_404(TheUser, auth_token=request.data.get('user_token'))

        try:
            profile_user.user_photo.save('user_{}.png'.format(profile_user.id), request.data.get('file'))
            profile_user.save()
            logger.info("User '{}' changed his avatar.".format(profile_user))

            resize_image(profile_user.user_photo.path, AVATAR_WIDTH)
            logger.info("Image '{}' successfully resized!".format(profile_user.user_photo.path))

            return Response({'status': 200,
                             'detail': 'successful',
                             'data': {'profile_image': profile_user.user_photo.url}})

        except ValidationError:
            logger.info("User '{}' tried to upload not an image as avatar!".format(profile_user))

            return Response({'status': 404,
                             'detail': 'tried to upload not an image',
                             'data': {}})
项目:Bitpoll    作者:fsinfuhh    | 项目源码 | 文件源码
def change_email(request, token):
    try:
        data = signing.loads(token, max_age=TOKEN_MAX_AGE)
    except signing.SignatureExpired:
        return TemplateResponse(request, 'registration/token_expired.html')
    except signing.BadSignature:
        return TemplateResponse(request, 'registration/token_invalid.html')
    if request.user.username != data.get('username'):
        return TemplateResponse(request, 'registration/token_invalid.html')
    email = data.get('email')
    try:
        validate_email(email)
    except ValidationError:
        return TemplateResponse(request, 'registration/token_invalid.html')
    request.user.email = email
    request.user.save()

    messages.success(request, _('Your email address has been changed.'))
    return redirect('registration_account')
项目:openbare    作者:openbare    | 项目源码 | 文件源码
def renew(self):
        """Renew lendable.

        If renewals are available update the due_on date by adding
        another period equal to lending_period_in_days.

        If no renewals available raise error and display message to user.
        """
        if self.renewals > 0:
            self.renewals -= 1
            self.due_on = self.due_on + timedelta(self.lending_period_in_days)
        else:
            raise ValidationError(
                _("No more renewals are available for this item.")
            )
        return self.save()
项目:WPS-4th    作者:Fastcampus-WPS    | 项目源码 | 文件源码
def clean_recipient_numbers(self):
        cleaned_numbers = []
        error_numbers = []
        # 0?? ???? ?? 9? ?? 10?? ???? ??
        p = re.compile(r'^0\d{9}\d?$')
        number_string = self.cleaned_data['recipient_numbers']
        print(number_string)
        # ???? ?? '-'??? ''(? ???)? ?????
        sub_string = re.sub(r'\s|-', '', number_string)
        print(sub_string)
        # , ?? .? ???? ???? ??? ???? ??? numbers? ??
        numbers = re.split(r',|\.', sub_string)
        print(numbers)
        for number in numbers:
            if re.match(p, number):
                cleaned_numbers.append(number)
            else:
                error_numbers.append(number)

        if error_numbers:
            raise ValidationError('Invalid phone number format! {}'.format(', '.join(error_numbers)))
        return cleaned_numbers
项目:mos-horizon    作者:Mirantis    | 项目源码 | 文件源码
def test_clean_file_upload_form_invalid_json(self):
        kwargs = {'next_view': 'Launch Stack'}
        t = forms.TemplateForm({}, **kwargs)
        precleaned = {
            'template_data': 'http://templateurl.com',
        }
        json_str = '{notvalidjson::::::json/////json'
        files = {'template_upload':
                 self.SimpleFile('template_name', json_str)}

        self.assertRaises(
            exceptions.ValidationError,
            t.clean_uploaded_files,
            'template',
            'template',
            precleaned,
            files)
项目:lightning-coindesk    作者:lightninglabs    | 项目源码 | 文件源码
def clean(self, value):
        if not value and not self.required:
            return None

        if not value.startswith(u"1") and not value.startswith(u"3"):
            raise ValidationError(self.error_messages['invalid'])
        value = value.strip()

        if "\n" in value:
            raise ValidationError(u"Multiple lines in the bitcoin address")

        if " " in value:
            raise ValidationError(u"Spaces in the bitcoin address")

        if re.match(r"[a-zA-Z1-9]{27,35}$", value) is None:
            raise ValidationError(self.error_messages['invalid'])
        version = get_bcaddress_version(value)
        if version is None:
            raise ValidationError(self.error_messages['invalid'])
        return value
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def has_changed(self, initial, data):
        """
        Return True if data differs from initial.
        """
        try:
            data = self.to_python(data)
            if hasattr(self, '_coerce'):
                return self._coerce(data) != self._coerce(initial)
        except ValidationError:
            return True
        # For purposes of seeing whether something has changed, None is
        # the same as an empty string, if the data or initial value we get
        # is None, replace it with ''.
        initial_value = initial if initial is not None else ''
        data_value = data if data is not None else ''
        return initial_value != data_value
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def to_python(self, value):
        """
        Validates that int() can be called on the input. Returns the result
        of int(). Returns None for empty values.
        """
        value = super(IntegerField, self).to_python(value)
        if value in self.empty_values:
            return None
        if self.localize:
            value = formats.sanitize_separators(value)
        # Strip trailing decimal and zeros.
        try:
            value = int(self.re_decimal.sub('', str(value)))
        except (ValueError, TypeError):
            raise ValidationError(self.error_messages['invalid'], code='invalid')
        return value
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def to_python(self, value):
        """
        Validates that the input is a decimal number. Returns a Decimal
        instance. Returns None for empty values. Ensures that there are no more
        than max_digits in the number, and no more than decimal_places digits
        after the decimal point.
        """
        if value in self.empty_values:
            return None
        if self.localize:
            value = formats.sanitize_separators(value)
        value = smart_text(value).strip()
        try:
            value = Decimal(value)
        except DecimalException:
            raise ValidationError(self.error_messages['invalid'], code='invalid')
        return value
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def clean(self, data, initial=None):
        # If the widget got contradictory inputs, we raise a validation error
        if data is FILE_INPUT_CONTRADICTION:
            raise ValidationError(self.error_messages['contradiction'], code='contradiction')
        # False means the field value should be cleared; further validation is
        # not needed.
        if data is False:
            if not self.required:
                return False
            # If the field is required, clearing is not possible (the widget
            # shouldn't return False data in that case anyway). False is not
            # in self.empty_value; if a False value makes it this far
            # it should be validated from here on out as None (so it will be
            # caught by the required check).
            data = None
        if not data and initial:
            return initial
        return super(FileField, self).clean(data)
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def _coerce(self, value):
        """
        Validates that the values are in self.choices and can be coerced to the
        right type.
        """
        if value == self.empty_value or value in self.empty_values:
            return self.empty_value
        new_value = []
        for choice in value:
            try:
                new_value.append(self.coerce(choice))
            except (ValueError, TypeError, ValidationError):
                raise ValidationError(
                    self.error_messages['invalid_choice'],
                    code='invalid_choice',
                    params={'value': choice},
                )
        return new_value
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def management_form(self):
        """Returns the ManagementForm instance for this FormSet."""
        if self.is_bound:
            form = ManagementForm(self.data, auto_id=self.auto_id, prefix=self.prefix)
            if not form.is_valid():
                raise ValidationError(
                    _('ManagementForm data is missing or has been tampered with'),
                    code='missing_management_form',
                )
        else:
            form = ManagementForm(auto_id=self.auto_id, prefix=self.prefix, initial={
                TOTAL_FORM_COUNT: self.total_form_count(),
                INITIAL_FORM_COUNT: self.initial_form_count(),
                MIN_NUM_FORM_COUNT: self.min_num,
                MAX_NUM_FORM_COUNT: self.max_num
            })
        return form
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def _clean_fields(self):
        for name, field in self.fields.items():
            # value_from_datadict() gets the data from the data dictionaries.
            # Each widget type knows how to retrieve its own data, because some
            # widgets split data over several HTML fields.
            if field.disabled:
                value = self.initial.get(name, field.initial)
            else:
                value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name))
            try:
                if isinstance(field, FileField):
                    initial = self.initial.get(name, field.initial)
                    value = field.clean(value, initial)
                else:
                    value = field.clean(value)
                self.cleaned_data[name] = value
                if hasattr(self, 'clean_%s' % name):
                    value = getattr(self, 'clean_%s' % name)()
                    self.cleaned_data[name] = value
            except ValidationError as e:
                self.add_error(name, e)
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def changed_data(self):
        data = []
        for name, field in self.fields.items():
            prefixed_name = self.add_prefix(name)
            data_value = field.widget.value_from_datadict(self.data, self.files, prefixed_name)
            if not field.show_hidden_initial:
                initial_value = self.initial.get(name, field.initial)
                if callable(initial_value):
                    initial_value = initial_value()
            else:
                initial_prefixed_name = self.add_initial_prefix(name)
                hidden_widget = field.hidden_widget()
                try:
                    initial_value = field.to_python(hidden_widget.value_from_datadict(
                        self.data, self.files, initial_prefixed_name))
                except ValidationError:
                    # Always assume data has changed if validation fails.
                    data.append(name)
                    continue
            if field.has_changed(initial_value, data_value):
                data.append(name)
        return data
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def __call__(self, value):
        value = force_text(value)

        if not value or '@' not in value:
            raise ValidationError(self.message, code=self.code)

        user_part, domain_part = value.rsplit('@', 1)

        if not self.user_regex.match(user_part):
            raise ValidationError(self.message, code=self.code)

        if (domain_part not in self.domain_whitelist and
                not self.validate_domain_part(domain_part)):
            # Try for possible IDN domain-part
            try:
                domain_part = domain_part.encode('idna').decode('ascii')
                if self.validate_domain_part(domain_part):
                    return
            except UnicodeError:
                pass
            raise ValidationError(self.message, code=self.code)
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def validate_password(password, user=None, password_validators=None):
    """
    Validate whether the password meets all validator requirements.

    If the password is valid, return ``None``.
    If the password is invalid, raise ValidationError with all error messages.
    """
    errors = []
    if password_validators is None:
        password_validators = get_default_password_validators()
    for validator in password_validators:
        try:
            validator.validate(password, user)
        except ValidationError as error:
            errors.append(error)
    if errors:
        raise ValidationError(errors)
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def validate(self, password, user=None):
        if not user:
            return

        for attribute_name in self.user_attributes:
            value = getattr(user, attribute_name, None)
            if not value or not isinstance(value, string_types):
                continue
            value_parts = re.split('\W+', value) + [value]
            for value_part in value_parts:
                if SequenceMatcher(a=password.lower(), b=value_part.lower()).quick_ratio() > self.max_similarity:
                    verbose_name = force_text(user._meta.get_field(attribute_name).verbose_name)
                    raise ValidationError(
                        _("The password is too similar to the %(verbose_name)s."),
                        code='password_too_similar',
                        params={'verbose_name': verbose_name},
                    )
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def to_python(self, value):
        if value:
            items = value.split(self.delimiter)
        else:
            items = []
        errors = []
        values = []
        for i, item in enumerate(items):
            try:
                values.append(self.base_field.to_python(item))
            except ValidationError as e:
                for error in e.error_list:
                    errors.append(ValidationError(
                        string_concat(self.error_messages['item_invalid'], error.message),
                        code='item_invalid',
                        params={'nth': i},
                    ))
        if errors:
            raise ValidationError(errors)
        return values
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def to_python(self, value):
        if not value:
            return {}
        if not isinstance(value, dict):
            try:
                value = json.loads(value)
            except ValueError:
                raise ValidationError(
                    self.error_messages['invalid_json'],
                    code='invalid_json',
                )

        if not isinstance(value, dict):
            raise ValidationError(
                self.error_messages['invalid_format'],
                code='invalid_format',
            )

        # Cast everything to strings for ease.
        for key, val in value.items():
            value[key] = six.text_type(val)
        return value
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def compress(self, values):
        if not values:
            return None
        lower, upper = values
        if lower is not None and upper is not None and lower > upper:
            raise exceptions.ValidationError(
                self.error_messages['bound_ordering'],
                code='bound_ordering',
            )
        try:
            range_value = self.range_type(lower, upper)
        except TypeError:
            raise exceptions.ValidationError(
                self.error_messages['invalid'],
                code='invalid',
            )
        else:
            return range_value
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def validate(self, value, model_instance):
        super(ArrayField, self).validate(value, model_instance)
        for i, part in enumerate(value):
            try:
                self.base_field.validate(part, model_instance)
            except exceptions.ValidationError as e:
                raise exceptions.ValidationError(
                    string_concat(self.error_messages['item_invalid'], e.message),
                    code='item_invalid',
                    params={'nth': i},
                )
        if isinstance(self.base_field, ArrayField):
            if len({len(i) for i in value}) > 1:
                raise exceptions.ValidationError(
                    self.error_messages['nested_array_mismatch'],
                    code='nested_array_mismatch',
                )
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def validate(self, value, model_instance):
        if self.remote_field.parent_link:
            return
        super(ForeignKey, self).validate(value, model_instance)
        if value is None:
            return

        using = router.db_for_read(model_instance.__class__, instance=model_instance)
        qs = self.remote_field.model._default_manager.using(using).filter(
            **{self.remote_field.field_name: value}
        )
        qs = qs.complex_filter(self.get_limit_choices_to())
        if not qs.exists():
            raise exceptions.ValidationError(
                self.error_messages['invalid'],
                code='invalid',
                params={
                    'model': self.remote_field.model._meta.verbose_name, 'pk': value,
                    'field': self.remote_field.field_name, 'value': value,
                },  # 'pk' is included for backwards compatibility
            )
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def to_python(self, value):
        if value is None:
            return value
        if isinstance(value, datetime.timedelta):
            return value
        try:
            parsed = parse_duration(value)
        except ValueError:
            pass
        else:
            if parsed is not None:
                return parsed

        raise exceptions.ValidationError(
            self.error_messages['invalid'],
            code='invalid',
            params={'value': value},
        )
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def to_python(self, value):
        if value is None:
            return None
        if value in (True, False):
            return bool(value)
        if value in ('None',):
            return None
        if value in ('t', 'True', '1'):
            return True
        if value in ('f', 'False', '0'):
            return False
        raise exceptions.ValidationError(
            self.error_messages['invalid'],
            code='invalid',
            params={'value': value},
        )
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def has_changed(self, initial, data):
        """
        Return True if data differs from initial.
        """
        try:
            data = self.to_python(data)
            if hasattr(self, '_coerce'):
                return self._coerce(data) != self._coerce(initial)
        except ValidationError:
            return True
        # For purposes of seeing whether something has changed, None is
        # the same as an empty string, if the data or initial value we get
        # is None, replace it with ''.
        initial_value = initial if initial is not None else ''
        data_value = data if data is not None else ''
        return initial_value != data_value
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def to_python(self, value):
        """
        Validates that int() can be called on the input. Returns the result
        of int(). Returns None for empty values.
        """
        value = super(IntegerField, self).to_python(value)
        if value in self.empty_values:
            return None
        if self.localize:
            value = formats.sanitize_separators(value)
        # Strip trailing decimal and zeros.
        try:
            value = int(self.re_decimal.sub('', force_text(value)))
        except (ValueError, TypeError):
            raise ValidationError(self.error_messages['invalid'], code='invalid')
        return value
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def to_python(self, value):
        """
        Validates that the input is a decimal number. Returns a Decimal
        instance. Returns None for empty values. Ensures that there are no more
        than max_digits in the number, and no more than decimal_places digits
        after the decimal point.
        """
        if value in self.empty_values:
            return None
        if self.localize:
            value = formats.sanitize_separators(value)
        value = smart_text(value).strip()
        try:
            value = Decimal(value)
        except DecimalException:
            raise ValidationError(self.error_messages['invalid'], code='invalid')
        return value
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def clean(self, data, initial=None):
        # If the widget got contradictory inputs, we raise a validation error
        if data is FILE_INPUT_CONTRADICTION:
            raise ValidationError(self.error_messages['contradiction'], code='contradiction')
        # False means the field value should be cleared; further validation is
        # not needed.
        if data is False:
            if not self.required:
                return False
            # If the field is required, clearing is not possible (the widget
            # shouldn't return False data in that case anyway). False is not
            # in self.empty_value; if a False value makes it this far
            # it should be validated from here on out as None (so it will be
            # caught by the required check).
            data = None
        if not data and initial:
            return initial
        return super(FileField, self).clean(data)
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def _coerce(self, value):
        """
        Validates that the values are in self.choices and can be coerced to the
        right type.
        """
        if value == self.empty_value or value in self.empty_values:
            return self.empty_value
        new_value = []
        for choice in value:
            try:
                new_value.append(self.coerce(choice))
            except (ValueError, TypeError, ValidationError):
                raise ValidationError(
                    self.error_messages['invalid_choice'],
                    code='invalid_choice',
                    params={'value': choice},
                )
        return new_value
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def management_form(self):
        """Returns the ManagementForm instance for this FormSet."""
        if self.is_bound:
            form = ManagementForm(self.data, auto_id=self.auto_id, prefix=self.prefix)
            if not form.is_valid():
                raise ValidationError(
                    _('ManagementForm data is missing or has been tampered with'),
                    code='missing_management_form',
                )
        else:
            form = ManagementForm(auto_id=self.auto_id, prefix=self.prefix, initial={
                TOTAL_FORM_COUNT: self.total_form_count(),
                INITIAL_FORM_COUNT: self.initial_form_count(),
                MIN_NUM_FORM_COUNT: self.min_num,
                MAX_NUM_FORM_COUNT: self.max_num
            })
        return form
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def _clean_fields(self):
        for name, field in self.fields.items():
            # value_from_datadict() gets the data from the data dictionaries.
            # Each widget type knows how to retrieve its own data, because some
            # widgets split data over several HTML fields.
            if field.disabled:
                value = self.initial.get(name, field.initial)
            else:
                value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name))
            try:
                if isinstance(field, FileField):
                    initial = self.initial.get(name, field.initial)
                    value = field.clean(value, initial)
                else:
                    value = field.clean(value)
                self.cleaned_data[name] = value
                if hasattr(self, 'clean_%s' % name):
                    value = getattr(self, 'clean_%s' % name)()
                    self.cleaned_data[name] = value
            except ValidationError as e:
                self.add_error(name, e)
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def changed_data(self):
        data = []
        for name, field in self.fields.items():
            prefixed_name = self.add_prefix(name)
            data_value = field.widget.value_from_datadict(self.data, self.files, prefixed_name)
            if not field.show_hidden_initial:
                initial_value = self.initial.get(name, field.initial)
                if callable(initial_value):
                    initial_value = initial_value()
            else:
                initial_prefixed_name = self.add_initial_prefix(name)
                hidden_widget = field.hidden_widget()
                try:
                    initial_value = field.to_python(hidden_widget.value_from_datadict(
                        self.data, self.files, initial_prefixed_name))
                except ValidationError:
                    # Always assume data has changed if validation fails.
                    data.append(name)
                    continue
            if field.has_changed(initial_value, data_value):
                data.append(name)
        return data
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def __call__(self, value):
        value = force_text(value)

        if not value or '@' not in value:
            raise ValidationError(self.message, code=self.code)

        user_part, domain_part = value.rsplit('@', 1)

        if not self.user_regex.match(user_part):
            raise ValidationError(self.message, code=self.code)

        if (domain_part not in self.domain_whitelist and
                not self.validate_domain_part(domain_part)):
            # Try for possible IDN domain-part
            try:
                domain_part = domain_part.encode('idna').decode('ascii')
                if self.validate_domain_part(domain_part):
                    return
            except UnicodeError:
                pass
            raise ValidationError(self.message, code=self.code)
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def validate_password(password, user=None, password_validators=None):
    """
    Validate whether the password meets all validator requirements.

    If the password is valid, return ``None``.
    If the password is invalid, raise ValidationError with all error messages.
    """
    errors = []
    if password_validators is None:
        password_validators = get_default_password_validators()
    for validator in password_validators:
        try:
            validator.validate(password, user)
        except ValidationError as error:
            errors.append(error)
    if errors:
        raise ValidationError(errors)
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def validate(self, password, user=None):
        if not user:
            return

        for attribute_name in self.user_attributes:
            value = getattr(user, attribute_name, None)
            if not value or not isinstance(value, string_types):
                continue
            value_parts = re.split('\W+', value) + [value]
            for value_part in value_parts:
                if SequenceMatcher(a=password.lower(), b=value_part.lower()).quick_ratio() > self.max_similarity:
                    verbose_name = force_text(user._meta.get_field(attribute_name).verbose_name)
                    raise ValidationError(
                        _("The password is too similar to the %(verbose_name)s."),
                        code='password_too_similar',
                        params={'verbose_name': verbose_name},
                    )
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def to_python(self, value):
        if value:
            items = value.split(self.delimiter)
        else:
            items = []
        errors = []
        values = []
        for index, item in enumerate(items):
            try:
                values.append(self.base_field.to_python(item))
            except ValidationError as error:
                errors.append(prefix_validation_error(
                    error,
                    prefix=self.error_messages['item_invalid'],
                    code='item_invalid',
                    params={'nth': index},
                ))
        if errors:
            raise ValidationError(errors)
        return values
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def to_python(self, value):
        if not value:
            return {}
        if not isinstance(value, dict):
            try:
                value = json.loads(value)
            except ValueError:
                raise ValidationError(
                    self.error_messages['invalid_json'],
                    code='invalid_json',
                )

        if not isinstance(value, dict):
            raise ValidationError(
                self.error_messages['invalid_format'],
                code='invalid_format',
            )

        # Cast everything to strings for ease.
        for key, val in value.items():
            value[key] = six.text_type(val)
        return value
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def compress(self, values):
        if not values:
            return None
        lower, upper = values
        if lower is not None and upper is not None and lower > upper:
            raise exceptions.ValidationError(
                self.error_messages['bound_ordering'],
                code='bound_ordering',
            )
        try:
            range_value = self.range_type(lower, upper)
        except TypeError:
            raise exceptions.ValidationError(
                self.error_messages['invalid'],
                code='invalid',
            )
        else:
            return range_value
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def __call__(self, value):
        keys = set(value.keys())
        missing_keys = self.keys - keys
        if missing_keys:
            raise ValidationError(
                self.messages['missing_keys'],
                code='missing_keys',
                params={'keys': ', '.join(missing_keys)},
            )
        if self.strict:
            extra_keys = keys - self.keys
            if extra_keys:
                raise ValidationError(
                    self.messages['extra_keys'],
                    code='extra_keys',
                    params={'keys': ', '.join(extra_keys)},
                )
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def validate(self, value, model_instance):
        super(ArrayField, self).validate(value, model_instance)
        for index, part in enumerate(value):
            try:
                self.base_field.validate(part, model_instance)
            except exceptions.ValidationError as error:
                raise prefix_validation_error(
                    error,
                    prefix=self.error_messages['item_invalid'],
                    code='item_invalid',
                    params={'nth': index},
                )
        if isinstance(self.base_field, ArrayField):
            if len({len(i) for i in value}) > 1:
                raise exceptions.ValidationError(
                    self.error_messages['nested_array_mismatch'],
                    code='nested_array_mismatch',
                )
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def prefix_validation_error(error, prefix, code, params):
    """
    Prefix a validation error message while maintaining the existing
    validation data structure.
    """
    if error.error_list == [error]:
        error_params = error.params or {}
        return ValidationError(
            # We can't simply concatenate messages since they might require
            # their associated parameters to be expressed correctly which
            # is not something `string_concat` does. For example, proxied
            # ungettext calls require a count parameter and are converted
            # to an empty string if they are missing it.
            message=string_concat(
                SimpleLazyObject(lambda: prefix % params),
                SimpleLazyObject(lambda: error.message % error_params),
            ),
            code=code,
            params=dict(error_params, **params),
        )
    return ValidationError([
        prefix_validation_error(e, prefix, code, params) for e in error.error_list
    ])
项目:django-modeltrans    作者:zostera    | 项目源码 | 文件源码
def test_clean(self):
        '''
        Blog has required_languages=('nl', ), so this should raise an error
        if `title_nl` is not set.
        '''
        m = Blog(title='Horse', body='Horses are nice')

        with self.assertRaises(ValidationError) as e:
            m.full_clean()

        self.assertEquals(
            {(field, tuple(errors)) for field, errors in e.exception},
            {
                ('title_nl', ('This field cannot be null.', )),
                ('body_nl', ('This field cannot be null.', ))
            }
        )

        # With an added `title_nl`, it should validate.
        m.title_nl = 'Paard'
        m.body_nl = 'foo'
        m.full_clean()
项目:planet-b-saleor    作者:planet-b    | 项目源码 | 文件源码
def validate_shipping_address(view):
    """Decorate a view making it require a valid shipping address.

    Expects to be decorated with `@validate_cart`.

    If either the shipping address or customer email is empty redirects to the
    shipping address step.
    """
    @wraps(view)
    def func(request, checkout):
        if checkout.email is None or checkout.shipping_address is None:
            return redirect('checkout:shipping-address')
        try:
            checkout.shipping_address.full_clean()
        except ValidationError:
            return redirect('checkout:shipping-address')
        return view(request, checkout)
    return func
项目:zing    作者:evernote    | 项目源码 | 文件源码
def test_create_project_reserved_code(english, reserved_code):
    """Tests projects are not created with reserved project codes."""

    with pytest.raises(ValidationError):
        Project(
            code=reserved_code,
            fullname="whatever",
            source_language=english
        ).save()

    reserved_code_with_padding = "  %s  " % reserved_code
    with pytest.raises(ValidationError):
        Project(
            code=reserved_code_with_padding,
            fullname="whatever",
            source_language=english
        ).save()
项目:socialhome    作者:jaywink    | 项目源码 | 文件源码
def _share(self):
        content = self.get_object()
        try:
            share = content.share(self.request.user.profile)
        except ValidationError as e:
            raise exceptions.ValidationError(e.message)
        except Exception:
            raise exceptions.APIException("Unknown error when creating share.")
        return Response({"status": "ok", "content_id": share.id}, status=HTTP_201_CREATED)
项目:socialhome    作者:jaywink    | 项目源码 | 文件源码
def _unshare(self):
        content = self.get_object()
        try:
            content.unshare(self.request.user.profile)
        except ValidationError as e:
            raise exceptions.ValidationError(e.message)
        except Exception:
            raise exceptions.APIException("Unknown error when creating share.")
        return Response({"status": "ok"}, status=HTTP_204_NO_CONTENT)