Validating Django ModelForm

Trying to solve an interesting problem right now.

I have a Django model with an image field that is not required, but is set to the default when instantiating a new model.

 class Product(models.Model): image = models.ImageField(upload_to='/image/directory/', default='/default/image/path/', blank=True) 

I also have a ModelForm based on this model that includes an image field and has some custom validation.

 class ProductForm(forms.ModelForm): class Meta: model = Product fields = ('image',) def clean_image(self): image = self.cleaned_data.get('image', False) if image: # validate image return None 

The problem is that in the documents , calling is_valid() in the validation of the ModelForm trigger model in addition to validating the form, so when the user submits the model form without an image, my form validation code tries to validate the model image by default, and not just do nothing as intended.

How can I make it do nothing if the form itself does not matter for the image field?

+6
source share
1 answer

Just solved it in a rather simple way. Add an answer here if it is useful to anyone else.

Django docs indicate that

... the model form instance bound to the model object will contain the self.instance attribute, which gives the model form methods access to that particular model instance.

Therefore, instead of checking whether the ModelForm value has an image value, I just check to see if the image value from the saved instance has changed. Now the form check looks like this:

 class ProductForm(forms.ModelForm): class Meta: model = Product fields = ('image',) def clean_image(self): image = self.cleaned_data.get('image', False) if not self.instance.image == image: # validate image return None 

The problem is solved!

+10
source

Source: https://habr.com/ru/post/927284/


All Articles