Python django.core.validators.MaxValueValidator() Examples

The following are 30 code examples of django.core.validators.MaxValueValidator(). 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: fields.py    From django-htk with MIT License 6 votes vote down vote up
def __init__(self, verbose_name=None, name=None, min_value=None, max_value=None, *args, **kwargs):
        self.min_value = min_value
        self.max_value = max_value

        validators = kwargs.pop('validators', [])
        if min_value:
            validators.append(MinValueValidator(min_value))
        if max_value:
            validators.append(MaxValueValidator(max_value))

        return super(IntegerRangeField, self).__init__(
            verbose_name=verbose_name,
            name=name,
            validators=validators,
            *args,
            **kwargs
        ) 
Example #2
Source File: fields_storage.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def clean(self, value):
        value = super().clean(value)
        if value is not None:
            # Exit early if this is percentage value.
            if is_percentage(value):
                return value
            else:
                value = machine_readable_bytes(value)

        # Run validation again, but with the min and max validators. This is
        # because the value has now been converted to an integer.
        self.validators = []
        if self.min_value is not None:
            self.validators.append(MinValueValidator(self.min_value))
        if self.max_value is not None:
            self.validators.append(MaxValueValidator(self.max_value))
        self.run_validators(value)
        return value 
Example #3
Source File: forms.py    From telemetry-analysis-service with Mozilla Public License 2.0 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        user_sshkeys = self.created_by.created_sshkeys.all()
        self.fields["ssh_key"].queryset = user_sshkeys.all()
        self.fields["ssh_key"].help_text = (
            "The SSH key to deploy to the cluster. "
            'See <a href="%s">your keys</a> or '
            '<a href="%s">add a new one</a>.'
            % (reverse("keys-list"), reverse("keys-new"))
        )
        # if the user is not a cluster maintainer, reset the max
        # to the default so they can't create larger clusters
        if not self.created_by.has_perm("clusters.maintain_cluster"):
            max_size = settings.AWS_CONFIG["MAX_CLUSTER_SIZE"]
            self.fields["size"].max_value = max_size
            self.fields["size"].validators.append(
                validators.MaxValueValidator(max_size)
            )
            self.fields["size"].widget.attrs["max"] = max_size
            self.fields["size"].help_text = (
                "Number of workers to use in the cluster, between 1 and %s. "
                "For testing or development 1 is recommended." % max_size
            )

        # if there are fewer options we just show radio select buttons
        if user_sshkeys.count() <= 6:
            self.fields["ssh_key"].widget = forms.RadioSelect(
                choices=self.fields["ssh_key"].choices, attrs={"class": "radioset"}
            ) 
Example #4
Source File: __init__.py    From bioforum with MIT License 6 votes vote down vote up
def validators(self):
        # These validators can't be added at field initialization time since
        # they're based on values retrieved from `connection`.
        validators_ = super().validators
        internal_type = self.get_internal_type()
        min_value, max_value = connection.ops.integer_field_range(internal_type)
        if min_value is not None:
            for validator in validators_:
                if isinstance(validator, validators.MinValueValidator) and validator.limit_value >= min_value:
                    break
            else:
                validators_.append(validators.MinValueValidator(min_value))
        if max_value is not None:
            for validator in validators_:
                if isinstance(validator, validators.MaxValueValidator) and validator.limit_value <= max_value:
                    break
            else:
                validators_.append(validators.MaxValueValidator(max_value))
        return validators_ 
Example #5
Source File: __init__.py    From python2017 with MIT License 6 votes vote down vote up
def validators(self):
        # These validators can't be added at field initialization time since
        # they're based on values retrieved from `connection`.
        validators_ = super(IntegerField, self).validators
        internal_type = self.get_internal_type()
        min_value, max_value = connection.ops.integer_field_range(internal_type)
        if min_value is not None:
            for validator in validators_:
                if isinstance(validator, validators.MinValueValidator) and validator.limit_value >= min_value:
                    break
            else:
                validators_.append(validators.MinValueValidator(min_value))
        if max_value is not None:
            for validator in validators_:
                if isinstance(validator, validators.MaxValueValidator) and validator.limit_value <= max_value:
                    break
            else:
                validators_.append(validators.MaxValueValidator(max_value))
        return validators_ 
