Python django.core.validators.MaxLengthValidator() Examples

The following are 28 code examples of django.core.validators.MaxLengthValidator(). 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 GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, max_length=None, min_length=None, *args, **kwargs):
        self.max_length, self.min_length = max_length, min_length
        super(CharField, self).__init__(*args, **kwargs)
        if min_length is not None:
            self.validators.append(validators.MinLengthValidator(int(min_length)))
        if max_length is not None:
            self.validators.append(validators.MaxLengthValidator(int(max_length))) 
Example #2
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 #3
Source File: cms_plugins.py    From richie with MIT License 6 votes vote down vote up
def get_form(self, request, obj=None, change=False, **kwargs):
        """
        Add a max length validator based on what is configured in settings for the
        current placeholder.
        """
        form = super().get_form(request, obj=obj, change=change, **kwargs)

        placeholder_id = request.GET.get("placeholder_id")
        if not placeholder_id and not obj:
            return form

        if placeholder_id:
            placeholder = Placeholder.objects.only("slot").get(id=placeholder_id)
        else:
            placeholder = obj.placeholder

        max_length = getattr(settings, "RICHIE_PLAINTEXT_MAXLENGTH", {}).get(
            placeholder.slot
        )
        if max_length:
            form.base_fields["body"].validators.append(MaxLengthValidator(max_length))

        return form 
Example #4
Source File: tag.py    From site with MIT License 6 votes vote down vote up
def validate_tag_embed_author(author: Any) -> None:
    """Raises a ValidationError if the given author is invalid."""
    field_validators = {
        'name': (
            MinLengthValidator(
                limit_value=1,
                message="Embed author name must not be empty."
            ),
            MaxLengthValidator(limit_value=256)
        ),
        'url': (),
        'icon_url': (),
        'proxy_icon_url': ()
    }

    if not isinstance(author, Mapping):
        raise ValidationError("Embed author must be a mapping.")

    for field_name, value in author.items():
        if field_name not in field_validators:
            raise ValidationError(f"Unknown embed author field: {field_name!r}.")

        for validator in field_validators[field_name]:
            validator(value) 
Example #5
Source File: tag.py    From site with MIT License 6 votes vote down vote up
def validate_tag_embed_fields(fields: dict) -> None:
    """Raises a ValidationError if any of the given embed fields is invalid."""
    field_validators = {
        'name': (MaxLengthValidator(limit_value=256),),
        'value': (MaxLengthValidator(limit_value=1024),),
        'inline': (is_bool_validator,),
    }

    required_fields = ('name', 'value')

    for field in fields:
        if not isinstance(field, Mapping):
            raise ValidationError("Embed fields must be a mapping.")

        if not all(required_field in field for required_field in required_fields):
            raise ValidationError(
                f"Embed fields must contain the following fields: {', '.join(required_fields)}."
            )

        for field_name, value in field.items():
            if field_name not in field_validators:
                raise ValidationError(f"Unknown embed field field: {field_name!r}.")

            for validator in field_validators[field_name]:
                validator(value) 
Example #6
Source File: tag.py    From site with MIT License 6 votes vote down vote up
def validate_tag_embed_footer(footer: Dict[str, str]) -> None:
    """Raises a ValidationError if the given footer is invalid."""
    field_validators = {
        'text': (
            MinLengthValidator(
                limit_value=1,
                message="Footer text must not be empty."
            ),
            MaxLengthValidator(limit_value=2048)
        ),
        'icon_url': (),
        'proxy_icon_url': ()
    }

    if not isinstance(footer, Mapping):
        raise ValidationError("Embed footer must be a mapping.")

    for field_name, value in footer.items():
        if field_name not in field_validators:
            raise ValidationError(f"Unknown embed footer field: {field_name!r}.")

        for validator in field_validators[field_name]:
            validator(value) 
