Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a list of fields in django forms

Is there any way to make a django forms class that actually holds an array of fields? I have a database that will pull up a variable number of questions to ask the user and each question will know how to define it's widget...etc, I just can't seem to hook this up to django forms.

I tried this:

class MyForm(forms.Form):
    question = []
    questions = Question.objects.all()
    for q in questions:
        question.append(forms.CharField(max_length=100, label=q.questionText))

But this doesn't seem to expose my questions list when I create a new instance of MyForm. Is there any way to get a variable number of form fields using django forms, or is this beyond the scope of what it can do?

like image 671
Kevin DiTraglia Avatar asked Jun 18 '13 02:06

Kevin DiTraglia


People also ask

How do I get form fields in django?

Basically to extract data from a form field of a form, all you have to do is use the form. is_valid() function along with the form. cleaned_data. get() function, passing in the name of the form field into this function as a parameter.

What is form Is_valid () in django?

The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class. It returns True if data is valid and place all data into a cleaned_data attribute.

What is forms ModelForm in django?

Django Model Form It is a class which is used to create an HTML form by using the Model. It is an efficient way to create a form without writing HTML code. Django automatically does it for us to reduce the application development time.

What is form AS_P in django?

{{ form.as_p }} – Render Django Forms as paragraph. {{ form.as_ul }} – Render Django Forms as list.


1 Answers

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/

like image 61
stellarchariot Avatar answered Oct 08 '22 20:10

stellarchariot