我正在使用 Django 表单集为活动制作注册表。表单集中的所有表单都有 2 个字段mem1
和mem2
,除了第一个字段。如何mem3
在第一个表单中添加额外的字段?
这是我的forms.py
:
class EventTeamForm(forms.Form):
event = forms.BooleanField()
mem1 = forms.CharField(label="Member 1", max_length = 20, required = True)
mem2 = forms.CharField(label="Member 2", max_length = 20, required = False)
class BaseEventTeamFormSet(BaseFormSet):
def clean(self):
if any(self.errors):
return
for form in self.forms:
participating = form.cleaned_data.get('event')
mem1 = form.cleaned_data.get('mem1')
if participating == True:
if mem1 == '':
raise forms.ValidationError("The 'Member 1' field is required.")
if participating == False:
if mem1 != '':
raise forms.ValidationError("Please tick the required event.")
def add_fields(self, form, index):
super(BaseEventTeamFormSet, self).add_fields(form, index)
form.fields["Member 3"] = forms.CharField()