apollos
apollos

Reputation: 323

How Can I make Image Field in Django ModelForm Required

I have a Django ModelForm with an image field and I want to add validation on empty image form field. That is, I want system validation message display when user did not select an image.

I have tried but it is not working as I expected because my Validation Error Message displays only when the user selection is not an image but processes the form on none selection. In short I want to add a required attribute to the image field thereby compelling the user to select a valid image before proceeding. Remember that there is an avatar.jpg default in the database but upon user profile I want him or her to change it before proceeding. Here is my Model code:

class ProfileUpdateForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = [ 'image']

    def clean_image(self):
       image = self.cleaned_data.get('image')
       if not image or image == "":
           raise forms.ValidationError(('Invalid value'), code='invalid') 
       return image

Upvotes: 0

Views: 102

Answers (1)

Wouter
Wouter

Reputation: 535

You can set the field required using the __init__() method:

class ProfileUpdateForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = [ 'image']

     def __init__(self, *args, **kwargs):
        super(ProfileUpdateForm, self).__init__(*args, **kwargs)
        self.fields['image'].required = True

You could also change the Profile model by making sure the image cannot be null/blank. This could be done with models.ImageField([..], blank=False, null=False)

Upvotes: 1

Related Questions