如果在Django表单中选中了另一个字段,则需要填写一个字段

时间:2014-04-02 15:28:41

标签: django django-forms

我有一个这样的模型:

class News(models.Model):
    is_activity = models.BooleanField(default=False)
    activity_name = models.CharField(max_length=240, blank=True, null=True)

我想要实现的是,如果选中is_activity,我需要activity_name。因此,我试图覆盖__init__方法:

class NewsForm(forms.ModelForm):
    class Meta:
        model = News

    def __init__(self, *args, **kwargs):
        super(NewsForm, self).__init__(*args, **kwargs)
        if self.fields['is_activity'] is True:
            self.fields['activity_name'].required = True


class NewsAdmin(FrontendEditableAdminMixin, admin.ModelAdmin):
    form = NewsForm

即使我在is_activity办理登机手续,activity_name也不是必需的。怎么了?

1 个答案:

答案 0 :(得分:6)

使用ModelForm.clean()方法可以访问已清理的数据 - 您可以在此处包含特定于字段的条件逻辑:

from django.core.validators import EMPTY_VALUES

class NewsForm(forms.ModelForm):
    class Meta:
        model = News

    def clean(self):
        is_activity = self.cleaned_data.get('is_activity', False)
        if is_activity:
            # validate the activity name
            activity_name = self.cleaned_data.get('activity_name', None)
            if activity_name in EMPTY_VALUES:
                self._errors['activity_name'] = self.error_class([
                    'Activity message required here'])
        return self.cleaned_data

class NewsAdmin(FrontendEditableAdminMixin, admin.ModelAdmin):
    form = NewsForm