Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django教程-错误消息不';t显示_Python_Django - Fatal编程技术网

Python Django教程-错误消息不';t显示

Python Django教程-错误消息不';t显示,python,django,Python,Django,我正在学习Django教程。当前位于,如果您未选择选项就进行投票,则页面应重新加载,并在投票上方显示一条错误消息。但是,当我这样做时,页面会重新加载,但不会显示任何错误消息。顺便说一句,开发服务器没有显示任何错误 以下是模板代码: <h1>{{ question.question_text }}</h1> {% if error_message %}<p><strong>{{ error_message }}</strong></

我正在学习Django教程。当前位于,如果您未选择选项就进行投票,则页面应重新加载,并在投票上方显示一条错误消息。但是,当我这样做时,页面会重新加载,但不会显示任何错误消息。顺便说一句,开发服务器没有显示任何错误

以下是模板代码:

<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>

关于为什么没有显示错误消息有什么帮助吗?

我真的很惊讶您没有从
render
收到错误消息

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

#这行。。。
返回呈现(请求,'polls/detail.html',{'question':question},{'error_message':“您没有选择。”})
#…应该这样写。
返回呈现(请求,'polls/detail.html',{'question':问题,'error_message':“您没有选择选项。”)

传递上下文词典作为回报,而不是传递两个不同的dict。所以你的观点是这样的

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,)))

啊,我知道我在那里做了什么,谢谢!现在一切都好了。谢谢你,我明白我犯的错误了!
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,)))