Example #7
Source File: fields.py    From esdc-ce with Apache License 2.0 5 votes vote down vote up
def __init__(self, max_length=None, min_length=None, allow_none=False, *args, **kwargs):
        self.max_length, self.min_length = max_length, min_length
        self.allow_none = allow_none
        super(CharField, self).__init__(*args, **kwargs)
        if min_length is not None:
            self.validators.append(validators.MinLengthValidator(min_length))
        if max_length is not None:
            self.validators.append(validators.MaxLengthValidator(max_length)) 
Example #8
Source File: forms.py    From django-bom with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        self.organization = kwargs.pop('organization', None)
        super(PartClassForm, self).__init__(*args, **kwargs)
        self.fields['code'].required = False
        self.fields['name'].required = False
        self.fields['code'].validators.extend([MaxLengthValidator(self.organization.number_class_code_len), MinLengthValidator(self.organization.number_class_code_len)]) 
Example #9
Source File: __init__.py    From python2017 with MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        kwargs['editable'] = False
        super(BinaryField, self).__init__(*args, **kwargs)
        if self.max_length is not None:
            self.validators.append(validators.MaxLengthValidator(self.max_length)) 
Example #10
Source File: __init__.py    From python2017 with MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(CharField, self).__init__(*args, **kwargs)
        self.validators.append(validators.MaxLengthValidator(self.max_length)) 
Example #11
Source File: fields.py    From python2017 with MIT License 5 votes vote down vote up
def __init__(self, max_length=None, min_length=None, strip=True, empty_value='', *args, **kwargs):
        self.max_length = max_length
        self.min_length = min_length
        self.strip = strip
        self.empty_value = empty_value
        super(CharField, self).__init__(*args, **kwargs)
        if min_length is not None:
            self.validators.append(validators.MinLengthValidator(int(min_length)))
        if max_length is not None:
            self.validators.append(validators.MaxLengthValidator(int(max_length))) 
Example #12
Source File: __init__.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        kwargs['editable'] = False
        super(BinaryField, self).__init__(*args, **kwargs)
        if self.max_length is not None:
            self.validators.append(validators.MaxLengthValidator(self.max_length)) 
Example #13
Source File: __init__.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(CharField, self).__init__(*args, **kwargs)
        self.validators.append(validators.MaxLengthValidator(self.max_length)) 
Example #14
Source File: fields.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def __init__(self, max_length=None, min_length=None, strip=True, *args, **kwargs):
        self.max_length = max_length
        self.min_length = min_length
        self.strip = strip
        super(CharField, self).__init__(*args, **kwargs)
        if min_length is not None:
            self.validators.append(validators.MinLengthValidator(int(min_length)))
        if max_length is not None:
            self.validators.append(validators.MaxLengthValidator(int(max_length))) 
Example #15
Source File: __init__.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(CharField, self).__init__(*args, **kwargs)
        self.validators.append(validators.MaxLengthValidator(self.max_length)) 
Example #16
Source File: fields.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, max_length=None, min_length=None, *args, **kwargs):
        self.max_length, self.min_length = max_length, min_length
        super(CharField, self).__init__(*args, **kwargs)
        if min_length is not None:
            self.validators.append(validators.MinLengthValidator(min_length))
        if max_length is not None:
            self.validators.append(validators.MaxLengthValidator(max_length)) 
Example #17
Source File: __init__.py    From python with Apache License 2.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        kwargs['editable'] = False
        super(BinaryField, self).__init__(*args, **kwargs)
        if self.max_length is not None:
            self.validators.append(validators.MaxLengthValidator(self.max_length)) 
Example #18
Source File: __init__.py    From python with Apache License 2.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(CharField, self).__init__(*args, **kwargs)
        self.validators.append(validators.MaxLengthValidator(self.max_length)) 
