[Fixed]-How to properly recieve data from list of forms?

1👍

Here is one possible improvement to the design:

Instead of QuestionForm, make a QuizForm. Pass sitting.sitting_questions.all() to your form, and make each one its own ChoiceField. This will make it much easier to process your form. Once you initialize whatever variables you need, handling in the view is usually as simple as this:

if request.method == 'POST':
    form = QuizForm(request.POST)
    if form.is_valid():
        # whatever you'd like to do
else:               # GET
    form = QuizForm(list_of_questions)

There is no need to parse to get the question id, you can just call question.id or question.pk.

some elaboration:

class QuizForm(forms.Form):
    def __init__(self, questions, *args, **kwargs):
        super(QuizForm, self).__init__(*args, **kwargs)
        for question in questions:
            choice_list = [("QUESTION TEXT", question.text)]
            choice_list.append([(x.pk, x.text) for x in question.get_answers_list()])
            self.fields["question-{}".format(question.id) = forms.ChoiceField(
                choices=choice_list,
                widget=forms.RadioSelect
             )

Update: How to add Question text before options.

If your QuizForm has fields which are all questions, then when you iterate over your field you will get these question fields: {% for question in form %}. Since question is a field and not the actual Question object, I admit you can’t simply access question.text in the loop. However, you can decide to add question.text to the choices field (a little hack-ish, but functional), I’ve included this possibility above. Then try something like this:

{% for question in form %}
{% for id, text in question.field.choices %}
{% if id == 'QUESTION TEXT' %}
    {{ text }}
{% else %}
    <!-- render however you like -->
{% endif %}
{% endfor %}
{% endfor %}

For rendering buttons: https://docs.djangoproject.com/es/1.9/ref/forms/widgets/#radioselect
I think there are a lot of similar questions on SO already for how to render the choices.

Leave a comment