首页 > 解决方案 > 使用涉及 HTML 的 Django 创建 AP 测验

问题描述

我目前使用 Django 3.1.2 和 Python 3.7。我在创建下面的测验时遇到问题。

这是我的代码:

视图.py

from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader


from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from .models import Question
from .models import Answer
#from .models import Answer 

# Create your views here.

def index(request):
    return render(request, 'apquiz/index.html')
    #print(request.POST)

def question(request):
    template = loader.get_template('apquiz/hi.html')
    #questions = ["1. What is Dosie's position in PURPLE KISS?", "2. Yuki's position in PURPLE KISS, based on this excerpt is:","3. PURPLE KISS has how many members:","4. PURPLE KISS debuted on","5. Which of the following is PURPLE KISS's main vocalist?"]
    #answers = [{'a. main rapper, main dancer, vocalist':0,'b. lead dancer, lead rapper':0, 'c. main dancer, vocalist':1,'d. main dancer, lead rapper':0},{'a. lead dancer, vocalist, rapper, visual':0,'b. lead rapper, lead dancer, vocalist, visual':0, 'main rapper, lead dancer, vocalist, visual':1, 'd. main vocalist, lead dancer, rapper, visual':0},{'a. 7':1,'b. 2':0,'c.9':0,'d.2':0},  {'a. August 3, 2020':0,'b. March 15, 2021':1, 'c. February 3, 2021':0,'d. November 26, 2020':0},{'a. Yuki':0,'b. Dosie':0,'c. Jieun':0,'d. Swan':1}]  
    #questions = Question.objects.get()
    #answers = Answer.objects.get()
    question_set=Question.objects.all()
    answer_set=Answer.objects.all()
    context = {}
    numberofquestions = len(question_set)
    numberofanswers = len(answer_set)
    numberofcorrectanswers = 0
    for i in question_set:
        for j in answers:
            if i == j:
                #context[i] = j #mke sure questions correspond to answrs
                context['questions'] = question_set
            if j.values == 1: #select the correct answer
                numberofcorrectanswers += 1
    percent = (numberofcorrectanswers/numberofquestions) * 100
    if percent >= 25 and percent <= 50:
        score = 2
    elif percent > 50 and percent < 75:
        score = 3
    elif percent >= 75 and percent < 90:
        score = 4
    elif percent >= 90:
        score = 5
    else:
        score = 1
    response = "You are on track to get a" + str(score) + "on an exam like this."
    return render(request, "apquiz/hi.html", context)

模型.py

from django.db import models
import random
from jsonfield import JSONField


# Create your models here.
def question():
    return ["1. What is Dosie's position in PURPLE KISS?", "2. Yuki's position in PURPLE KISS, based on this excerpt is:","3. PURPLE KISS has how many members:","4. PURPLE KISS debuted on","5. Which of the following is PURPLE KISS's main vocalist?"]

def answer():
    return {'a. main rapper, main dancer, vocalist':0,'b. lead dancer, lead rapper':0, 'c. main dancer, vocalist':1,'d. main dancer, lead rapper':0},{'a. lead dancer, vocalist, rapper, visual':0,'b. lead rapper, lead dancer, vocalist, visual':0, 'main rapper, lead dancer, vocalist, visual':1, 'd. main vocalist, lead dancer, rapper, visual':0},{'a. 7':1,'b. 2':0,'c.9':0,'d.2':0},  {'a. August 3, 2020':0,'b. March 15, 2021':1, 'c. February 3, 2021':0,'d. November 26, 2020':0},{'a. Yuki':0,'b. Dosie':0,'c. Jieun':0,'d. Swan':1}


class Question(models.Model):
    question_text = models.CharField(max_length=255,default=question)
    #question_text = ["1. What is Dosie's position in PURPLE KISS?", "2. Yuki's position in PURPLE KISS, based on this excerpt is:","3. PURPLE KISS has how many members:","4. PURPLE KISS debuted on","5. Which of the following is PURPLE KISS's main vocalist?"]
    #created = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.question_text

    #correct answer

class Answer(models.Model):
    answer_text = JSONField(default=answer)
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    def __str__(self):
        return self.answer_text

网址.py

from django.contrib import admin
from django.urls import include, path
from . import views
from django.conf import settings
#from django.conf.urls.static import static

app_name= 'apquiz'

urlpatterns = [
    path('admin/', admin.site.urls),
    path('quiz/', views.question, name = 'quiz'),
]

嗨.html

<h1>{{ question.question_text }}</h1>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}

<form action="" method="post">
{% csrf_token %}
{% for question in questions %} 
    <input type="radio" name="choice" id="choice{{ forloop.counter0 }}" value="{{ choice.id }}">
    <label for="answer{{ forloop.counter }}">{{ answer }}</label><br>
{% endfor %}
<input type="submit" value="Submit Quiz">
<h1>{{ question }}</h1>

<ul>
{% for choice in question.choice_set.all %}
    <li>{{ answer }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
{% endfor %}
</ul>

</form>

这些是我最常使用的页面。如果有人可以帮助我修复这些文件,将不胜感激。我正在尝试使用多项选择答案进行测验,而无需使用管理文件进行编辑(这意味着它已经给出并且您无法在管理站点中更改它们),并且为了编辑这些问题,您必须自己编辑代码. 截至目前,我只看到一个没有返回任何内容的答案按钮。我需要它来返回从 1 到 5 的分数(我试图模仿 Ap 考试)。如果有人可以帮助我处理此代码或让我知道任何错误,我们将不胜感激。我的 HTML 技能不是很好,我特别需要这部分的帮助,就像我不知道如何正确显示它们一样。

标签: pythondjango

解决方案


我稍微调整了你的代码。我希望这能给你一个起点。

模型.py

class Question(models.Model):
    question_text = models.CharField(max_length=255)
    correct_answer = models.CharField(max_length=255)

    def __str__(self):
        return self.question_text

class Answer(models.Model):
    answer_text = models.CharField(max_length=255)
    question = models.ForeignKey(Question, on_delete=models.CASCADE)

    def __str__(self):
        return self.answer_text

管理员.py

通过管理面板添加您的QuestionAnswer并创建关系到每个Question

admin.site.register(Question)
admin.site.register(Answer)

嗨.html

<form action="" method="post">
{% csrf_token %}
{% for question in questions %}
  <h1>{{ question.question_text }}</h1>
  {% for answer in question.answer_set.all %}
    <input type="radio" name={{ question.pk }} value="{{ answer.answer_text }}">
    <label for="answer{{ forloop.counter }}">{{ answer }}</label><br>
  {% endfor %}
{% endfor %}
<input type="submit" value="Submit Quiz">
<h1>Your score is {{ score }}/{{ questions.count }}</h1>
</form>

视图.py

def question(request):
    questions = Question.objects.all()
    context = {'questions': questions, 'score': 0}

    if request.method == 'GET':
        return render(request, "apquiz/hi.html", context)
    elif request.method == 'POST':
        data = request.POST.copy()
        data.pop('csrfmiddlewaretoken')  #  remove key bc at Question.objects.get(pk='csrfmiddlewaretoken') won´t be found
        score = 0
        for key, value in data.items():  # key is primary key of name={{ question.pk }} in your "hi.html", value contains your choosen answer 
            if Question.objects.get(pk=key).correct_answer == value:
                score += 1
        context['score'] = score
        return render(request, "apquiz/hi.html", context)

推荐阅读