如何验证模型中的多个字段中的至少一个不是空白

时间:2016-08-16 21:04:28

标签: python django forms

我有一个模特:

class Artwork(models.Model):
    title = models.CharField(max_length=50)
    description = models.TextField(null=True, blank=True)
    image_file = models.ImageField(upload_to='portfolios/image/%Y/%m', null=True, blank=True)
    video_file = models.FileField(upload_to='portfolios/video/%Y/%m', null=True, blank=True)
    video_url = models.URLField(blank=True, null=True)

当用户编辑其中一个对象时,如何验证这三个字段中的至少一个是否提供了数据:image_filevideo_filevideo_url,以便验证邮件会在字段中显示在表单中,类似于设置blank=False并将其留空的情况下自动生成的内容?

1 个答案:

答案 0 :(得分:2)

您需要覆盖表单的clean方法并为字段分配错误消息。这是一个示例,如果所有三个字段都是空白的,则会从Django docs改编为错误消息:

from django import forms

class ArtworkForm(forms.Form):

    def clean(self):
        cleaned_data = super(ArtWorkForm, self).clean()
        image_file = cleaned_data.get("image_file")
        video_file = cleaned_data.get("video_file")
        video_url = cleaned_data.get("video_url")

        if not (image_file or video_file or video_url):
            msg = "your error message."
            self.add_error('image_file', msg)
            self.add_error('video_file', msg)
            self.add_error('video_url', msg)