python-0007-django模版

介绍

模版是对js,html等资源的封装

新建

在项目路径下新建模版文件夹templates(可以为其他名称),要是想细分业务的话,还可以在templates路径下继续建文件夹。如下图:
在这里插入图片描述

注册模版

在项目的settings找到TEMPLATES,在DIRS中添加刚刚的模版,如下:

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进行渲染,如下:

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源码如下:

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

相关推荐

  1. python-0004-django站点

    2024-03-14 09:12:02       20 阅读
  2. python-0006-django路由

    2024-03-14 09:12:02       25 阅读
  3. python-0008-修改django数据库为mysql

    2024-03-14 09:12:02       20 阅读
  4. python-0009-django对数据的增删改

    2024-03-14 09:12:02       21 阅读
  5. python-0001-安装虚拟环境

    2024-03-14 09:12:02       23 阅读
  6. Python Django

    2024-03-14 09:12:02       31 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-03-14 09:12:02       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-03-14 09:12:02       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-03-14 09:12:02       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-03-14 09:12:02       20 阅读

热门阅读

  1. 鸿蒙 线程模型

    2024-03-14 09:12:02       18 阅读
  2. CMake在linux上的使用

    2024-03-14 09:12:02       22 阅读
  3. 什么是MVC

    2024-03-14 09:12:02       17 阅读
  4. InnoDB对MVCC的实现

    2024-03-14 09:12:02       19 阅读
  5. 事实分布式与价值集中式

    2024-03-14 09:12:02       20 阅读
  6. 并发编程2-掌握C#线程库的使用

    2024-03-14 09:12:02       19 阅读
  7. LeetCode344 -反转字符串

    2024-03-14 09:12:02       18 阅读