Django and switches

I am using a quiz app and I am showing multiple choice answers using radio buttons.

I need to group the answers to a question, so I have this as

{% 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 a 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 get casting through quotes?

I have tried request.POST.getlist('score')

and returns an empty list

PS. quiz.id cannot be sequential, it is from the database row id.

My current job:

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

      

+3


source to share


2 answers


Just filter out 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 a 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 I went about was to keep the name for each radio button the same (like a score) and then merge the quiz id with the value:

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

      

Then you can easily list all results and split the values:

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

      

+3


source


You are using PHP-ism by naming the inputs score[{{quiz.id}}]

. Do not do this. Just name them all score

and your browser will do it right by putting them all in the same POST value that you can get through request.POST.getlist('score')

.



+2


source







All Articles