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')
相关推荐
overmind3 分钟前
oeasy Python 114 在列表指定位置插入insert
开发语言·python
喵手16 分钟前
Python爬虫实战:监控型爬虫实战 - 从结构检测到智能告警的完整方案(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·csv导出·监控型爬虫实战·从结构哦检测到智能告警
深蓝电商API19 分钟前
爬虫中 Cookie 池维护与自动刷新
爬虫·python
蜡笔羊驼33 分钟前
LALIC环境安装过程
开发语言·python·深度学习
Starry_hello world34 分钟前
Python(1)
python
codeJinger38 分钟前
【Python】基础知识
开发语言·python
一切顺势而行1 小时前
python 文件目录操作
java·前端·python
woshikejiaih2 小时前
2026年阅读软件Top5避坑攻略:告别卡顿闪退提升沉浸感
人工智能·python
007张三丰2 小时前
2026马年开年寄语
python·ai工具·祝福·新技术·新年·马年
zlpzpl2 小时前
Java总结进阶之路 (基础二 )
java·开发语言·python