Python django.core.validators 模块,EMPTY_VALUES 实例源码

我们从Python开源项目中,提取了以下31个代码示例,用于说明如何使用django.core.validators.EMPTY_VALUES

项目:stormtrooper    作者:CompileInc    | 项目源码 | 文件源码
def process(cls, answers):
        import re
        import tldextract
        from django.core.validators import EMPTY_VALUES
        _answers = []
        for answer in answers:
            extract = tldextract.extract(answer.decode('utf-8'))
            if extract.domain in EMPTY_VALUES or\
               extract.suffix in EMPTY_VALUES:
                tmp_domain = ''
            else:
                extract = list(extract)
                tmp_domain = ".".join(extract)
                p = re.compile("^[w]{1,3}([\d]{0,2})?\.")
                m = p.search(tmp_domain)
                if m:
                    tmp_domain = tmp_domain[len(m.group(0)):]

            _answers.append(tmp_domain.lstrip(".").lower())
        return _answers
项目:stormtrooper    作者:CompileInc    | 项目源码 | 文件源码
def normalize_website(cls, w):
        from django.core.validators import EMPTY_VALUES
        from urlparse import urlparse, urlunparse, ParseResult
        w = w.decode('utf-8')
        if w in EMPTY_VALUES:
            return None
        w = w.lower().strip()
        if not w.startswith('http://') and not w.startswith('https://'):
            w = 'http://' + w.lstrip('/')
        try:
            parsed = urlparse(w)
        except ValueError as e:
            return None
        else:
            new_parsed = ParseResult(scheme='http',
                                     netloc=cls.get_website_tld(w),
                                     path=parsed.path.rstrip('/'),
                                     params='',
                                     query=parsed.query,
                                     fragment='')
            return urlunparse(new_parsed)
项目:esdc-ce    作者:erigones    | 项目源码 | 文件源码
def run_validators(self, value):
        if value in validators.EMPTY_VALUES:
            return

        errors = []

        for v in self.validators:
            try:
                v(value)
            except ValidationError as e:
                if hasattr(e, 'code') and e.code in self.error_messages:
                    message = self.error_messages[e.code]
                    if e.params:
                        message = message % e.params
                    errors.append(message)
                else:
                    errors.extend(e.messages)
        if errors:
            raise ValidationError(errors)
项目:esdc-ce    作者:erigones    | 项目源码 | 文件源码
def from_native(self, data):
        if data in validators.EMPTY_VALUES:
            return None

        # UploadedFile objects should have name and size attributes.
        try:
            file_name = data.name
            file_size = data.size
        except AttributeError:
            raise ValidationError(self.error_messages['invalid'])

        if self.max_length is not None and len(file_name) > self.max_length:
            error_values = {'max': self.max_length, 'length': len(file_name)}
            raise ValidationError(self.error_messages['max_length'] % error_values)
        if not file_name:
            raise ValidationError(self.error_messages['invalid'])
        if not self.allow_empty_file and not file_size:
            raise ValidationError(self.error_messages['empty'])

        return data
项目:maas    作者:maas    | 项目源码 | 文件源码
def clean_global_empty(self, value):
        """Make sure the value is not empty and is thus suitable to be
        feed to the sub fields' validators."""
        if not value or isinstance(value, (list, tuple)):
            # value is considered empty if it is in
            # validators.EMPTY_VALUES, or if each of the subvalues is
            # None.
            is_empty = (
                value in validators.EMPTY_VALUES or
                all(v is None for v in value))
            if is_empty:
                if self.required:
                    raise ValidationError(self.error_messages['required'])
                else:
                    return None
            else:
                return True
        else:
            raise ValidationError(self.error_messages['invalid'])
项目:ambulatorioAPI    作者:xsurfer    | 项目源码 | 文件源码
def clean(self, value):
        value = super(ITSocialSecurityNumberField, self).clean(value)
        if value in EMPTY_VALUES:
            return ''
        value = re.sub('\s', '', value).upper()
        # Entities SSN are numeric-only
        if value.isdigit():
            try:
                return vat_number_validation(value)
            except ValueError:
                raise ValidationError(self.error_messages['invalid'])
        # Person SSN
        else:
            try:
                return ssn_validation(value)
            except (ValueError, IndexError):
                raise ValidationError(self.error_messages['invalid'])
项目:stormtrooper    作者:CompileInc    | 项目源码 | 文件源码
def save(self, *args, **kwargs):
        if self.slug in EMPTY_VALUES:
            rs = ''.join(random.choice(string.lowercase) for i in range(10))
            content = "{}{}".format(str(self.question),
                                    str(rs))
            self.slug = hashlib.sha1(content).hexdigest()

        return super(Question, self).save(*args, **kwargs)
