A
A
Animkim2016-07-13 11:12:57
Django
Animkim, 2016-07-13 11:12:57

Django forms, how to dynamically add fields?

class MyForm(forms.Form):
    slug = forms.CharField(max_length=50)

There is a form, you need to dynamically add an unknown number of fields of the same type to it in advance.
I can’t figure out how to turn something like that, can someone kick in the right direction?
This came to my mind, but I don’t know how true it is, pseudocode.
class MyForm(forms.Form):
    def __init__(self, *args):
         super(MyForm, self).__init__(*args)
         self.fields.update({'fields': forms.CharField(max_length=50),})
    slug = forms.CharField(max_length=50)

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Dmitry Tiunov, 2016-07-14
@Animkim

class MyForm(forms.Form):
    def __init__(self, *args, **kwargs):
        slugs_cnt = kwargs.pop('slugs_cnt', None)
        super(MyForm, self).__init__(*args, **kwargs)

        if slugs_cnt:
            for i in xrange(1, slugs_cnt + 1):
                self.fields['slug_{}'.format(i)] = forms.CharField(max_length=50)

Z
zelsky, 2016-07-13
@zelsky

Formset.

A
Alexey, 2016-07-13
@MAKAPOH

Try this, create a form class as you go:

MyForm = type('MyForm', (forms.Form,), {
    'slug01': forms.CharField(max_length=50),
    'slug02': forms.CharField(max_length=50),
    'slug03': forms.CharField(max_length=50),
})
form = MyForm()
...

Poidee should work.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question