【问题标题】:Django Tutorials part 3: Error while creating view and templateDjango 教程第 3 部分:创建视图和模板时出错
【发布时间】:2017-11-15 14:34:28
【问题描述】:

我开始学习 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/ *未定义全局名称“latest_question_list”**

【问题讨论】:

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


    【解决方案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))
    

    【讨论】:

      【解决方案2】:

      试试这个:

      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)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-11-13
        • 2012-11-13
        • 2018-11-02
        • 2016-12-24
        • 2017-08-21
        • 2015-10-10
        • 2012-11-30
        • 2014-04-06
        相关资源
        最近更新 更多