3

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

damio
  • 6,041
  • 3
  • 39
  • 58
  • probably because you're setting attributes on `MyForm` and not `BankForm`. But maybe just a typo? – marcusshep Aug 10 '16 at 15:15
  • 1
    oops, edited, no, it would have triggered an undefined variable exception – damio Aug 10 '16 at 15:17
  • 1
    The `modelform_factory` method is useful for creating model forms, but not really suited for this case where you want to add fields to a regular form. The add_fields` method is for *formsets*, not forms. – Alasdair Aug 10 '16 at 16:03

1 Answers1

7

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()
Alasdair
  • 298,606
  • 55
  • 578
  • 516
  • thanks, found it was already answered here so it show be closed as duplicate: https://stackoverflow.com/questions/6142025/dynamically-add-field-to-a-form – damio Aug 10 '16 at 15:30