Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically generate django forms [duplicate]

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

like image 625
damio Avatar asked Dec 05 '25 08:12

damio


1 Answers

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()
like image 105
Alasdair Avatar answered Dec 07 '25 20:12

Alasdair



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!