I'm trying to dynamically generate python classes. Here, a django form.
class BankForm(forms.Form):
name = forms.CharField()
for i in range(10):
setattr(BankForm, 'contact_' + str(i), forms.CharField())
But when using the form, only the name field shows up. Any advice on how to do it ?
EDIT: Found out about modelform_factory, looks like it's one solution
EDIT2: Even better, looks like there is a add_fields method that I can use
You can add fields in the form's __init__ method as follows:
class BankForm(forms.Form):
name = forms.CharField()
def __init__(self, *args, **kwargs):
super(BankForm, self).__init__(*args, **kwargs)
for i in range(10):
self.fields['contact_' + str(i)] = forms.CharField()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With