django - 如何使用 zip() 函数插入数据
问题描述
我试图在使用zip()
函数获取数据后插入数据,但收到错误消息。x 是问题 id,y 是选择的答案,corrected_answer
在print(x, y, correct_answers)
. 我想通过设置的值is_correct=True
和不正确的答案来保存正确的问题is_correct=False
@login_required
@student_required
def take_exam(request, pk):
course = get_object_or_404(Course, pk=pk)
student = request.user.student
question = course.questions.filter()
#correct_answers = student.course_answers.filter(answer__question__quiz=course, answer__is_correct=True).count()
total_questions = course.questions.count()
choice = Answer.objects.filter()
marks_obtainable = Details.objects.get(course_id=course)
if request.method == 'POST':
question_pk = request.POST.getlist('question_pk')
#question_obj = Question.objects.filter(id=int(question_pk))
#question_obj = Question.objects.filter(id=question_pk)
#choice_pk = [request.POST['choice_pk{}'.format(q)] for q in question_obj]
choice_pk = [request.POST['choice_pk{}'.format(q)] for q in question_pk]
#print(marks_obtainable.marks_obtained)
zipped = zip(question_pk, choice_pk)
for x, y in zipped:
correct_answers = Answer.objects.filter(question_id=x, is_correct=True).values("id").first()['id']
print(x, y, correct_answers)
if int(y) == int(correct_answers):
z = TakenQuiz(student=student, course=course, question=x, selected_choice=y, marks_obtained=marks_obtainable, is_correct=True)
print("correct")
else:
z = TakenQuiz(student=student, course=course, question=x, selected_choice=y, marks_obtained=marks_obtainable, is_correct=False)
print("Not Correct")
return render(request, 'classroom/students/take_exam_form.html', {
'course': course,
'question': question,
'course': course,
'total_questions': total_questions,
'choice': choice,
'marks_obtainable': marks_obtainable
})
<form method="post" novalidate>
{% csrf_token %}
{% for questions in question %}
<input type="hidden" name="question_pk" value="{{ questions.pk }}">
<h3 class="text-info">{{ questions.text|safe }}</h3>
{% for choices in questions.answers.all %}
<input class="form-check-input" type="radio" name="choice_pk{{ questions.pk }}" id="choices-{{ forloop.counter }}" value="{{ choices.pk }}">
<label class="form-check-label" for="choices-{{ forloop.counter }}">
{{ choices.text|safe }}
</label>
{% endfor %}
{% endfor %}
<button type="submit" class="btn btn-primary">Submit Now →</button>
</form>
解决方案
基于错误 x 应该是 Question 实例。
您需要为每个 pk 获取 Question 对象,然后对其进行压缩。
question_pk = [Question.objects.get(pk=pk) for pk in request.POST.getlist('question_pk')]
推荐阅读
- php - 将模型保存到数据库后,是否有一种干净的方法可以使用模型的 ID?
- javascript - 如何滚动到里面的特定文本索引
- excel - 如何检查值是否仅存在于一个或其他范围内,否则会出错?
- git - 从版本控制中排除 git 中的大文件,但从远程推送/拉取它们
- python - 来自内容字段的 Django-polymorphic-tree list_display 对象名称
- node.js - 异步函数的 chai 测试失败并引发错误
- html - 不正确的自动完成输入样式;
- python - 常量名称不符合 UPPER_CASE 命名 stylepylint(invalid-name)
- react-native - React Native Drawer改变状态栏的颜色
- python - matplotlib 文本框中的表格文本