没有得到我的mcq应用程序 - Django得分

时间:2017-02-08 19:43:37

标签: python django

对于我的MCQ应用,我创建了一个视图

def process_data(request):
question_set=Question.objects.all()
choice_list=[]
question_set
for k, v in request.POST.items():
    if k.startswith('choice'):
        choice_list.append(v)
i=0
score=0
print type(question_set)
for question in question_set:
        if question.answer1==choice_list[i]:
            #print question.answer1
            i=i+1
            score=score+1
return HttpResponse(score)

html页面包含的表单如下所示。

{% extends 'quiz/base.html' %}
{% block content%}
<h1>You are at quiz page</h1>

<form action="{% url 'quiz:process_data' %}" method="post">
    {% csrf_token %}
    {% for question in question_set %}
        <h3>{{question.question_no}}.{{question.question_text }}</h3>
        <input type="radio" name="choice{{ question.question_no}}" value="{{ question.option1 }}">{{ question.option1 }}<br>
        <input type="radio" name="choice{{ question.question_no}}" value="{{ question.option2 }}">{{ question.option2 }}<br>
        <input type="radio" name="choice{{ question.question_no}}" value="{{ question.option3 }}">{{ question.option3 }}<br>
        <input type="radio" name="choice{{ question.question_no}}" value="{{ question.option4 }}">{{ question.option4 }}<br>
        <input type="radio" name="choice{{ question.question_no}}" value="{{ question.option5 }}">{{ question.option5 }}<br>
    {% endfor %}
    <input type="Submit" name="Submit">
</form>
{% endblock%}

这是问题的模型

class Question(models.Model):
  question_no=models.IntegerField(default=0)
  question_text=models.CharField(max_length=1000)
  option1=models.CharField(max_length=100)
  option2=models.CharField(max_length=100)
  option3=models.CharField(max_length=100)
  option4=models.CharField(max_length=100)
  option5=models.CharField(max_length=100)
  answer1=models.CharField(max_length=100)

  def __str__(self):
    return self.question_text

问题是得分没有正确。所以我用print语句对它进行了测试,并意识到只有第一个问题的答案才会得到。我怎样才能正确得分?谢谢

1 个答案:

答案 0 :(得分:0)

问题在于您如何处理此调用request.POST.item。对item函数的调用返回无序字典。这导致您的第二个for循环将用户输入与错误的问题相匹配。以下是我的意思的示例代码:

user_inputs = request.POST.items() # key: choice<question_no> and value: <user_choice>
for question in question_set:
    user_choice = user_inputs.get('choice'+question.question_no)
    if user_choice == question.answer1:
         //count the score