Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django multiple input field values with same name

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']
like image 464
binpy Avatar asked Nov 24 '16 10:11

binpy


1 Answers

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
like image 62
neverwalkaloner Avatar answered Nov 14 '22 10:11

neverwalkaloner