3

複数のフォームで同じカスタム検証を使用する必要があります。他のフレームワークでは、新しい「バリデーター」クラスを作成しますが、Django/Python で何が最適かはわかりません。

以下は私がしたことです。より良い方法はありますか(以下の解決策)?

任意の形式で:

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

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

検証モジュールで

def validate_image_with_dimensions(image, expected_width, expected_height):
    from django.core.files.images import get_image_dimensions

    # the validation code...

    return image

以下は解決策です:

形式: _

    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)
                )
4

1 に答える 1

2

フォームおよびモデル フィールドは、バリデータのリストを受け入れます

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

バリデーターはあらゆる種類の呼び出し可能なオブジェクトです。自由に呼び出し可能なクラスを作成してください (django 内部バリデーターはクラスベースです)。

インスピレーションについては、django.core.validators のソースをご覧ください。

于 2013-02-26T00:38:19.063 に答える