Django有大量所谓的快捷键函数,使使用Django开发变得更加容易。这些快捷键是跨越模型、视图、模板范式中许多不同层次的辅助函数。render()函数就是这样一个函数。render()的目的是返回一个HttpResponse,其内容是用传递的参数调用render_to_string()的结果来填充。我们在Register Django Templates教程中看到了如何使用render_to_string()函数。现在我们来看看如何使用这个更容易使用的render()函数。
render()函数
在使用render()函数之前,我们先看一下它的源代码。
def render(request, template_name, context=None, content_type=None, status=None, using=None):
"""
Return a HttpResponse whose content is filled with the result of calling
django.template.loader.render_to_string() with the passed arguments.
"""
content = loader.render_to_string(template_name, context, request, using=using)
return HttpResponse(content, content_type, status)
render()函数有两个强制性的参数,你在调用该函数时必须传递给它。这两个参数是request和template_name。可选参数包括context、content_type、status和using。
要渲染的模板
记得我们在goals/templates/goals目录下有一个简单的模板,如下图所示。在模板文件夹中重复应用程序的名称被认为是一个最佳做法,因为如果项目中有许多应用程序有类似的名称,那么Django将不知道哪个模板在哪个应用程序下面。这是因为Django在运行时将所有模板文件夹合并为一个大的模板文件夹。
C:\python\djangoprojects\myproject\goals\templates\goals\goal.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>The Template Works!</h1>
</body>
</html>
在一个视图函数中调用render()
我们已经看到了在Django中渲染模板的长方法,那就是使用render_to_string()函数将模板转换为一个包含模板HTML的字符串。然后,这个字符串会在一个HttpResponse中被送回给用户。render()函数让我们把这个两步的过程,在一步之内完成。render()函数在下面的views.py文件中被强调。
C:\python\djangoprojects\myproject\goals\views.py
from django.shortcuts import redirect, render
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
# dictionary data store
goals = {
'daily': 'Learn Something New',
'weekly': 'Take a day off',
'monthly': 'Complete a creative course'
}
def homepage(request):
goal_list = '<html><body><ul>'
for goal in goals.keys():
href = reverse('namedurl', args=[goal])
goal_list += f'<li><a href="{href}">{goal}</a></li>'
goal_list += '</ul></body></html>'
return HttpResponse(goal_list)
def goals_by_int_timeframe(request, timeframe):
timeframes = list(goals.keys())
redirect_to = timeframes[timeframe - 1]
named_redirect = reverse('namedurl', args=[redirect_to])
return HttpResponseRedirect(named_redirect)
def goals_by_timeframe(request, timeframe):
goal = goals[timeframe]
return render(request, 'goals/goal.html')
注意,我们确实传递了request和template_name这两个必要参数。如果我们访问http://127.0.0.1:8000/goals/daily,它确实可以工作。

