我正在关注django 2.0教程" 2.6.2使用通用视图:更少代码更好"并尝试将函数视图转换为类视图。
它引发了这样的错误:
TemplateDoesNotExist at /polls/1/results/
polls/question_detail.html
Request Method: GET
Request URL: http://127.0.0.1:8000/polls/1/results/
Django Version: 2.0.4
我使用官方资料检查了代码
class ResultsView(generic.DetailView):
model = Question
template = 'polls/results.html'
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):
#Redisplay the question voting form
return render(request, 'polls/detail.html', {
'question':question,
'error_message':"You did'nt select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
当我尝试提交投票时发生错误:
polls/detail.html
模板与函数视图一起正常工作:
<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>
我的代码有什么问题?
答案 0 :(得分:6)
默认情况下,DetailView
应用中Question
模型的polls
使用模板polls/question_detail.html
。
如果要覆盖它,则需要使用template_name
。您已设置template
,这将无效。它应该是:
class ResultsView(generic.DetailView):
model = Question
template_name = 'polls/results.html'
...