如何在Django中重用自定义验证?

2024-10-02 16:23:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要在几个表单中使用相同的自定义验证。在其他框架中,我会创建一个新的“Validator”类,但我不确定Django/Python的最佳选择。在

下面是我所做的,有没有更好的方法(下面的解决方案)?在

以任何形式

    def clean_image(self):
        image = self.cleaned_data.get("image")

        return validate_image_with_dimensions(
            image,
            expected_width=965,
            expected_height=142
        )

验证模块中

^{pr2}$

以下是解决方案:

形式

    image = forms.ImageField(
        max_length=250,
        label=mark_safe('Image<br /><small>(must be 1100 x 316px)</small>'),
        required=True,
        validators=[
            ImageDimensionsValidator(
                expected_width=1100,
                expected_height=316
            )
        ]
    )

验证模块中:

class ImageDimensionsValidator(object):

    def __init__(self, expected_width, expected_height):
        self.expected_width = expected_width
        self.expected_height = expected_height

    def __call__(self, image):
        """
        Validates that the image entered have the good dimensions
        """
        from django.core.files.images import get_image_dimensions

        if not image:
            pass
        else:
            width, height = get_image_dimensions(image)
            if width != self.expected_width or height != self.expected_height:
                raise ValidationError(
                    "The image dimensions are: " + str(width) + "x" + str(height) + ". "
                    "It's supposed to be " + str(self.expected_width) + "x" + str(self.expected_height)
                )

Tags: 模块imageselfgetdefbe解决方案width
1条回答
网友
1楼 · 发布于 2024-10-02 16:23:00

表单和模型字段accept a list of validators

class YourForm(forms.Form):
   ...
   image = forms.ImageField(validators=[validate_image_with_dimensions])

验证器是任何类型的可调用对象,请随意编写可调用类(django内部验证器是基于类的)。在

要获得灵感,请看django.core.validators source。在

相关问题 更多 >