好吧,帮帮我,我快疯了!
我有 4 个问题,每个问题的单选按钮名称设置为问题 id,值设置为答案 id 以获取答案的 id 并使用它来获取用户提交的答案以检查它是否正确。< /p>
views.py
def sampleQuestions(request):
if request.method == 'POST':
user = request.user
userInformation = UserInformation.objects.get(user=user)
allAnswers = Answers.objects.all()
allQuestions = Questions.objects.all()
i = 0
for q in Questions.objects.all():
print(q.id) #returns 1
answerID = request.POST.get(q.id) #returns None
print(answerID)
answer = Answers.objects.get(id=answerID)
print(answer)
模板.html
{% for q in questions %}
<table>
<tr>
<td> {{q.question}}</td>
</tr>
{% for a in answers %}
{% if a.answerForQuestion == q%}
<tr>
<td> <input type="radio" name = "{{q.id}}" value="{{a.id}}"> {{a.answer}}</td>
{{q.id}}
</tr>
{% endif %}
{% endfor %}
</fieldset>
</table>
{% endfor %}
答案 0 :(得分:1)
request.POST
id 一个 python 字典,key 作为字符串。所以在键查找中提供一个字符串。
answerID = request.POST.get(str(q.id)) #returns None