如何解决Django-如何通过多次尝试在测验应用程序中进行评分
我正在Django中制作一个测验应用程序,并在计分上挣扎。
这是我的模型设置:
class Quiz(models.Model):
song = models.ForeignKey(Song,null=True,on_delete=models.CASCADE)
title = models.CharField(max_length=15)
slug = models.SlugField(unique=True,max_length=250)
questions_count = models.IntegerField(default=0)
class Question(models.Model):
quiz = models.ForeignKey(Quiz,on_delete=models.CASCADE)
label = models.CharField(max_length=1000,help_text="Enter the question text that you want displayed")
class Choice(models.Model):
question = models.ForeignKey(Question,on_delete=models.CASCADE)
answer = models.CharField(max_length=100)
is_correct = models.BooleanField('Correct answer',default=False)
class QuizTaker(models.Model):
user = models.ForeignKey(User,on_delete=models.CASCADE)
quiz = models.ForeignKey(Quiz,on_delete=models.CASCADE)
correct_answers = models.IntegerField(default=0)
completed = models.BooleanField(default=False)
attempt_number = models.AutoField(primary_key=True)
在我的html中,测验显示如下:
{% for q in question_list %}
{{q}} <br>
{% for choice in q.choice_set.all %}
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.answer }}">
<label for="choice{{ forloop.counter }}">{{ choice.answer }}</label><br>
{% endfor %}
<a class='btn btn-warning save_ans' href="#">Save answer</a>
通过ajax调用处理每个问题的答案,并将其发送到以下视图:
ans_given = []
def save_ans(request):
ans = request.GET['ans']
ans_given.append(ans)
return HttpResponse(ans)
我已经按照以下方法评分:
ans_correct = []
answers = models.Choice.objects.filter(is_correct=True)
for i in answers:
scoring['ans_correct'].append(i.answer)
def quiz_results(request,pk):
score = 0
quiz = models.Quiz.objects.get(song__pk=pk)
count = quiz.questions_count
questions = models.Question.objects.filter(quiz=quiz)
for i in range(len(questions)):
if ans_given[i] == ans_correct[i]:
score +=1
combined = list(zip(scoring['ans_correct'],scoring['ans_given']))
return render(request,'quizzes/quiz_song_result.html',{'score': score,'combined': combined})
这可以正常工作,但这只是第一次。我想允许用户多次尝试测验。第一次之后,我收到一个list index out of range
错误,这当然是有道理的,因为它保留了第一个n
答案,并向列表中添加了n
,而长度为{ {1}}当然不会改变。
我尝试了各种方法来解决此问题,但无济于事。我尝试使用ans_correct
代替insert
,但是无法正确建立索引。我尝试将append
放在函数的开头,以便每次都从一个干净的列表开始,但是它会在每个答案之后(而不是在整个测验之后)清除列表。
我也尝试过这样的答案:
ans_given.clear()
然后以类似方式进行评分。在这种情况下,列表的长度至少相等,但是计分仍然无效,并且弄乱了我的模板。
我很确定对此有一个简单的解决方案,但我只是没有看到。还是有一种更好的方式来做我想做的事...所以,如果有人可以帮助我,我将非常感激!
编辑: 我设法解决了以下问题(,但我仍然热衷于提出有关如何以不同方式进行处理的建议,即使这意味着要对其进行大量重新设计。)
for question in questions:
answer = models.Choice.objects.values_list('answer',flat=True).get(is_correct=True,question=question)
scoring['ans_correct'].append(answer)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。