[Fixed]-How to create a list of fields in django forms

17👍

You may be able to use formsets if your forms are identical (including their labels). e.g.

Question: __________________
Question: __________________
Question: __________________

etc. I’m assuming each form contains only one field here (the ‘Question’ field). There are three forms in this example.


If you need a dynamic number of fields in a single form, then you can use __init__ to achieve what you want (note: untested code!):

class MyForm(forms.Form):
    def __init__(self, *args, **kwargs):
        questions = kwargs.pop('questions')
        super(MyForm, self).__init__(*args, **kwargs)
        counter = 1
        for q in questions:
            self.fields['question-' + str(counter)] = forms.CharField(label=question)
            counter += 1

And you’d create the form with something like:

form = MyForm(questions=your_list_of_questions)

You’ll find this article useful: http://jacobian.org/writing/dynamic-form-generation/

6👍

Of course you can!

class MyForm(forms.Form):
    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        for i, q in enumerate(Question.objects.all()):
            self.fields['%s_field' % i] = forms.CharField(max_length=100, label=q.questionText)

Note: make sure your questions are ordered between calls.. as the field list will be repopulated upon form submission, receipt, etc.

If the data is ordered and static, it won’t be a problem.

Also you may want to look into FormSets, a list of forms which may be more fitting in your case.

Leave a comment