简体   繁体   中英

Django: Make field required if other field entered

I'm trying to make the field video_thumbnail become required if the user enter a value into the field video_url and vice versa. But if both are empty then they are not required.

models.py

class Post(TimeStampedModel):
    video_url = models.CharField(max_length=255, blank=True)
    video_thumbnail = ResizedImageField(upload_to=file_name, storage=upload_storage, max_length=255, blank=True, null=True)

You can override save method,

class Post(TimeStampedModel):
    video_url = models.CharField(max_length=255, blank=True)
    video_thumbnail = ResizedImageField(upload_to=file_name, storage=upload_storage, max_length=255, blank=True, null=True)

    def save(self, *args, **kwargs):
       if not self.video_url and self.video_thumbnail == None:
          raise ValueError("The value isn't allowed")
       super(Post, self).save(*args, **kwargs)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM