如何在Django的测验应用程序中检查候选人选择的选项是否正确?

时间:2018-04-14 20:50:22

标签: python django

我正在Django中制作一个Quiz应用程序,我想知道如何才能让用户正确回答问题的数量?

models.py

class Question(models.Model):
    question_text = models.CharField(max_length=15000)
    def __str__(self):
        return self.question_text
    
class Choice(models.Model):
    choice = models.ForeignKey(Question, on_delete = models.CASCADE)
    choice_text = models.CharField(max_length=15000)
    def __str__(self):
        return self.choice_text
class CorrectChoice(models.Model):
    answer = models.ForeignKey(Question, on_delete = models.CASCADE, default = "")
    correct_choice = models.CharField(max_length=1500)
    def __str__(self):
        return self.correct_choice

模板

<form action = '/quiz/next/' method = 'post'>
            {% csrf_token %}
            <h2>{{ question }}</h2>
            {% for choice in question.choice_set.all %}
            <input type = 'radio' name = 'choice' id = 'choice' value = '{{ choice.choice_text }}'>&nbsp;&nbsp;{{ choice.choice_text }}<br>
            {% endfor %}
            <br>
            <button class = 'btn btn-primary' type = 'submit' style = 'width: 100px'>Submit</button>
        </form>

views.py

def next_ques(request):
    if request.method == 'POST':
     choices = []
     choice = request.POST['choice']
     choices.append(choice)
     choices = set(choices)
     answers = set(CorrectChoice.objects.all())
     total = len(choices.intersection(answers))
     question = e.next_question()
     if question == False :
        return HttpResponse(str(total))
     else :
      context = {
         'question':question
      }
      return render(request, 'quiz.html', context)
    else :
        return('Invalid')

每当我运行此代码时,我总计为0

1 个答案:

答案 0 :(得分:0)

我想......

choices是一组数字,是个别Choice模型记录的ID。

answers是一组Choice模型记录。

他们不会相交。