Django ModelForm:当用户从 RadioSelect 中选择 "Other" 时,使 "Other" Textarea 成为必需项

Django ModelForm: Making an "Other" Textarea manditory when the user selects "Other" from RadioSelect

我正在将调查从表单转换为 Django 1.6.2 中的模型表单。我想创建一个 "Other" forms.Textarea,如果用户从 forms.RadioSelect select "Other",则必须填写该 "Other" forms.Textarea。我希望仅当来自 forms.RadioSelect.

的用户 selects "Other" 时才强制执行此操作

到目前为止,这是我的代码,可以正常提交,但 forms.Textarea 不是强制性的。谁能看到我做错了什么?谢谢

如果我从 party_benefit_message 中删除 blank=True,,则每个 forms.RadioSelect selection 上的 forms.Textarea 都是强制性的。

models.py

PARTY_BENEFIT = (
    ('NO', 'No'),
    ('YES_DEMOCRAT', 'Yes, Democrat'),
    ('YES_REPUBLICAN', 'Yes, Republican'),
    ('YES_OTHER', 'Other') )   
party_benefit = models.CharField(null=True, max_length=100, default=None, choices=PARTY_BENEFIT, verbose_name="Does one or another political party benefit more than the others due to Biased coverage in the media? \n And if so which?")
party_benefit_message = models.CharField(max_length=1000, blank=True, verbose_name='If you selected \"Other\", please specify:')

def clean_other(self):
    cleaned_data = super(SurveyFormG, self).clean()
    if 'party_benefit' in cleaned_data.keys():
      options = cleaned_data['party_benefit']
      if 'party_benefit_message' in options:
        other_input = cleaned_data['party_benefit_message']
        if other_input == None or len(other_input) == 0:
          raise forms.ValidationError('Required when \"Other\" is checked')

    return cleaned_data

forms.py

class SurveyFormG(forms.ModelForm): #Reflective Questions

    class Meta:
        model = Person
        fields = ['party_benefit', 'party_benefit_message']        

        widgets = {'party_benefit' : forms.RadioSelect,
                   'party_benefit_message' : forms.Textarea} 

如有任何帮助,我们将不胜感激。谢谢

你必须在你的模型上定义一个自定义的清理方法(而不是在你的表单上,以使这个验证更可重用):

models.py

from django.core.exceptions import ValidationError

class Person(models.Model):

    PARTY_BENEFIT = (
        ('NO', 'No'),
        ('YES_DEMOCRAT', 'Yes, Democrat'),
        ('YES_REPUBLICAN', 'Yes, Republican'),
        ('YES_OTHER', 'Other')
    )   
    party_benefit = models.CharField(null=True, max_length=100, default=None, choices=PARTY_BENEFIT, verbose_name="Does one or another political party benefit more than the others due to Biased coverage in the media? \n And if so which?")
    party_benefit_message = models.CharField(max_length=1000, blank=True, verbose_name='If you selected \"Other\", please specify:')

    def clean(self):
        if self.party_benefit == 'YES_OTHER' and not self.party_benefit_message:
            raise ValidationError({'party_benefit_message': ['You must enter a message.']})

更多关于模型验证的信息:https://docs.djangoproject.com/en/1.8/ref/models/instances/#django.db.models.Model.clean

你的表格没有变化。

我会这样写(clean 方法在你的 ModelForm 中):

def clean(self):
    benefit_option = self.cleaned_data.get('party_benefit')
    message = self.cleaned_data.get('party_benefit_message')
    if benefit_option and benefit_option == 'YES_OTHER' and message is None:
        raise forms.ValidationError('Message is required when \"Other\" is checked')