Python django.core.validators.EMPTY_VALUES Examples

The following are 30 code examples of django.core.validators.EMPTY_VALUES(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.core.validators , or try the search function .
Example #1
Source File: cleanup.py    From django-unused-media with MIT License 6 votes vote down vote up
def get_used_media():
    """
        Get media which are still used in models
    """

    media = set()

    for field in get_file_fields():
        is_null = {
            '%s__isnull' % field.name: True,
        }
        is_empty = {
            '%s' % field.name: '',
        }

        storage = field.storage

        for value in field.model._base_manager \
                .values_list(field.name, flat=True) \
                .exclude(**is_empty).exclude(**is_null):
            if value not in EMPTY_VALUES:
                media.add(storage.path(value))

    return media 
Example #2
Source File: __init__.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def run_validators(self, value):
        if value in validators.EMPTY_VALUES:
            return

        errors = []
        for v in self.validators:
            try:
                v(value)
            except exceptions.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 exceptions.ValidationError(errors) 
Example #3
Source File: fields.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def to_python(self, value):
        """
        Validates that the values are in self.choices and can be coerced to the
        right type.
        """
        value = super(TypedMultipleChoiceField, self).to_python(value)
        super(TypedMultipleChoiceField, self).validate(value)
        if value == self.empty_value or value in validators.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'] % {'value': choice})
        return new_value 
Example #4
Source File: fields.py    From esdc-ce with Apache License 2.0 6 votes vote down vote up
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) 
Example #5
Source File: fields.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def to_python(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 
Example #6
Source File: fields.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def to_python(self, value):
        """
        Validates that the input can be converted to a datetime. Returns a
        Python datetime.datetime object.
        """
        if value in validators.EMPTY_VALUES:
            return None
        if isinstance(value, datetime.datetime):
            return from_current_timezone(value)
        if isinstance(value, datetime.date):
            result = datetime.datetime(value.year, value.month, value.day)
            return from_current_timezone(result)
        if isinstance(value, list):
            # Input comes from a SplitDateTimeWidget, for example. So, it's two
            # components: date and time.
            if len(value) != 2:
                raise ValidationError(self.error_messages['invalid'])
            if value[0] in validators.EMPTY_VALUES and value[1] in validators.EMPTY_VALUES:
                return None
            value = '%s %s' % tuple(value)
        result = super(DateTimeField, self).to_python(value)
        return from_current_timezone(result) 
Example #7
Source File: fields.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
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) 
Example #8
Source File: config_forms.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
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"]) 
Example #9
Source File: fields.py    From esdc-ce with Apache License 2.0 6 votes vote down vote up
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 
Example #10
Source File: views.py    From django-clever-selects with MIT License 5 votes vote down vote up
def dispatch(self, request, *args, **kwargs):
        self.field = request.GET.get("field")
        self.field_value = request.GET.get("field_value", None)
        self.parent_field = request.GET.get("parent_field")
        self.parent_value = request.GET.get("parent_value")
        if self.parent_value in EMPTY_VALUES + ('None', ):
            return self.empty_response()
        return super(ChainedSelectChoicesView, self).dispatch(request, *args, **kwargs) 
Example #11
Source File: views.py    From django-clever-selects with MIT License 5 votes vote down vote up
def get_choices(self):
        choices = []
        if self.parent_value in EMPTY_VALUES + ('None', ) or self.get_child_set() is None:
            return []
        try:
            for obj in self.get_child_set().all():
                choices.append((obj.pk, str(obj)))
            return choices
        except ObjectDoesNotExist:
            return [] 
Example #12
Source File: forms.py    From django-clever-selects with MIT License 5 votes vote down vote up
def init_chained_choices(self, *args, **kwargs):
        self.chained_fields_names = self.get_fields_names_by_type(ChainedChoiceField)
        self.chained_model_fields_names = self.get_fields_names_by_type(ChainedModelChoiceField) + self.get_fields_names_by_type(ChainedModelMultipleChoiceField)
        self.user = kwargs.get('user', self.user)

        if kwargs.get('data', None) is not None:
            self.set_choices_via_ajax(kwargs['data'])

        elif len(args) > 0 and args[0] not in EMPTY_VALUES:
            self.set_choices_via_ajax(args[0])

        elif kwargs.get('instance', None) is not None:
            oldest_parent_field_names = list(set(self.get_oldest_parent_field_names()))
            youngest_child_names = list(set(self.get_youngest_children_field_names()))

            for youngest_child_name in youngest_child_names:
                self.find_instance_attr(kwargs['instance'], youngest_child_name)

            for oldest_parent_field_name in oldest_parent_field_names:
                try:
                    self.fields[oldest_parent_field_name].initial = getattr(self, '%s' % oldest_parent_field_name)
                except AttributeError:
                    pass

            self.set_choices_via_ajax()

        elif 'initial' in kwargs and kwargs['initial'] not in EMPTY_VALUES:
            self.set_choices_via_ajax(kwargs['initial'], is_initial=True)
        else:
            for field_name in self.chained_fields_names + self.chained_model_fields_names:
                empty_label = self.fields[field_name].empty_label
                self.fields[field_name].choices = [('', empty_label)] 
Example #13
Source File: forms.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def to_python(self, value):
        if value in validators.EMPTY_VALUES:
            raise ValidationError(self.error_messages['required'])
        try:
            value = int(value)
        except ValueError:
            raise forms.ValidationError("Invalid format")
        try:
            student = Person.objects.get(emplid=value)
        except Person.DoesNotExist:
            raise forms.ValidationError("Could not find student record")
        return student 
