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')
相关推荐
ikun_文2 小时前
Django框架路由Router的使用
python·pycharm·django
IvanCodes2 小时前
Python 基础语法(二):字符串与常用操作
python
昭昭日月明2 小时前
LangChain 生态:从链到代理,开发者需要掌握的三大核心
python·langchain·agent
Csvn3 小时前
🐍 Day 8:面向对象编程
后端·python
程序员天天困3 小时前
向量检索不准怎么办:混合检索与 Rerank 重排序召回优化实战
后端·python·ai编程
alphaTao4 小时前
LeetCode 每日一题 2026/8/24-2026/8/30
python·算法·leetcode
苏灿烤鱼4 小时前
当 AI Agent 遇见真实科学环境:深度拆解 Scientific Agent Skills,把"聊天机器人"变成"AI 科学家"
python·开源·agent
张文君4 小时前
ubuntu26.04坏道坏块分区隔离急速版260831-V0.12
linux·python
lupai15 小时前
手机在网状态接口实测效果与质量评估
大数据·python·智能手机·api接口
荷蒲16 小时前
【小白量化Qbuddy】用AI设计miniQMT指标公式计算量化平台
人工智能·python·机器人