Django ModelForm - 条件验证

时间:2013-08-20 08:40:57

标签: django validation django-models django-forms

我需要为我的ModelForm添加一个条件验证。

以下是我的Listing模型。

LISTING_TYPES = (
    ('event', 'event'),
    ('release', 'release')
)

class Listing(models.Model):
    title = models.CharField(max_length=255, verbose_name='Listing Title')
    type = models.CharField(max_length=255, choices=LISTING_TYPES, verbose_name='Listing Type')
    slug = models.SlugField(max_length=100)
    content = models.TextField(verbose_name='Listing Overview')
    competition = models.TextField()
    date_start = models.DateTimeField()
    time_start = models.CharField(max_length=255)
    date_end = models.DateTimeField()
    time_end = models.CharField(max_length=255)
    pub_date = models.DateTimeField('date published', auto_now_add=True)
    venue = models.ForeignKey(Venue)

class ListingForm(ModelForm):
    date_start = forms.DateField(input_formats=DATE_INPUT_FORMATS)
    date_end = forms.DateField(input_formats=DATE_INPUT_FORMATS)
    class Meta:
        model = Listing

如果输入=='event',则 。如果输入=='release',我希望场地是必需的= False

我该如何解决这个问题?

由于

2 个答案:

答案 0 :(得分:4)

首先Listing.venue需要允许空值

venue = models.ForeignKey(Venue, blank=True, null=True)

您的ModelForm则需要clean method。类似于以下内容

def clean(self):
    cleaned_data = super(ListingForm, self).clean()
    venue = cleaned_data.get("venue")
    type = cleaned_data.get("type")

    if type == 'event' and not venue:
        raise forms.ValidationError("A venue is required for events")

答案 1 :(得分:2)

您提到了ModelForm验证,但您应该问自己这个规则是否特定于创建带有表单的对象,或者它是否是您的数据模型本身固有的。如果是后者,那么model validation更有意义。

from django.core.exceptions import ValidationError

class Listing(models.Model):
    ...
    def clean(self):
        super(Listing, self).clean()

        if self.type == 'event' and not self.venue:
            raise ValidationError('A venue is required for events')

这将在ModelForm验证期间调用,因此它会产生相同的效果,但在模型上定义它可以让您使用Model.full_clean()方法检查数据的一致性

正如Iain所指出的,您首先需要允许venue的空值。

venue = models.ForeignKey(Venue, blank=True, null=True)