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是上图红框部分

相关推荐
asdzx672 分钟前
使用 Python 比较 PDF 文件差异(简单方法)
python·pdf·文档比较
穿过锁扣的风7 分钟前
【完整带注释版】图像直方图绘制教程(OpenCV+Matplotlib)
笔记·python·opencv
zyq99101_19 分钟前
蓝桥杯刷题算法实战解析
数据结构·python·算法·蓝桥杯
好家伙VCC13 分钟前
# 发散创新:用 Rust构建高并发虚拟世界引擎核心模块在当今游戏开发与元宇宙构建中,**虚拟世界的性能瓶颈往往不是图形渲染,而是底
java·开发语言·python·rust·图形渲染
for_syq20 分钟前
trace抓取工具
android·python
Pyeako29 分钟前
基于Qt和PaddleOCR的工业视觉识别报警系统开发
人工智能·python·深度学习·数码相机·opencv·ocr·pyqt5
搜佛说42 分钟前
RocksDB, SQLite, TDengine Edge, LiteDB与sfsDb选型
物联网·edge·sqlite·边缘计算·时序数据库·iot·tdengine
未知鱼1 小时前
Python安全开发asyncio(异步IO与高并发)
python·安全·网络安全·github
代码探秘者1 小时前
【大模型应用】5.深入理解向量数据库
java·数据库·后端·python·spring·面试
小鸡吃米…1 小时前
Python 网络爬虫
开发语言·爬虫·python