Example #6
Source File: fields.py    From esdc-ce with Apache License 2.0 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        try:
            self.model_field = kwargs.pop('model_field')
        except KeyError:
            raise ValueError("ModelField requires 'model_field' kwarg")

        self.min_length = kwargs.pop('min_length',
                                     getattr(self.model_field, 'min_length', None))
        self.max_length = kwargs.pop('max_length',
                                     getattr(self.model_field, 'max_length', None))
        self.min_value = kwargs.pop('min_value',
                                    getattr(self.model_field, 'min_value', None))
        self.max_value = kwargs.pop('max_value',
                                    getattr(self.model_field, 'max_value', None))

        super(ModelField, self).__init__(*args, **kwargs)

        if self.min_length is not None:
            self.validators.append(validators.MinLengthValidator(self.min_length))
        if self.max_length is not None:
            self.validators.append(validators.MaxLengthValidator(self.max_length))
        if self.min_value is not None:
            self.validators.append(validators.MinValueValidator(self.min_value))
        if self.max_value is not None:
            self.validators.append(validators.MaxValueValidator(self.max_value)) 
Example #7
Source File: serializers.py    From esdc-ce with Apache License 2.0 6 votes vote down vote up
def __init__(self, request, instance, *args, **kwargs):
        super(SnapshotDefineSerializer, self).__init__(request, instance, *args, **kwargs)

        if not kwargs.get('many', False):
            dc_settings = request.dc.settings

            # Limit maximum number of snapshots - Issue #chili-447
            if dc_settings.VMS_VM_SNAPSHOT_LIMIT_AUTO is None:
                min_count, max_count = RETENTION_MIN, RETENTION_MAX
            else:
                min_count, max_count = 1, int(dc_settings.VMS_VM_SNAPSHOT_LIMIT_AUTO)

            self.fields['retention'].validators.append(validators.MinValueValidator(min_count))
            self.fields['retention'].validators.append(validators.MaxValueValidator(max_count))

            if instance.vm.is_kvm():
                self._update_fields_ = list(self._update_fields_)
                self._update_fields_.append('fsfreeze') 
Example #8
Source File: __init__.py    From python with Apache License 2.0 6 votes vote down vote up
def validators(self):
        # These validators can't be added at field initialization time since
        # they're based on values retrieved from `connection`.
        validators_ = super(IntegerField, self).validators
        internal_type = self.get_internal_type()
        min_value, max_value = connection.ops.integer_field_range(internal_type)
        if min_value is not None:
            for validator in validators_:
                if isinstance(validator, validators.MinValueValidator) and validator.limit_value >= min_value:
                    break
            else:
                validators_.append(validators.MinValueValidator(min_value))
        if max_value is not None:
            for validator in validators_:
                if isinstance(validator, validators.MaxValueValidator) and validator.limit_value <= max_value:
                    break
            else:
                validators_.append(validators.MaxValueValidator(max_value))
        return validators_ 
Example #9
Source File: serializers.py    From esdc-ce with Apache License 2.0 5 votes vote down vote up
def __init__(self, request, instance, *args, **kwargs):
        vm_template = kwargs.pop('vm_template', False)
        self._update_fields_ = list(self._update_fields_)
        super(BackupDefineSerializer, self).__init__(request, instance, *args, **kwargs)

        if not kwargs.get('many', False):
            dc_settings = request.dc.settings
            backup_nodes = get_nodes(request, is_backup=True)
            self.fields['node'].queryset = backup_nodes
            self.fields['zpool'].default = dc_settings.VMS_STORAGE_DEFAULT
            self.fields['compression'].default = dc_settings.VMS_VM_BACKUP_COMPRESSION_DEFAULT

            # Set first backup node and backup node storage available in DC
            # (used only when called by VmDefineBackup.create_from_template())
            if vm_template:
                try:
                    self.fields['node'].default = first_node = backup_nodes[0]
                except IndexError:
                    pass
                else:
                    first_node_zpools = get_zpools(request).filter(node=first_node).values_list('zpool', flat=True)

                    if first_node_zpools and dc_settings.VMS_STORAGE_DEFAULT not in first_node_zpools:
                        self.fields['zpool'].default = first_node_zpools[0]

            if request.method != 'POST':
                self.fields['type'].read_only = True

            # Limit maximum number of backups - Issue #chili-447
            if dc_settings.VMS_VM_BACKUP_LIMIT is None:
                min_count, max_count = RETENTION_MIN, RETENTION_MAX
            else:
                min_count, max_count = 1, int(dc_settings.VMS_VM_BACKUP_LIMIT)
            self.fields['retention'].validators.append(validators.MinValueValidator(min_count))
            self.fields['retention'].validators.append(validators.MaxValueValidator(max_count))

            if instance.vm.is_kvm():
                self._update_fields_.append('fsfreeze') 
