快捷方式:render()


快捷方式:render()

常见的习惯是载入一个模板,填充一个context然后返回一个含有模板渲染结果的HttpResponse对象。

Django 为此提供一个快捷方式,下面是重写后的index()视图 

polls/views.py
from django.shortcuts import render

from .models import Question


def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')
    context = {'latest_question_list': latest_question_list}
    return render(request, 'polls/index.html', context)

主意,一旦我们在所有的视图上都应用这个快捷函数,我们将不再需要导入 loader、RequestContext和HttpResponse (如果你没有改变先前的detail、results和 vote方法,你将需要在导入中保留HttpResponse)。

render() 函数将请求对象作为它第一个参数,模板的名字作为它的第2个参数,一个字典作为它可选的第三个参数

它返回一个HttpResponse对象,含有用给定的context 渲染后的模板。

原文地址:https://www.cnblogs.com/hzcya1995/p/13349130.html