Example #19
Source File: fields.py    From python with Apache License 2.0 5 votes vote down vote up
def __init__(self, max_length=None, min_length=None, strip=True, empty_value='', *args, **kwargs):
        self.max_length = max_length
        self.min_length = min_length
        self.strip = strip
        self.empty_value = empty_value
        super(CharField, self).__init__(*args, **kwargs)
        if min_length is not None:
            self.validators.append(validators.MinLengthValidator(int(min_length)))
        if max_length is not None:
            self.validators.append(validators.MaxLengthValidator(int(max_length))) 
Example #20
Source File: __init__.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        kwargs.setdefault('editable', False)
        super().__init__(*args, **kwargs)
        if self.max_length is not None:
            self.validators.append(validators.MaxLengthValidator(self.max_length)) 
Example #21
Source File: __init__.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.validators.append(validators.MaxLengthValidator(self.max_length)) 
Example #22
Source File: fields.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def __init__(self, *, max_length=None, min_length=None, strip=True, empty_value='', **kwargs):
        self.max_length = max_length
        self.min_length = min_length
        self.strip = strip
        self.empty_value = empty_value
        super().__init__(**kwargs)
        if min_length is not None:
            self.validators.append(validators.MinLengthValidator(int(min_length)))
        if max_length is not None:
            self.validators.append(validators.MaxLengthValidator(int(max_length)))
        self.validators.append(validators.ProhibitNullCharactersValidator()) 
Example #23
Source File: __init__.py    From bioforum with MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        kwargs['editable'] = False
        super().__init__(*args, **kwargs)
        if self.max_length is not None:
            self.validators.append(validators.MaxLengthValidator(self.max_length)) 
Example #24
Source File: __init__.py    From bioforum with MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.validators.append(validators.MaxLengthValidator(self.max_length)) 
Example #25
Source File: fields.py    From bioforum with MIT License 5 votes vote down vote up
def __init__(self, *, max_length=None, min_length=None, strip=True, empty_value='', **kwargs):
        self.max_length = max_length
        self.min_length = min_length
        self.strip = strip
        self.empty_value = empty_value
        super().__init__(**kwargs)
        if min_length is not None:
            self.validators.append(validators.MinLengthValidator(int(min_length)))
        if max_length is not None:
            self.validators.append(validators.MaxLengthValidator(int(max_length)))
        self.validators.append(validators.ProhibitNullCharactersValidator()) 
Example #26
Source File: __init__.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        kwargs['editable'] = False
        super(BinaryField, self).__init__(*args, **kwargs)
        if self.max_length is not None:
            self.validators.append(validators.MaxLengthValidator(self.max_length)) 
Example #27
Source File: __init__.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(CharField, self).__init__(*args, **kwargs)
        self.validators.append(validators.MaxLengthValidator(self.max_length)) 
Example #28
Source File: fields.py    From django-enum-choices with MIT License 4 votes vote down vote up
def __init__(self, enum_class: Type[Enum], choice_builder=value_value, **kwargs):
        if not issubclass(enum_class, Enum):
            raise EnumChoiceFieldException(
                _('`enum_class` argument must be a child of `Enum`')
            )

        self.enum_class = enum_class
        self.choice_builder = self._get_choice_builder(choice_builder)

        # Saving original for proper deconstruction
        self._original_choice_builder = choice_builder

        built_choices = self.build_choices()

        # `choices` is passed to `__init__` when migrations are generated
        # `choices` should not be passed when normally initializing the field
        self._passed_choices = kwargs.get(
            'choices',
            built_choices
        )  # Saved for deconstruction

        kwargs['choices'] = built_choices

        calculated_max_length = self._calculate_max_length(**kwargs)

        kwargs.setdefault('max_length', calculated_max_length)

        super().__init__(**kwargs)

        # Removing `MaxLengthValidator` instances and adding
        # an `EnumValueMaxLengthValidator` instance
        self.validators = [
            validator for validator in self.validators
            if not isinstance(validator, MaxLengthValidator)
        ]

        self.validators.append(
            EnumValueMaxLengthValidator(
                value_builder=self.get_prep_value,
                limit_value=kwargs['max_length']
            )
        )