0

Suppose I have a django model of an Image:

from django.db import models
class Image(models.Model):
      ...
      image = models.ImageField(upload_to='some_place')
      image_url = models.URLField()
      ...

and I want that a user can upload either image or its url so I can not set both field null=True because I want atleast one of them to show in template. How can I do this?

Vijay Soni
  • 197
  • 1
  • 10
  • Check Django docs for CheckConstraint https://docs.djangoproject.com/en/4.0/ref/models/constraints/#checkconstraint – PTomasz Jun 23 '22 at 12:59

1 Answers1

1

You can put null=True to both of them and then verify that at least one of the two fields of your form was filled using its clean method.

class ImageForm(forms.ModelForm):
    def clean(self):
        if not (self.cleaned_data.get('image') or self.cleaned_data.get('image_url')):
            raise forms.ValidationError("You must fill at least one of both fields")

If both fields are empty, it will return a validation error saying that at least one of them should be filled.

Balizok
  • 904
  • 2
  • 5
  • 19