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

相关推荐
学不好python的小猫11 分钟前
7-4 身份证号处理
开发语言·python·算法
MAOX78929 分钟前
基于python的web系统界面登录
前端·python
一颗红心丶1 小时前
Windows系统上离线部署Python运行飞桨(PaddlePaddle) OCR服务
windows·python·paddlepaddle
我爱音乐yyy1 小时前
pythonday50
pytorch·python·深度学习
white.tie1 小时前
一个手机请求头的随机库
开发语言·javascript·python
Mikhail_G2 小时前
Python初学者入门指南
大数据·运维·开发语言·python·数据分析
和我乘风破浪2 小时前
iOS自动化录屏在Chrome浏览器打不开处理方法
python·测试
站大爷IP2 小时前
当生成器遇上异步IO:Python并发编程的十大实战兵法
python
大明者省3 小时前
pycharm2020.2版本给项目选择了虚拟环境解释器,项目文件都运行正常,为什么terminal文件路径的前面没有虚拟解释器的名称
开发语言·python
love530love3 小时前
MSYS2 环境下 Python 开发配置(结合 PyCharm)使用笔记
人工智能·windows·笔记·python·pycharm·virtualenv·uv