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

相关推荐
buhuizhiyuci24 分钟前
【python篇——一周速通python语法】python的基础语法操作
开发语言·python
盼小辉丶1 小时前
OpenCV-Python实战——分析与加速OpenCV应用程序
python·神经网络·opencv·计算机视觉
buhuizhiyuci1 小时前
【python篇——一周速通python语法】python的条件语句和循环语句
开发语言·python
学AI不秃头1 小时前
官方要 16GB,实测 4-bit 压到 2.9GB:把 LocateAnything-3B 搬上 8GB Jetson
python·深度学习·机器学习·计算机视觉·机器人
Exclusive_Cat2 小时前
FastAPI热重载失效?降级uvicorn解决
python·fastapi
m0_617493943 小时前
Python OpenCV 孔洞检测与缺陷分析详解与实战
开发语言·python·opencv
闻道且行之12 小时前
TurboOCR:基于PP-OCRv6的极速Windows离线OCR工具,深度解析3.4GB依赖背后的技术架构
c++·人工智能·python·qt·机器学习·ocr
许彰午13 小时前
95_Python内存管理与垃圾回收
开发语言·python
骄阳如火14 小时前
Python 性能深度剖析:从“被诟病的慢”到“Rust 重塑”的拐点
python