首页 > 解决方案 > Python Django - 带有查看请求的问题

问题描述

我正在使用用 Python 编写的 Django 框架构建一个测试应用程序。我想问一个问题,让用户回答问题,然后得到用户选择的答案的结果。我在检索用户选择的内容时遇到问题。

模型.py

class Question(models.Model):
    passage = models.ForeignKey(Passage, on_delete=models.CASCADE)
    questions_text = models.CharField(max_length=400)

    def __str__(self):
        return self.questions_text


class Choice(models.Model):
    correct_choices = (
        ("Correct", "Correct"),
        ("Incorrect", "Incorrect"),
    )
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    explain = models.ForeignKey(Explanation, on_delete=models.CASCADE, default="")
     choice_text = models.CharField(max_length=200)
    correct = models.CharField(max_length=10, choices=correct_choices, default='Incorrect')
    answer = models.CharField(max_length=500, default='')

    def __str__(self):
        return self.choice_text

    def check_answer(self, choice):
        return self.choices_set.filter(id=choice.id, is_answer=True).exists()

    def get_answer(self):
        return self.choices_set.filter(is_answer=True)'''

视图.py

def detail(request, question_id):
    try:
        question = Question.objects.get(pk=question_id)
     except Question.DoesNotExist:
        raise Http404("Sorry, Question does not exist")
    return render(request, 'index/details.html', {'question': question})
    
def result(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'index/results.html', {'question': question})
    
def answer(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    try:
        selected_answer = question.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        # Redisplay the question voting form.
        return render(request, 'index/details.html', {
            'question': question,
            'error_message': "Please make a Valid Selection.",
        })
    else:
        selected_answer.save()
    return HttpResponseRedirect(reverse('results', args=(question.id,)))'''

结果.html

<h1>Passage / Equation:</h1>
<p>{{ question.passage }}</p>
</div>
<div class="column" style="background-color:#bbb;">
<h1>Answer for Question: </h1>
<h1>{{ question.questions_text }}</h1>
<p>Your Choice was: **{{ choice.selected_answer }}** ##I believe this is the issue here but unable to 
figure it out##</p>
<ul>
{% for choice in question.choice_set.all %} <br>
<li>&#9658; {{ choice.choice_text }}</li>
<li>&#9644; This answer was: <b>{{ choice.correct }}</b></li>
<li>&#9677; Explanation: {{ choice.explain }}</li>
{% endfor %}

**details.py**
<form action="{% url 'results' question.id %}" method="post">
{% csrf_token %}
{% for choice in question.choice_set.all %}
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ 
choice.id }}">
<label for="choice{{ forloop.counter }}"><p>{{ choice.choice_text }}</p> 
</label><br>
{% endfor %}
<input type="submit" value="Submit Answer">

我将不胜感激有关此问题的任何反馈或帮助。

标签: pythondjangoviewrequest

解决方案


首先,我会检查在您到达结果视图时,您的数据库中是否有一条记录选择了该选项。如果有,也许问题是您没有将“选择”对象传递给模板?

#You have this line but in the template
<p>Your Choice was: **{{ choice.selected_answer }}** ##I believe this is the issue here but unable to figure it out##</p>

#But in the render you only pass the question
return render(request, 'index/results.html', {'question': question})

在渲染 result.html 之前添加这一行:

#Pass the choice to the context
choice = question.choice_set.all().first()
return render(request, 'index/results.html', {'question': question,'choice': choice})

推荐阅读