Django笔记(二):模板templates

Django模板层是为动态生成html服务的,非本文重点。前后端分离的设计更为常见,尽量少的涉及Django模板层内容。本文记录Django如何找到一个html文件。

模板文件

在创建一个Django项目project后,目录下会生成一个同名目录和manage.py。创建一个app,并为app编写一个视图,如:

python 复制代码
from django.shortcuts import render

# Create your views here.
def index(request):
    return render(request, 'index.html')

当通过路由访问index视图函数时,会返回index.html文件,这个文件从何处获取?

搜寻路径

每创建一个app,都需要在全局配置文件(/project/project/settings.py)中注册,Django会按照注册顺序,依次寻找各app目录下templates目录下的index.html文件。如果各app中文件名称相同,则返回注册靠前的app下的html文件。

一个解决重名的方式是创建html文件时,添加app名作为前缀,如"app1_index.html"。另一种方式,可以将html文件统一管理,进行全局配置。

模板配置

在project目录下创建templates(名称随意,不建议更改)文件夹(与manage.py同级),并进行全局配置/project/project/settings.py: (os module需要导入)

python 复制代码
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',
            ],
        },
    },
]

添加TEMPLATES的DIRS项,之后Django会在根目录下的templates寻找。

为了解决重名问题,可在templates下为各app建立目录,如上述index.hltml可放在/project/templates/app1/index.hltml,当app2有index时,可放在/project/templates/app2/index.hltml。

app1中index视图,可更改为:

python 复制代码
from django.shortcuts import render

# Create your views here.
def index(request):
    return render(request, '1/index.html')
相关推荐
电商API&Tina14 小时前
电商数据采集API接口||合规优先、稳定高效、数据精准
java·javascript·数据库·python·json
玲娜贝儿--努力学习买大鸡腿版14 小时前
hot 100 刷题记录(1)
数据结构·python·算法
兮℡檬,14 小时前
答题卡识别判卷
开发语言·python·计算机视觉
阆遤15 小时前
利用TRAE对nanobot进行安全分析并优化
python·安全·ai·trae·nanobot
雕刻刀15 小时前
ERROR: Failed to build ‘natten‘ when getting requirements to build wheel
开发语言·python
何双新15 小时前
Odoo 技术演进全解析:从 Widget 到 Owl,从 Old API 到声明式 ORM
python
山川行16 小时前
关于《项目C语言》专栏的总结
c语言·开发语言·数据结构·vscode·python·算法·visual studio code
星辰徐哥16 小时前
C语言游戏开发:Pygame、SDL、OpenGL深度解析
c语言·python·pygame
xcLeigh16 小时前
Python入门:Python3基础练习题详解,从入门到熟练的 25 个实例(六)
开发语言·python·教程·python3·练习题
不懒不懒16 小时前
安装python3.9.7和pycharm-community-2022.3.2.exe以及linux
linux·ide·python·pycharm