Example #10
Source File: fields.py    From python2017 with MIT License 5 votes vote down vote up
def __init__(self, max_value=None, min_value=None, *args, **kwargs):
        self.max_value, self.min_value = max_value, min_value
        if kwargs.get('localize') and self.widget == NumberInput:
            # Localized number input is not well supported on most browsers
            kwargs.setdefault('widget', super(IntegerField, self).widget)
        super(IntegerField, self).__init__(*args, **kwargs)

        if max_value is not None:
            self.validators.append(validators.MaxValueValidator(max_value))
        if min_value is not None:
            self.validators.append(validators.MinValueValidator(min_value)) 
Example #11
Source File: test_forms.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_validators_independence(self):
        """
        The list of form field validators can be modified without polluting
        other forms.
        """
        class MyForm(Form):
            myfield = CharField(max_length=25)

        f1 = MyForm()
        f2 = MyForm()

        f1.fields['myfield'].validators[0] = MaxValueValidator(12)
        self.assertNotEqual(f1.fields['myfield'].validators[0], f2.fields['myfield'].validators[0]) 
Example #12
Source File: test_integerfield.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_backend_range_validation(self):
        """
        Backend specific ranges are enforced at the model validation level
        (#12030).
        """
        min_value, max_value = self.backend_range

        if min_value is not None:
            instance = self.model(value=min_value - 1)
            expected_message = validators.MinValueValidator.message % {
                'limit_value': min_value,
            }
            with self.assertRaisesMessage(ValidationError, expected_message):
                instance.full_clean()
            instance.value = min_value
            instance.full_clean()

        if max_value is not None:
            instance = self.model(value=max_value + 1)
            expected_message = validators.MaxValueValidator.message % {
                'limit_value': max_value,
            }
            with self.assertRaisesMessage(ValidationError, expected_message):
                instance.full_clean()
            instance.value = max_value
            instance.full_clean() 
Example #13
Source File: test_integerfield.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_redundant_backend_range_validators(self):
        """
        If there are stricter validators than the ones from the database
        backend then the backend validators aren't added.
        """
        min_backend_value, max_backend_value = self.backend_range

        if min_backend_value is not None:
            min_custom_value = min_backend_value + 1
            ranged_value_field = self.model._meta.get_field('value').__class__(
                validators=[validators.MinValueValidator(min_custom_value)]
            )
            field_range_message = validators.MinValueValidator.message % {
                'limit_value': min_custom_value,
            }
            with self.assertRaisesMessage(ValidationError, "[%r]" % field_range_message):
                ranged_value_field.run_validators(min_backend_value - 1)

        if max_backend_value is not None:
            max_custom_value = max_backend_value - 1
            ranged_value_field = self.model._meta.get_field('value').__class__(
                validators=[validators.MaxValueValidator(max_custom_value)]
            )
            field_range_message = validators.MaxValueValidator.message % {
                'limit_value': max_custom_value,
            }
            with self.assertRaisesMessage(ValidationError, "[%r]" % field_range_message):
                ranged_value_field.run_validators(max_backend_value + 1) 
Example #14
Source File: test_forms.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_validators_independence(self):
        """
        The list of form field validators can be modified without polluting
        other forms.
        """
        class MyForm(Form):
            myfield = CharField(max_length=25)

        f1 = MyForm()
        f2 = MyForm()

        f1.fields['myfield'].validators[0] = MaxValueValidator(12)
        self.assertNotEqual(f1.fields['myfield'].validators[0], f2.fields['myfield'].validators[0]) 
Example #15
Source File: test_integerfield.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_backend_range_validation(self):
        """
        Backend specific ranges are enforced at the model validation level
        (#12030).
        """
        min_value, max_value = self.backend_range

        if min_value is not None:
            instance = self.model(value=min_value - 1)
            expected_message = validators.MinValueValidator.message % {
                'limit_value': min_value,
            }
            with self.assertRaisesMessage(ValidationError, expected_message):
                instance.full_clean()
            instance.value = min_value
            instance.full_clean()

        if max_value is not None:
            instance = self.model(value=max_value + 1)
            expected_message = validators.MaxValueValidator.message % {
                'limit_value': max_value,
            }
            with self.assertRaisesMessage(ValidationError, expected_message):
                instance.full_clean()
            instance.value = max_value
            instance.full_clean() 
