我正在按照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,)))
关于为什么未显示错误消息的任何帮助吗?
答案 0 :(得分: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."})
答案 1 :(得分: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,)))