gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 17:48:08 24 4
gpt4 key购买 nike

我需要在多个表单中使用相同的自定义验证。在其他框架中,我会创建一个新的“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
)

验证模块中

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

最佳答案

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

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

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

如需灵感,请查看 django.core.validators source .

关于python - 如何在 Django 中重用自定义验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15079255/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com