模板的正确用法,之前都用白瞎了

https://docs.djangoproject.com/zh-hans/2.1/intro/tutorial03/#write-views-that-actually-do-something

将下面的代码输入到刚刚创建的模板文件中:

polls/templates/polls/index.html

{% 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 %}

然后,让我们更新一下 polls/views.py 里的 index 视图来使用模板:

polls/views.py

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/index.html 模板文件,并且向它传递一个上下文(context)。这个上下文是一个字典,它将模板内的变量映射为 Python 对象。

猜你喜欢

转载自blog.csdn.net/qq_27361945/article/details/83016783