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

相关推荐
lifloveyou8 小时前
table接口结构
python
Warson_L10 小时前
class 扩展
python
前端与小赵10 小时前
Python 数据结构陷阱与复数运算优化:列表、元组、字典成员操作辨析及 NumPy 高效实践
python
天天进步201511 小时前
Python全栈项目--基于深度学习的视频目标跟踪系统
python·深度学习·音视频
天天进步201511 小时前
Python全栈项目--Python自动化运维工具开发
运维·python·自动化
(●—●)橘子……11 小时前
力扣第503场周赛练习理解
python·学习·算法·leetcode·职场和发展·周赛
爱吃羊的老虎12 小时前
【JAVA】python转java:Spring Boot 入门
java·spring boot·python
小桥流水---人工智能12 小时前
【已解决】ImportError: cannot import name ‘AdamW‘ from ‘transformers.optimization‘
python
芝麻开门GEO12 小时前
泰安GEO优化服务,真的能提升效果吗?
人工智能·python
颜酱12 小时前
选读:工业级调用 LangChain:从 Demo 到企业级应用
python