7

I need some help. How can I handle the form ,with multiple input field values, with same name? and only once view, this actually for basic questions form.. another idea I found this method from https://stackoverflow.com/a/478406/6396981:

relations = request.POST.getlist('relations')

django questions form

How do I handle it all? Currently I'm doing it with <input type="radio"..., but of course it couldn't work if it has same name in once form. But if I use: <input type="checkbox"..., the answers can be check more than 1 in once question...

Maybe like this:

<input type="radio" name="answer-{{ question.id }}">

How can I get it all in the view?

Solved:

In my test:

{% for question in questions %}
    <input type="hidden" name="question" value="{{ question.id }}/>

    {% for answer in question.get_answers %}
        <input type="radio" name="answer-{{ question.id }}" value={{ answer.score }}>
    {% endfor %}
{% endfor %}

views.py

questions = request.POST.getlist('question')
answers = [request.POST['answer-{}'.format(q)] for q in questions]

And the results of it:

['20', '19', '16', '13', '11', '10', '9', '8', '1']
['5', '2', '3', '4', '1', '4', '4', '2', '2']
2
  • 1
    This is very unclear. Checkboxes and radio buttons are supposed to have more than one option with the same input name. What exact problem are you experiencing? And why aren't you using the Django forms API? Commented Nov 24, 2016 at 11:09
  • how i can do with Django forms with dynamically, if have many questions? Commented Nov 24, 2016 at 11:23

1 Answer 1

3

If I understood you right you need to implement multiple choice? Then you can do in your template this:

{% for answer in answers %}
    <input type="checkbox" name="answer" id="answer{{ forloop.counter }}" value="{{ answer.id }}">
{% endif %}

Andi in view:

answer = request.POST.getlist('answer')
for el in answer:
    pass
Sign up to request clarification or add additional context in comments.

1 Comment

previously i doing same with this.. but only once answer which successfully saved...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.