3👍
✅
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('-')
2👍
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')
.
Source:stackexchange.com