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

相关推荐
张子夜 iiii4 小时前
(0️⃣基础)程序控制语句(初学者)(第3天)
人工智能·python
码农派大星。7 小时前
Selenium在Pyhton应用
python·selenium·测试工具
day>day>up8 小时前
django uwsgi启动报错failed to get the Python codec of the filesystem encoding
后端·python·django
Shun_Tianyou8 小时前
Python Day25 进程与网络编程
开发语言·网络·数据结构·python·算法
都叫我大帅哥9 小时前
LangGraph条件判断:让AI工作流"聪明"起来
python·langchain
编程研究坊9 小时前
Neo4j APOC插件安装教程
数据库·人工智能·python·neo4j
咩?10 小时前
SEABORN库函数(第十八节课内容总结)
开发语言·python·matplotlib·seaborn
万粉变现经纪人10 小时前
如何解决pip安装报错ModuleNotFoundError: No module named ‘transformers’问题
人工智能·python·beautifulsoup·pandas·scikit-learn·pip·ipython
浊酒南街10 小时前
Pytorch基础入门1
pytorch·python
仪器科学与传感技术博士11 小时前
Matplotlib库:Python数据可视化的基石,发现它的美
开发语言·人工智能·python·算法·信息可视化·matplotlib·图表可视化