2013-02-26 2 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

Большое спасибо. Я завершаю свой вопрос рабочим примером. –

Смежные вопросы