尝试在详细信息视图中覆盖模板名称时的TemplateDoesNotExist

时间:2018-05-01 12:08:06

标签: python django

我正在关注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,)))

当我尝试提交投票时发生错误:

enter image description here

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>

我的代码有什么问题?

1 个答案:

答案 0 :(得分:6)

默认情况下,DetailView应用中Question模型的polls使用模板polls/question_detail.html

如果要覆盖它,则需要使用template_name。您已设置template,这将无效。它应该是:

class ResultsView(generic.DetailView):
    model = Question
    template_name = 'polls/results.html'
    ...