James Lin
James Lin

Reputation: 26588

Django and radio buttons

I am implementing a quiz app and I am displaying the multiple choice answers using radio buttons.

I need to group the answers per question, so I have it like this

{% for answer in quiz.quizanswer_set.all %}
<p><input type="radio" name="score[{{quiz.id}}]" value="{{answer.score}}"/>{{answer.answer}}</p>
{% endfor %}

When I hit submit, I have the POST object like this

<QueryDict: {u'score[1]': [u'10'], u'score[3]': [u'10'], u'score[2]': [u'10'], u'Get Result': [u'Submit']}>

How do I loop through the scores in a canonical way?

I have tried request.POST.getlist('score') and it returns empty list

PS. the quiz.id may not in sequence, it's from the database row id.

My current work around is:

for quiz in Quiz.objects.all():
        total_score += int(request.POST.get('score[{0}]'.format(quiz.id)))

Upvotes: 3

Views: 2512

Answers (2)

Daniel Roseman
Daniel Roseman

Reputation: 599956

You are using a PHP-ism by naming the inputs score[{{quiz.id}}]. Don't do that. Just call them all score, and your browser will do the right thing by putting them all in the same POST value which you can then get via request.POST.getlist('score').

Upvotes: 2

Giles Smith
Giles Smith

Reputation: 1972

Just filter the POST keys:

for score_key in filter(lambda key:key.startswith('score'), request.POST.keys()):

    total_score += int(request.POST[score_key])

Update

Thinking about it, a list comprehension would be better than filter:

for score_key in [key for key in request.POST.keys() if key.startswith('score[')]:

   total_score += int(request.POST[score_key])

Update 2

Another way that I have been looking into, is keeping the name for each radio button the same (e.g. score) and then merging the quiz id with the value:

<input type="radio" name="score" value="{{quiz.id}}-{{answer.score}} /> 

You could then easily get a list of all scores and split the values:

for value in request.POST['score']:
    quiz_id, score = value.split('-')

Upvotes: 3

Related Questions