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

相关推荐
Victory_orsh15 小时前
“自然搞懂”深度学习系列(基于Pytorch架构)——01初入茅庐
人工智能·pytorch·python·深度学习·算法·机器学习
大模型真好玩15 小时前
LangGraph实战项目:从零手搓DeepResearch(二)——DeepResearch架构设计与实现
人工智能·python·langchain
濑户川15 小时前
基于DDGS实现图片搜索,文本搜索,新闻搜索
人工智能·爬虫·python
深蓝电商API16 小时前
快速上手 Scrapy:5 分钟创建一个可扩展的爬虫项目
爬虫·python·scrapy
Q_Q51100828516 小时前
python+uniapp基于微信小程序的心理咨询信息系统
spring boot·python·微信小程序·django·flask·uni-app·node.js
Lucky_Turtle16 小时前
【Java Xml】dom4j写入XML
xml·java·python
StarPrayers.17 小时前
用 PyTorch 搭建 CIFAR10 线性分类器:从数据加载到模型推理全流程解析
人工智能·pytorch·python
程序员杰哥17 小时前
UI自动化测试实战:从入门到精通
自动化测试·软件测试·python·selenium·测试工具·ui·职场和发展
SunnyRivers17 小时前
通俗易懂理解python yield
python
mortimer17 小时前
Python 进阶:彻底理解类属性、类方法与静态方法
后端·python