我有以下简单形式:
class ContactEmailForm(forms.ModelForm):
subject = forms.ChoiceField(choices=SUBJECT_TYPES)
class Meta:
model = ContactEmail
fields = ('name', 'email', 'subject', 'message',)
我想有条件地更改选项字段和文本输入字段之间的主题字段。
我该怎么做?
答案 0 :(得分:0)
这可以通过覆盖ContactEmailForm类中的__init__
函数来实现。
class ContactEmailForm(forms.ModelForm):
subject = forms.ChoiceField(choices=SUBJECT_TYPES)
def __init__(self, *args, **kwargs):
super(ContactEmailForm, self).__init__(*args, **kwargs)
if YOURCONDITION:
self.fields['subject'] = forms.CharField()
class Meta:
model = ContactEmail
fields = ('name', 'email', 'subject', 'message',)