Example #16
Source File: fields.py    From django-cryptographic-fields with MIT License 5 votes vote down vote up
def validators(self):
        # These validators can't be added at field initialization time since
        # they're based on values retrieved from `connection`.
        range_validators = []
        internal_type = self.__class__.__name__[9:]
        min_value, max_value = django.db.connection.ops.integer_field_range(
            internal_type)
        if min_value is not None:
            range_validators.append(validators.MinValueValidator(min_value))
        if max_value is not None:
            range_validators.append(validators.MaxValueValidator(max_value))
        return super(EncryptedNumberMixin, self).validators + range_validators 
Example #17
Source File: fields.py    From esdc-ce with Apache License 2.0 5 votes vote down vote up
def __init__(self, max_value=None, min_value=None, *args, **kwargs):
        self.max_value, self.min_value = max_value, min_value
        super(IntegerField, self).__init__(*args, **kwargs)

        if max_value is not None:
            self.validators.append(validators.MaxValueValidator(max_value))
        if min_value is not None:
            self.validators.append(validators.MinValueValidator(min_value)) 
Example #18
Source File: fields.py    From esdc-ce with Apache License 2.0 5 votes vote down vote up
def __init__(self, max_value=None, min_value=None, max_digits=None, decimal_places=None, *args, **kwargs):
        self.max_value, self.min_value = max_value, min_value
        self.max_digits, self.decimal_places = max_digits, decimal_places
        super(DecimalField, self).__init__(*args, **kwargs)

        if max_value is not None:
            self.validators.append(validators.MaxValueValidator(max_value))
        if min_value is not None:
            self.validators.append(validators.MinValueValidator(min_value)) 
Example #19
Source File: __init__.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def clean(self, value):
        value = super().clean(value)
        if value is not None:
            value = machine_readable_bytes(value)

        # Run validation again, but with the min and max validators. This is
        # because the value has now been converted to an integer.
        self.validators = []
        if self.min_value is not None:
            self.validators.append(MinValueValidator(self.min_value))
        if self.max_value is not None:
            self.validators.append(MaxValueValidator(self.max_value))
        self.run_validators(value)

        return value 
Example #20
Source File: fields.py    From django-htk with MIT License 5 votes vote down vote up
def __init__(self, min_value=1, max_value=5, *args, **kwargs):
        self.min_value = min_value
        self.max_value = max_value
        super(StarRatingField, self).__init__(
            blank=True,
            null=True,
            validators=[
                MinValueValidator(min_value),
                MaxValueValidator(max_value),
            ],
            *args,
            **kwargs
        ) 
Example #21
Source File: base.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def formfield(self, **kwargs):
        defaults = {'min_value': self.min_value, 'max_value':self.max_value}
        defaults.update(kwargs)
        field = super(FileSizeField, self).formfield(**defaults)
        # monkey-patch a better error message
        for v in field.validators:
            if isinstance(v, MaxValueValidator):
                v.message = "We currently limit submissions to %i kB on this system. For larger files, we suggest having students upload the files to their web space and submitting a URL." % (settings.MAX_SUBMISSION_SIZE)
        return field 
Example #22
Source File: __init__.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def validators(self):
        # These validators can't be added at field initialization time since
        # they're based on values retrieved from `connection`.
        range_validators = []
        internal_type = self.get_internal_type()
        min_value, max_value = connection.ops.integer_field_range(internal_type)
        if min_value is not None:
            range_validators.append(validators.MinValueValidator(min_value))
        if max_value is not None:
            range_validators.append(validators.MaxValueValidator(max_value))
        return super(IntegerField, self).validators + range_validators 
Example #23
Source File: fields.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def __init__(self, max_value=None, min_value=None, *args, **kwargs):
        self.max_value, self.min_value = max_value, min_value
        if kwargs.get('localize') and self.widget == NumberInput:
            # Localized number input is not well supported on most browsers
            kwargs.setdefault('widget', super(IntegerField, self).widget)
        super(IntegerField, self).__init__(*args, **kwargs)

        if max_value is not None:
            self.validators.append(validators.MaxValueValidator(max_value))
        if min_value is not None:
            self.validators.append(validators.MinValueValidator(min_value)) 
