2013-02-26 52 views
3

我需要使用幾種形式的相同的自定義驗證。在其他框架中,我會創建一個新的「Validator」類,但我不確定Django/Python最好。如何在Django中重新使用自定義驗證?

下面是我做的,有沒有更好的方法(下面的解決方案)?

在任何形式

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

回答

2

形式和模型字段accept a list of validators

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

驗證器是任何類型的可調用對象,隨意編寫可調用的類(django內部驗證器是基於類的)。

靈感來看,請看django.core.validators source

+0

非常感謝。我正在用工作示例完成我的問題。 – 2013-02-26 07:22:38

相關問題