python-0007-django模版

介绍

模版是对js,html等资源的封装

新建

在项目路径下新建模版文件夹templates(可以为其他名称),要是想细分业务的话,还可以在templates路径下继续建文件夹。如下图:

注册模版

在项目的settings找到TEMPLATES,在DIRS中添加刚刚的模版,如下:

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',
            ],
        },
    },
]

在视图返回模版

使用render进行渲染,如下:

python 复制代码
from django.shortcuts import render

# Create your views here.
from django.http import HttpRequest, HttpResponse


def index(request):
    context = {
        "name": "西游记"
    }
    return render(request,'book/index.html', context=context)
    pass

render源码如下:

python 复制代码
def render(request, template_name, context=None, content_type=None, status=None, using=None):

其中:request是HttpRequest对象,template_name是模版的路径,context是使用的数据

静态资源

在DEBUG = True的条件下

红框是静态路由,使用http://ip:port/static/girl.png即可访问

其中:/static是上图红框部分

相关推荐
leo_messi944 分钟前
2026版商城项目(三)-- ES+认证服务
后端·python·django
搜佛说9 分钟前
比SQLite更快,比InfluxDB更轻:sfsDb的降维打击
jvm·数据库·物联网·架构·sqlite·边缘计算·iot
NPE~21 分钟前
[App逆向]环境搭建下篇 — — 逆向源码+hook实战
android·javascript·python·教程·逆向·hook·逆向分析
财经资讯数据_灵砚智能33 分钟前
基于全球经济类多源新闻的NLP情感分析与数据可视化(夜间-次晨)2026年4月7日
人工智能·python·信息可视化·自然语言处理·ai编程
deephub38 分钟前
向量数据库对比:Pinecone、Chroma、Weaviate 的架构与适用场景
人工智能·python·大语言模型·embedding·向量检索
星马梦缘42 分钟前
强化学习实战5——BaseLine3使用自定义环境训练【输入状态向量】
pytorch·python·jupyter·强化学习·baseline3·gymnasium
阿捞21 小时前
JVM排查工具单
java·jvm·python
weixin_423533991 小时前
【ubuntu20.04安装nvidia显卡驱动及pytorch】
python
I疯子1 小时前
2026-04-08 打卡第 5 天
开发语言·windows·python
C+++Python1 小时前
Python MCP Server 最简实现
开发语言·python