Django教程-不显示错误消息

问题描述 投票:0回答:2

我正在按照Django教程的方式工作。当前位于Part 4,如果您在未选择任何选项的情况下进行投票,则页面应重新加载,并在民意调查上方显示错误消息。但是,当我这样做时,页面将重新加载,但是没有显示错误消息。顺便说一句,开发服务器未显示任何错误。

这是模板代码:

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

<form action="{% url 'polls:vote' 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 }}">{{ choice.choice_text }}</label><br>
{% endfor %}
<input type="submit" value="Vote">
</form>

这是view.py函数的摘录片段:

def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = question.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        return render(request, 'polls/detail.html', {'question': question}, {'error_message' : "You didn't select a choice."})
    else:
        selected_choice.votes += 1
        selected_choice.save()
        return HttpResponseRedirect(reverse('polls:results', args=(question_id,)))

关于为什么不显示错误消息的任何帮助?

python django
2个回答
0
投票

老实说,您没有收到来自render的错误消息。

您要将上下文数据作为两个字典传递给模板,但是Django不能那样工作。您只需要一本提供所有上下文数据的字典。

# This line...
return render(request, 'polls/detail.html', {'question': question}, {'error_message' : "You didn't select a choice."})

# ...should be written like this instead.
return render(request, 'polls/detail.html', {'question': question, 'error_message' : "You didn't select a choice."})

0
投票

传回上下文字典,而不是传递两个不同的字典。所以您的看法将是这样。

def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = question.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        context = {
         'question': question, 
         'error_message' : "You didn't select a choice.",
        }
        return render(request, 'polls/detail.html', context)
    else:
        selected_choice.votes += 1
        selected_choice.save()
        return HttpResponseRedirect(reverse('polls:results', args=(question_id,)))
© www.soinside.com 2019 - 2024. All rights reserved.