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

相关推荐
LuckyLay34 分钟前
1.1.2 运算符与表达式——AI教你学Django
python·django
学不会就看35 分钟前
Django--01基本请求与响应流程
后端·python·django
nbsaas-boot6 小时前
Java 正则表达式白皮书:语法详解、工程实践与常用表达式库
开发语言·python·mysql
仗剑_走天涯6 小时前
基于pytorch.nn模块实现线性模型
人工智能·pytorch·python·深度学习
chao_7896 小时前
二分查找篇——搜索旋转排序数组【LeetCode】两次二分查找
开发语言·数据结构·python·算法·leetcode
chao_78910 小时前
二分查找篇——搜索旋转排序数组【LeetCode】一次二分查找
数据结构·python·算法·leetcode·二分查找
烛阴10 小时前
Python装饰器解除:如何让被装饰的函数重获自由?
前端·python
noravinsc11 小时前
django 一个表中包括id和parentid,如何通过parentid找到全部父爷id
python·django·sqlite
ajassi200011 小时前
开源 python 应用 开发(三)python语法介绍
linux·python·开源·自动化
沉默媛11 小时前
如何安装python以及jupyter notebook
开发语言·python·jupyter