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')
相关推荐
不考研当牛马2 分钟前
Django 框架 深度学习 第二课程
后端·python·django
Dust-Chasing9 分钟前
Claude Code源码剖析 - ShellTool与真实动作
人工智能·python·ai
仙俊红18 分钟前
Java JUC:CompletableFuture 详解,多个任务并行执行并等待全部完成
java·python·spring
学习3人组21 分钟前
Python 评论朴素贝叶斯文本情感分析示例
人工智能·python·机器学习
用户3379225456825 分钟前
A2A Python SDK 源码架构解读:一个请求是如何被处理的
python
2401_8856651925 分钟前
从零搭建卷积神经网络:基于PyTorch实现MNIST手写数字分类
pytorch·python·神经网络·算法·机器学习·分类·cnn
SilentSamsara29 分钟前
MLflow 实验追踪与模型注册:从实验到生产的可复现工作流
开发语言·人工智能·pytorch·python·青少年编程
曲幽30 分钟前
写爬虫时用了代理还被封?Python 代理的那些隐藏坑,我替你踩明白了
python·http·https·proxy·socks·requests·socks5·proxies
装不满的克莱因瓶31 分钟前
掌握多头自注意力机制(Multi-Head Self-Attention)——Transformer 强大表达能力的核心来源
人工智能·python·深度学习·数学·ai·transformer
下班走回家37 分钟前
RAG 技术的进化:从朴素检索到 Agentic RAG
开发语言·人工智能·python