Example #14
Source File: forms.py    From django-clever-selects with MIT License 5 votes vote down vote up
def get_children_field_names(self, parent_name):
        if parent_name in EMPTY_VALUES:
            return []
        result = []
        for field_name in self.fields:
            field = self.fields[field_name]
            if getattr(field, 'parent_field', None) == parent_name:
                result.append(field_name)
        return result 
Example #15
Source File: views.py    From django-clever-selects with MIT License 5 votes vote down vote up
def dispatch(self, request, *args, **kwargs):
        self.field = request.GET.get("field")
        self.field_value = request.GET.get("field_value", None)
        self.parent_field = request.GET.get("parent_field")
        self.parent_value = request.GET.get("parent_value")
        if self.parent_value in EMPTY_VALUES + ('None', ):
            return self.empty_response()
        return super(ChainedSelectChoicesView, self).dispatch(request, *args, **kwargs) 
Example #16
Source File: views.py    From django-clever-selects with MIT License 5 votes vote down vote up
def get_choices(self):
        choices = []
        if self.parent_value in EMPTY_VALUES + ('None', ) or self.get_child_set() is None:
            return []
        try:
            for obj in self.get_child_set().all():
                choices.append((obj.pk, str(obj)))
            return choices
        except ObjectDoesNotExist:
            return [] 
Example #17
Source File: forms.py    From django-clever-selects with MIT License 5 votes vote down vote up
def init_chained_choices(self, *args, **kwargs):
        self.chained_fields_names = self.get_fields_names_by_type(ChainedChoiceField)
        self.chained_model_fields_names = self.get_fields_names_by_type(ChainedModelChoiceField) + self.get_fields_names_by_type(ChainedModelMultipleChoiceField)
        self.user = kwargs.get('user', self.user)

        if kwargs.get('data', None) is not None:
            self.set_choices_via_ajax(kwargs['data'])

        elif len(args) > 0 and args[0] not in EMPTY_VALUES:
            self.set_choices_via_ajax(args[0])

        elif kwargs.get('instance', None) is not None:
            oldest_parent_field_names = list(set(self.get_oldest_parent_field_names()))
            youngest_child_names = list(set(self.get_youngest_children_field_names()))

            for youngest_child_name in youngest_child_names:
                self.find_instance_attr(kwargs['instance'], youngest_child_name)

            for oldest_parent_field_name in oldest_parent_field_names:
                try:
                    self.fields[oldest_parent_field_name].initial = getattr(self, '%s' % oldest_parent_field_name)
                except AttributeError:
                    pass

            self.set_choices_via_ajax()

        elif 'initial' in kwargs and kwargs['initial'] not in EMPTY_VALUES:
            self.set_choices_via_ajax(kwargs['initial'], is_initial=True)
        else:
            for field_name in self.chained_fields_names + self.chained_model_fields_names:
                empty_label = self.fields[field_name].empty_label
                self.fields[field_name].choices = [('', empty_label)] 
Example #18
Source File: forms.py    From django-clever-selects with MIT License 5 votes vote down vote up
def get_children_field_names(self, parent_name):
        if parent_name in EMPTY_VALUES:
            return []
        result = []
        for field_name in self.fields:
            field = self.fields[field_name]
            if getattr(field, 'parent_field', None) == parent_name:
                result.append(field_name)
        return result 
Example #19
Source File: fields.py    From esdc-ce with Apache License 2.0 5 votes vote down vote up
def validate(self, value):
        if not self.allow_empty and value in validators.EMPTY_VALUES:
            raise ValidationError(self.error_messages['required']) 
Example #20
Source File: widgets.py    From django-is-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _render_readonly(self, name, value, attrs=None, renderer=None, request=None, form=None, initial_value=None):
        if request:
            choice = self._choice(value)
            if choice:
                rendered_value = self._render_object(request, choice.obj, force_text(choice[1]))
            elif value in EMPTY_VALUES:
                rendered_value = EMPTY_VALUE

            return format_html('<p>{}</p>', rendered_value)
        else:
            return super()._render_readonly(name, value, attrs, renderer, request, form, initial_value) 
Example #21
Source File: widgets.py    From django-is-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _get_value_display(self, value, request=None):
        from is_core.utils import display_for_value

        value = self._get_value(value)

        if value in EMPTY_VALUES:
            value = EMPTY_VALUE

        return display_for_value(value, request=request) 
Example #22
Source File: fields.py    From esdc-ce with Apache License 2.0 5 votes vote down vote up
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 
Example #23
Source File: config_forms.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
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) 
Example #24
Source File: config_forms.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
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 
Example #25
Source File: fields.py    From esdc-ce with Apache License 2.0 5 votes vote down vote up
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) 
Example #26
Source File: fields.py    From esdc-ce with Apache License 2.0 5 votes vote down vote up
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) 
Example #27
Source File: fields.py    From esdc-ce with Apache License 2.0 5 votes vote down vote up
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 
Example #28
Source File: fields.py    From esdc-ce with Apache License 2.0 5 votes vote down vote up
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) 
Example #29
Source File: fields.py    From esdc-ce with Apache License 2.0 5 votes vote down vote up
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 
Example #30
Source File: fields.py    From esdc-ce with Apache License 2.0 5 votes vote down vote up
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