Django教程第3部分:创建视图和模板时出错

时间:2017-06-13 17:22:04

标签: python-3.x django-templates django-views jinja2

我开始学习Django(1.11)并遵循Django Tutorials。在这部分我应该用模板创建动态视图(索引方法)。但在我创建模板

之后
{% if latest_question_list %}
    <ul>
    {% for question in latest_question_list %}
        <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>
    {% endfor %}
    </ul>
{% else %}
    <p>No polls are available.</p>
{% endif %}

和使用模板的索引视图

from django.http import HttpResponse
from django.template import loader

from .models import Question


    def index(request):
        latest_question_list = Question.objects.order_by('-pub_date')[:5]
        template = loader.get_template('polls/index.html')
        context = {
            'latest_question_list': latest_question_list,
        }
        return HttpResponse(template.render(context, request))

我去了一个错误:  * / polls /的NameError *全球名称&#39; latest_question_list&#39;未定义**

2 个答案:

答案 0 :(得分:1)

请改为尝试:

from django.shortcuts import render def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request,'polls/index.html',context)

答案 1 :(得分:1)

尝试这个:

...

from django.template import loader

from .models import Question

def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
    template = loader.get_template('polls/index.html')
    context = {'latest_question_list': latest_question_list, }
    return HttpResponse(template.render(context, request))