Example #24
Source File: fields.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, max_value=None, min_value=None, max_digits=None, decimal_places=None, *args, **kwargs):
        self.max_value, self.min_value = max_value, min_value
        self.max_digits, self.decimal_places = max_digits, decimal_places
        Field.__init__(self, *args, **kwargs)

        if max_value is not None:
            self.validators.append(validators.MaxValueValidator(max_value))
        if min_value is not None:
            self.validators.append(validators.MinValueValidator(min_value)) 
Example #25
Source File: fields.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, max_value=None, min_value=None, *args, **kwargs):
        self.max_value, self.min_value = max_value, min_value
        super(IntegerField, self).__init__(*args, **kwargs)

        if max_value is not None:
            self.validators.append(validators.MaxValueValidator(max_value))
        if min_value is not None:
            self.validators.append(validators.MinValueValidator(min_value)) 
Example #26
Source File: fields.py    From python with Apache License 2.0 5 votes vote down vote up
def __init__(self, max_value=None, min_value=None, *args, **kwargs):
        self.max_value, self.min_value = max_value, min_value
        if kwargs.get('localize') and self.widget == NumberInput:
            # Localized number input is not well supported on most browsers
            kwargs.setdefault('widget', super(IntegerField, self).widget)
        super(IntegerField, self).__init__(*args, **kwargs)

        if max_value is not None:
            self.validators.append(validators.MaxValueValidator(max_value))
        if min_value is not None:
            self.validators.append(validators.MinValueValidator(min_value)) 
Example #27
Source File: serializers.py    From SchoolIdolAPI with Apache License 2.0 5 votes vote down vote up
def validate(self, data):
        errors = {}
        request = self.context['request']
        card = None
        if request.method == 'POST':
            try:
                data['card'] = models.Card.objects.get(pk=request.POST['card'])
                card = data['card']
            except (ObjectDoesNotExist, KeyError):
                if 'card' not in request.POST:
                    errors['card'] = 'This field is required'
                else:
                    errors['card'] = 'Invalid id'
            try:
                data['owner_account'] = models.Account.objects.get(pk=request.POST['owner_account'], owner=request.user)
            except (ObjectDoesNotExist, KeyError):
                if 'owner_account' not in request.POST:
                    errors['owner_account'] = 'This field is required'
                else:
                    errors['owner_account'] = 'This account does\'t exist or isn\'t yours'
        else:
            card = self.instance.card
        # Check for skill slots
        if 'skill_slots' in data and card:
            for validator in [MinValueValidator(card.min_skill_slot), MaxValueValidator(card.max_skill_slot)]:
                try:
                    validator(data['skill_slots'])
                except DjangoCoreValidationError as e:
                    errors['skill_slots'] = e.messages
        elif card:
            data['skill_slots'] = card.min_skill_slot
        if errors:
            raise serializers.ValidationError(errors)
        return data 
Example #28
Source File: __init__.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def validators(self):
        # These validators can't be added at field initialization time since
        # they're based on values retrieved from `connection`.
        validators_ = super().validators
        internal_type = self.get_internal_type()
        min_value, max_value = connection.ops.integer_field_range(internal_type)
        if (min_value is not None and not
            any(isinstance(validator, validators.MinValueValidator) and
                validator.limit_value >= min_value for validator in validators_)):
            validators_.append(validators.MinValueValidator(min_value))
        if (max_value is not None and not
            any(isinstance(validator, validators.MaxValueValidator) and
                validator.limit_value <= max_value for validator in validators_)):
            validators_.append(validators.MaxValueValidator(max_value))
        return validators_ 
Example #29
Source File: fields.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def __init__(self, *, max_value=None, min_value=None, **kwargs):
        self.max_value, self.min_value = max_value, min_value
        if kwargs.get('localize') and self.widget == NumberInput:
            # Localized number input is not well supported on most browsers
            kwargs.setdefault('widget', super().widget)
        super().__init__(**kwargs)

        if max_value is not None:
            self.validators.append(validators.MaxValueValidator(max_value))
        if min_value is not None:
            self.validators.append(validators.MinValueValidator(min_value)) 
Example #30
Source File: models.py    From hknweb with MIT License 5 votes vote down vote up
def max_value_current_year(value):
    return MaxValueValidator(current_year())(value)