博客五部曲之一 - 简单博客


1213 浏览 5 years, 4 months

14 Django模板

版权声明: 转载请注明出处 http://www.codingsoho.com/

Django的优势之一是它的模板,它使得网页更灵活,更高效。

上面的例子了,为了简化演示,我们用了内嵌的HTML代码片段,这节我们开始介绍如果在Django中使用模板。

首先,我们在设置文件里设置模板相关配置。添加DIRS,这是模板搜索路径

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR,'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

修改post_list函数,用render函数渲染页面。第二个参数为模板文件,第三个是context,会在后面介绍。

def post_list(request):
    # return HttpResponse("<h1>List</h1>")     
    return render(request, "index.html", {})   

在BASE_DIR目录下创建templates目录,并在templates里创建第一个模板文件index.html

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <h1>Templates is working!</h1>
</body>
</html>

继续访问http://127.0.0.1:8000/posts/,显示Templates is working!

下面介绍一下模板路径的搜索规则:
- 如果不设置DIRS,将会报错 TemplateDoesNotExist,查看报错日志,它会从默认的django的内置应用admin和auth里去搜索

Template-loader postmortem
Django tried loading these templates, in this order:
Using engine django:
   django.template.loaders.app_directories.Loader: E:\Computer\virtualenv\iblog\env\lib\site-packages\django\contrib\admin\templates\index.html (Source does not exist)
   django.template.loaders.app_directories.Loader: E:\Computer\virtualenv\iblog\env\lib\site-packages\django\contrib\auth\templates\index.html (Source does not exist)
  • 如果DIRS设置了,但是模板文件index1.html不存在,可以看到下面报错。Django首先从用户应用内去搜寻,然后搜索内嵌应用。
Template-loader postmortem
Django tried loading these templates, in this order:
Using engine django:
   django.template.loaders.filesystem.Loader: E:\Computer\virtualenv\iblog\csblog\templates\index1.html (Source does not exist)
   django.template.loaders.app_directories.Loader: E:\Computer\virtualenv\iblog\env\lib\site-packages\django\contrib\admin\templates\index1.html (Source does not exist)
   django.template.loaders.app_directories.Loader: E:\Computer\virtualenv\iblog\env\lib\site-packages\django\contrib\auth\templates\index1.html (Source does not exist)