首页 > 解决方案 > 如何在 django api 中添加计算正确答案的功能?

问题描述

我正在 django 中创建测验应用程序。我创建了结果页面,但是每次在结果页面中显示正确的 ans = 0 ..plz 建议我如何更改此背后的逻辑 ...plz...plz

**view.py 的代码**

from django.shortcuts import render,redirect
from django.contrib.auth import login,logout,authenticate
from .forms import *
from .models import *
from django.http import HttpResponse
 
# Create your views here.
def home(request):
    if request.method == 'POST':
        print(request.POST)
        questions=QuesModel.objects.all()
        score=0
        wrong=0
        correct=0
        total=0
        for q in questions:
            total+=1
            print(request.POST.get(q.question))
            print(q.ans)
            print()
            if q.ans ==  request.POST.get(q.question):
                score+=10
                correct+=1
            else:
                wrong+=1
        percent = score/(total*10) *100
        context = {
            'score':score,
            'time': request.POST.get('timer'),
            'correct':correct,
            'wrong':wrong,
            'percent':percent,
            'total':total
        }
        return render(request,'result.html',context)
    else:
        questions=QuesModel.objects.all()
        context = {
            'questions':questions
        }
        return render(request,'home.html',context)

Model.py 的代码

from django.db import models

# Create your models here.
class QuesModel(models.Model):
    question = models.CharField(max_length=200,null=True)
    op1 = models.CharField(max_length=200,null=True)
    op2 = models.CharField(max_length=200,null=True)
    op3 = models.CharField(max_length=200,null=True)
    op4 = models.CharField(max_length=200,null=True)
    ans = models.CharField(max_length=200,null=True)
    
    def __str__(self):
        return self.question

标签: djangodjango-viewsdjango-templates

解决方案


if q.ans ==  request.POST.get(q.question):

它应该与选项进行比较。您正在将答案与问题本身进行比较。


推荐阅读