The code I use is:
class VoteForm(forms.ModelForm):
other_choice1 = forms.BooleanField(required=False)
other_choice2 = forms.BooleanField(required=False)
other_choice3 = forms.BooleanField(required=False)
other_choice4 = forms.BooleanField(required=False)
class Meta:
model = Vote
exclude = ('choice', 'other_choices',)
def __init__(self, poll_id, *args, **kwargs):
super(VoteForm, self).__init__(*args, **kwargs)
p = get_object_or_404(Poll, pk=poll_id)
choices = p.choice_set.all()
choices_len = len(choices)
f = ['other_choice1','other_choice2','other_choice3','other_choice4']
for i in range(0,choices_len):
self.fields[f[i]].label = str(choices[i])
for i in range(choices_len,4):
del self.fields[f[i]]
This is the best way I’ve found to modify form’s fields at runtime. It seems a bit like hacking the implementation. What’s the well-defined way to do that?
Thanks,
Alex
Use
base_fieldsas explained in Monkey patching a Django form class? :(Or
BaseFormas explained here http://snipt.net/danfreak/how-to-generate-a-dynamic-at-runtime-form-in-django/ :