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')
相关推荐
godspeed_lucip几秒前
LLM和Agent——专题3: Agentic Workflow 入门(2)
网络·人工智能·python
mingshili2 分钟前
[Python] Python中自带模块级的单例模式-不需要定义单例类
python·单例模式
alphaTao23 分钟前
LeetCode 每日一题 2026/5/18-2026/5/24
python·leetcode
徐安安_ye124 分钟前
FlashAttention学习路线:从调API到写算子,你该走哪条路
python·学习
IT策士42 分钟前
Django 从 0 到 1 打造完整电商平台:商品搜索
后端·python·django
茉莉玫瑰花茶1 小时前
LangGraph 持久化(Persistence)[ 2 ]
开发语言·python·ai·langgraph
有味道的男人1 小时前
AI 对接 1688 图搜接口|Open Claw 以图搜货实战
开发语言·python
MediaTea1 小时前
DL:Transformer 的基本原理与 PyTorch 实现
人工智能·pytorch·python·深度学习·transformer
wuxinyan1231 小时前
工业级大模型学习之路024:LangChain零基础入门教程(第七篇):RAG 系统评估、全链路调优
人工智能·python·学习·langchain
Kingairy1 小时前
Python简单算法题
开发语言·python