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

相关推荐
ynchyong22 分钟前
SQLAlchemy 更新操作:values() 与 ordered_values() 的隐藏差异
python·sqlalchemy·update·values·ordered_values
statistican_ABin36 分钟前
中国互联网与数字生活分析报告—基于1990-2023年世界银行互联网数据的多维度分析
python
“AI国潮设计-小江”1 小时前
【Python/SDXL实战】潮汕国潮IP视觉落地:普宁美食猫IP & 创意甜品设计(附ComfyUI工作流思路)
开发语言·人工智能·python·prompt·aigc
Allen_LVyingbo1 小时前
医疗人工智能项目全生命周期管理系统:监管知识建模、工程实现与实证评估(下)
大数据·数据库·人工智能·python·自然语言处理·自动化
wuhuhuan1 小时前
Case Generator 平台升级
python·测试工具·自动化
RobinDevNotes2 小时前
用 Profile 揪出大模型训练性能瓶颈
python·性能优化
李航19832 小时前
用 DeepDraw 几何引擎开发建筑设计软件(六):创建画线工具
python·软件构建
AI 编程助手GPT2 小时前
Python 备份 SQLite:为什么复制了 .db,恢复后还是少数据?
人工智能·python·ai·chatgpt
狗都不学爬虫_2 小时前
AI逆向 - 天御无感点击验证(补+纯)
爬虫·python·网络爬虫
529宝宝起名网2 小时前
用 Python 开发历史名字查询与起名灵感工具:从古籍人物数据库到名字文化故事生成
开发语言·前端·python