python - 尝试在详细 View 中覆盖模板名称时出现 TemplateDoesNotExist

标签 python django

我正在关注 django 2.0 教程“2.6.2 使用通用 View :代码越少越好”,并尝试将函数 View 转换为类 View 。

它抛出这样的错误:

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 模板在带有函数 View 时可以正常工作:

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

我的代码有什么问题?

最佳答案

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

如果你想覆盖它,你需要使用 template_name。您已经设置了template,这不会有任何效果。应该是:

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

关于python - 尝试在详细 View 中覆盖模板名称时出现 TemplateDoesNotExist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50116204/

相关文章:

python - pandas.apply() 从两列之间的差异返回 NaN

python - tastypie get_list 过滤器查询集

django - 应该对 Django 中基于类的 View 使用 GET/POST 或特定方法吗?

python - 如何在 python 中为每一对分开做矩阵向量内积?

python - 从树递归返回值列表

python - Python 中的静态对象列表

javascript - react 路由和django url冲突

python - 如何在 Django REST 中实现方法?

python - Django Model Choice Field 如何返回对象的主键而不是显示值

python - 如何在 Python 中编写一个永远在线的 "Quit"选项?