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

相关推荐
Aision_4 分钟前
从工具调用到 MCP、Skill完整学习记录
java·python·gpt·学习·langchain·prompt·agi
2301_809204705 小时前
JavaScript中严格模式use-strict对引擎解析的辅助.txt
jvm·数据库·python
zjy277776 小时前
mysql如何选择合适的索引类型_mysql索引设计实战
jvm·数据库·python
Aaswk6 小时前
Java Lambda 表达式与流处理
java·开发语言·python
万邦科技Lafite6 小时前
京东item_get接口实战案例:实时商品价格监控全流程解析
java·开发语言·数据库·python·开放api·淘宝开放平台
Cyber4K7 小时前
【Python专项】进阶语法-系统资源监控与数据采集(1)
开发语言·python·php
苍煜8 小时前
Java开发IO零基础吃透:BIO、NIO、同步异步、阻塞非阻塞
java·python·nio
AllData公司负责人9 小时前
通过Postgresql同步到Doris,全视角演示AllData数据中台核心功能效果,涵盖:数据入湖仓,数据同步,数据处理,数据服务,BI可视化驾驶舱
java·大数据·数据库·数据仓库·人工智能·python·postgresql
Flittly10 小时前
【LangGraph新手村系列】(5)时间旅行:浏览历史、分叉时间线与修改过去
python·langchain
2301_7820404511 小时前
CSS Flex布局中如何实现导航栏与Logo的左右分布_利用justify-content- space-between
jvm·数据库·python