项目:stormtrooper    作者:CompileInc    | 项目源码 | 文件源码
def compute_answer(self, answers, is_best_of):
        answer = None
        votes = None
        computed = False
        if self.task.answer_plugin:
            plugin = get_plugin(self.task.answer_plugin)
            if plugin.COMPUTE_ANSWER:
                # Plugins should return answers and votes because if a plugin
                # performs a transformation on answers, that info would be lost when
                # trying to count votes separately
                answer, votes = plugin.process(answers)
                computed = True
            else:
                answers = [ans for ans in get_plugin(self.task.answer_plugin).process(answers) if ans not in EMPTY_VALUES]
        if not answer and not votes and not computed:
            if len(answers) < Task.MIN_TO_ANSWER:
                answer = ""
            else:
                most_common = Counter(answers).most_common(1)[0]
                votes = most_common[1]
                if is_best_of:
                    cutoff = max(len(answers) // 2, Task.MIN_TO_ANSWER)
                    if votes >= cutoff:
                        answer = most_common[0]
                    else:
                        votes = None
                        answer = ""
                else:
                    answer = most_common[0]
        return {'ST_TASK_%s_ANSWER' % (self.task.id): answer,
                'ST_TASK_%s_VOTES' % (self.task.id): votes}
项目:stormtrooper    作者:CompileInc    | 项目源码 | 文件源码
def __unicode__(self):
        answer = self.answer
        try:
            choice_id = self.answer.get("choice_id")
            if choice_id and choice_id not in EMPTY_VALUES:
                answer = unicode(Choice.objects.get(task=self.question.task,
                                                    id=int(choice_id)))
            else:
                answer = self.cleaned_answer()
        except AttributeError:
            pass
        return answer
项目:stormtrooper    作者:CompileInc    | 项目源码 | 文件源码
def cleaned_answer(self):
        choice_id = self.answer.get("choice_id")
        if not choice_id or choice_id in EMPTY_VALUES:
            answer = self.answer['verbose']
            # remove multiple spaces
            return ' '.join(answer.split())
        return str(self)
项目:stormtrooper    作者:CompileInc    | 项目源码 | 文件源码
def process(cls, answers):
        from collections import defaultdict
        from django.core.validators import EMPTY_VALUES
        websites = [w for w in map(cls.normalize_website, answers) if w is not None]
        result_website = None
        votes = 0
        website_tlds = defaultdict(list)
        _website_tlds = []
        for w in websites:
            website_tld = cls.get_website_tld(w)
            if website_tld:
                _website_tlds.append(website_tld)
                website_tlds[website_tld].append(w)
        if _website_tlds not in EMPTY_VALUES:
            common_website_tld = cls.get_majority_item(_website_tlds)
            if common_website_tld is None:
                return (None, 0)
            common_websites = website_tlds[common_website_tld]
            common_website = cls.get_majority_item(common_websites)
            if common_website:
                    result_website = common_website
            else:
                result_website = cls.normalize_website(cls.get_website_tld(common_websites[0]))
            for website in websites:
                if result_website in website:
                    votes += 1
        return (result_website, votes)
项目:DreamRich    作者:DreamRich    | 项目源码 | 文件源码
def validate_cpf(value):
    '''
    Value can be either a string in the format XXX.XXX.XXX-XX or an
    11-digit number.
    '''

    if value in EMPTY_VALUES:
        return u''
    if not value.isdigit():
        value = re.sub(r'[-\.]', '', value)
    orig_value = value[:]
    try:
        int(value)
    except ValueError:
        raise ValidationError(ERROR_MESSAGES['digits_only'])
    if len(value) != 11:
        raise ValidationError(ERROR_MESSAGES['max_digits'])
    orig_dv = value[-2:]

    first_digit_verify = sum([i * int(value[idx])
                              for idx, i in enumerate(range(10, 1, -1))])
    first_digit_verify = verifying_digit_maker(first_digit_verify % 11)
    value = value[:-2] + str(first_digit_verify) + value[-1]
    seccond_digit_verify = sum([i * int(value[idx])
                                for idx, i in enumerate(range(11, 1, -1))])
    seccond_digit_verify = verifying_digit_maker(seccond_digit_verify % 11)
    value = value[:-1] + str(seccond_digit_verify)
    if value[-2:] != orig_dv:
        raise ValidationError(ERROR_MESSAGES['invalid'])

    return orig_value
项目:ecs    作者:ecs-org    | 项目源码 | 文件源码
def require_fields(form, fields):
    for f in fields:
        val = form.cleaned_data.get(f, None)
        if val in EMPTY_VALUES or \
            (isinstance(val, QuerySet) and not val.exists()):
            form.add_error(f, form.fields[f].error_messages['required'])
项目:munch-core    作者:crunchmail    | 项目源码 | 文件源码
def _default_ordering_field(self):
        if self._meta.order_by:
            order_field = self.form.fields[self.order_by_field]
            data = self.form[self.order_by_field].data
            ordered_value = None
            try:
                ordered_value = order_field.clean(data)
            except forms.ValidationError:
                pass
            if ordered_value in EMPTY_VALUES and self.strict:
                ordered_value = self.form.fields[
                    self.order_by_field].choices[0][0]

            return ordered_value
项目:esdc-ce    作者:erigones    | 项目源码 | 文件源码
def validate(self, value):
        if not self.allow_empty and value in validators.EMPTY_VALUES:
            raise ValidationError(self.error_messages['required'])
项目:esdc-ce    作者:erigones    | 项目源码 | 文件源码
def from_native(self, value):
        value = super(ChoiceField, self).from_native(value)
        if value == self.empty or value in validators.EMPTY_VALUES:
            return self.empty
        return value
项目:esdc-ce    作者:erigones    | 项目源码 | 文件源码
def from_native(self, value):
        if value in validators.EMPTY_VALUES:
            return None

        if isinstance(value, datetime.datetime):
            if timezone and settings.USE_TZ and timezone.is_aware(value):
                # Convert aware datetimes to the default time zone
                # before casting them to dates (#17742).
                default_timezone = timezone.get_default_timezone()
                value = timezone.make_naive(value, default_timezone)
            return value.date()
        if isinstance(value, datetime.date):
            return value

        for fmt in self.input_formats:
            if fmt.lower() == ISO_8601:
                try:
                    parsed = parse_date(value)
                except (ValueError, TypeError):
                    pass
                else:
                    if parsed is not None:
                        return parsed
            else:
                try:
                    parsed = datetime.datetime.strptime(value, fmt)
                except (ValueError, TypeError):
                    pass
                else:
                    return parsed.date()

        msg = self.error_messages['invalid'] % readable_date_formats(self.input_formats)

        raise ValidationError(msg)
项目:esdc-ce    作者:erigones    | 项目源码 | 文件源码
def from_native(self, value):
        if value in validators.EMPTY_VALUES:
            return None

        if isinstance(value, datetime.datetime):
            return value
        if isinstance(value, datetime.date):
            value = datetime.datetime(value.year, value.month, value.day)
            if settings.USE_TZ:
                # For backwards compatibility, interpret naive datetimes in
                # local time. This won't work during DST change, but we can't
                # do much about it, so we let the exceptions percolate up the
                # call stack.
                warnings.warn("DateTimeField received a naive datetime (%s)"
                              " while time zone support is active." % value,
                              RuntimeWarning)
                default_timezone = timezone.get_default_timezone()
                value = timezone.make_aware(value, default_timezone)
            return value

        for fmt in self.input_formats:
            if fmt.lower() == ISO_8601:
                try:
                    parsed = parse_datetime(value)
                except (ValueError, TypeError):
                    pass
                else:
                    if parsed is not None:
                        return parsed
            else:
                try:
                    parsed = datetime.datetime.strptime(value, fmt)
                except (ValueError, TypeError):
                    pass
                else:
                    return parsed

        msg = self.error_messages['invalid'] % readable_datetime_formats(self.input_formats)

        raise ValidationError(msg)
项目:esdc-ce    作者:erigones    | 项目源码 | 文件源码
def from_native(self, value):
        if value in validators.EMPTY_VALUES:
            return None

        try:
            value = int(str(value))
        except (ValueError, TypeError):
            raise ValidationError(self.error_messages['invalid'])
        return value
项目:esdc-ce    作者:erigones    | 项目源码 | 文件源码
def from_native(self, value):
        if value in validators.EMPTY_VALUES:
            return None

        try:
            return float(value)
        except (TypeError, ValueError):
            msg = self.error_messages['invalid'] % value
            raise ValidationError(msg)
项目:esdc-ce    作者:erigones    | 项目源码 | 文件源码
def from_native(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 validators.EMPTY_VALUES:
            return None
        value = smart_text(value).strip()
        try:
            value = Decimal(value)
        except DecimalException:
            raise ValidationError(self.error_messages['invalid'])
        return value
项目:esdc-ce    作者:erigones    | 项目源码 | 文件源码
def validate(self, value):
        super(DecimalField, self).validate(value)
        if value in validators.EMPTY_VALUES:
            return
        # Check for NaN, Inf and -Inf values. We can't compare directly for NaN,
        # since it is never equal to itself. However, NaN is the only value that
        # isn't equal to itself, so we can use this to identify NaN
        if value != value or value == Decimal("Inf") or value == Decimal("-Inf"):
            raise ValidationError(self.error_messages['invalid'])
        sign, digittuple, exponent = value.as_tuple()
        decimals = abs(exponent)
        # digittuple doesn't include any leading zeros.
        digits = len(digittuple)
        if decimals > digits:
            # We have leading zeros up to or past the decimal point.  Count
            # everything past the decimal point as a digit.  We do not count
            # 0 before the decimal point as a digit since that would mean
            # we would not allow max_digits = decimal_places.
            digits = decimals
        whole_digits = digits - decimals

        if self.max_digits is not None and digits > self.max_digits:
            raise ValidationError(self.error_messages['max_digits'] % self.max_digits)
        if self.decimal_places is not None and decimals > self.decimal_places:
            raise ValidationError(self.error_messages['max_decimal_places'] % self.decimal_places)
        if (self.max_digits is not None and self.decimal_places is not None and
                whole_digits > (self.max_digits - self.decimal_places)):
            raise ValidationError(self.error_messages['max_whole_digits'] % (self.max_digits - self.decimal_places))

        return value
项目:jiango    作者:yefei    | 项目源码 | 文件源码
def to_python(self, value):
        if value in EMPTY_VALUES:
            return ''
        return parse_humanize_second(value)
项目:legal    作者:tompecina    | 项目源码 | 文件源码
def to_python(self, value):
        if value in EMPTY_VALUES:
            return None
        if isinstance(value, datetime):
            return value.date()
        if isinstance(value, date):
            return value
        return super().to_python(value.replace(' ', ''))
项目:legal    作者:tompecina    | 项目源码 | 文件源码
def prepare_value(self, value):
        if value in EMPTY_VALUES:
            return None
        if not isinstance(value, STYPES):
            value = '{:.{prec}f}'.format(
                LocalFloat(value),
                prec=self.rounding)
        return value
项目:legal    作者:tompecina    | 项目源码 | 文件源码
def to_python(self, value):
        if value in EMPTY_VALUES:
            return None
        if isinstance(value, STYPES):
            value = proc_num(value)
        try:
            return round(float(value), self.rounding)
        except:
            raise ValidationError('Conversion error')
项目:legal    作者:tompecina    | 项目源码 | 文件源码
def to_python(self, value):
        if value in EMPTY_VALUES:
            return None
        if isinstance(value, STYPES):
            value = proc_num(value)
        try:
            return Decimal(value)
        except:
            raise ValidationError('Conversion error')
项目:legal    作者:tompecina    | 项目源码 | 文件源码
def to_python(self, value):
        if value in EMPTY_VALUES:
            return None
        if isinstance(value, STYPES):
            value = proc_num(value)
        try:
            return float(value)
        except:
            raise ValidationError('Conversion error')
项目:a4-opin    作者:liqd    | 项目源码 | 文件源码
def to_python(self, value):
        empty_featureset = '{"type":"FeatureCollection","features":[]}'
        if (value not in django_validators.EMPTY_VALUES and not
                value == empty_featureset):
            return super().to_python(value)
        else:
            return None
项目:maas    作者:maas    | 项目源码 | 文件源码
def clean_sub_fields(self, value):
        """'value' being the list of the values of the subfields, validate
        each subfield."""
        clean_data = []
        errors = ErrorList()
        # Remove the field corresponding to the SKIP_CHECK_NAME boolean field
        # if required.
        fields = self.fields if not self.skip_check else self.fields[:-1]
        for index, field in enumerate(fields):
            try:
                field_value = value[index]
            except IndexError:
                field_value = None
            # Set the field_value to the default value if not set.
            if field_value is None and field.initial not in (None, ''):
                field_value = field.initial
            # Check the field's 'required' field instead of the global
            # 'required' field to allow subfields to be required or not.
            if field.required and field_value in validators.EMPTY_VALUES:
                errors.append(
                    '%s: %s' % (field.label, self.error_messages['required']))
                continue
            try:
                clean_data.append(field.clean(field_value))
            except ValidationError as e:
                # Collect all validation errors in a single list, which we'll
                # raise at the end of clean(), rather than raising a single
                # exception for the first error we encounter.
                errors.extend(
                    '%s: %s' % (field.label, message)
                    for message in e.messages)
        if errors:
            raise ValidationError(errors)

        out = self.compress(clean_data)
        self.validate(out)
        return out
项目:maas    作者:maas    | 项目源码 | 文件源码
def decompress(self, value):
        """Returns a list of decompressed values for the given compressed
        value.  The given value can be assumed to be valid, but not
        necessarily non-empty."""
        if value not in validators.EMPTY_VALUES:
            return [value.get(name, None) for name in self.names]
        else:
            return [None] * len(self.names)