Django模板语法和请求

1、在django关于模板文件加载顺序

创建的django项目下会有一个seeetings.py的文件

  • 如果在seeetings.py 中加了 os.path.join(BASE_DIR,'templates'),如果是pycharm创建的django项目会加上,就会默认先去根目录找templates目录下的html文件,之后在去注册的app中找,按照app注册的顺序;
  • 如果在seeetings.py中没有 os.path.join(BASE_DIR,'templates') 这个配置, 就不会去根目录寻找,只会去注册的app中找templates目录,按照app注册顺序。

2、静态文件

静态文件包括:

  • 图片
  • js
  • css
  • 插件

都会当做静态文件处理。

需要在app目录下创建static目录,

bash 复制代码
app01
    |---static
            |---js
            |---css
            |---img
            |---plugins

比如在urls.py 有路径

python 复制代码
from django.urls import path

from app01 import views
urlpatterns = [
    path('index/', views.index),

]

在views.py 中增加函数

python 复制代码
from django.shortcuts import render, HttpResponse
# Create your views here.

def index(req):
    return render(req,"index.html")

在app 目录下的templates目录创建index.html的文件

在index.html 文件中引入静态文件

django引入静态文件也可以像flask一样,写上静态文件的路径,但是django推荐使用下面这种,先把static目录加载进来,后面再引用,也就是相当于使用相对路径一样。静态文件的目录static是可以设置的,万一需要修改的时候只要改{% load static %}这个就全部替换,而不需要一个一个连接去修改

html 复制代码
{% load static %}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="{% static 'plugins/bootstrap-3.4.1/css/bootstrap.css' %}">
</head>
<body>
<h1>用户列表</h1>
<img src="{% static 'img/1.png' %}" />

<input type="text" class="btn btn-primary" value="新建"/>
<script src="{% static 'js/jquery-3.7.0.min.js' %}"></script>
<script src="{% static 'plugins/bootstrap-3.4.1/js/bootstrap.js' %}"></script>
</body>
</html>

启动django 项目访问页面 访问:http://127.0.0.1:8000/index/

图片可以读取到

3、模板语法

本质上:在HTML中写一些占位符,由数据对这些占位符进行替换和处理。

  • 通过函数值传到html中,在html中显示单个字段
    在返回的时候通过字典传值,{key:变量名}, 在html中通过{{ }}这个占位符,在中间写上key 值
  • 循环展示
    通过 {% for item in n2 %}
    中间写标签
    {% endfor %}
    这样就可以根据item值的个数来循环创建标签
  • 如果是列表或是字典,通过点来获取值
  • 支持根据条件显示
    值为True就会执行该条件下的标签
    模板语法的流程:

案例:

1、在urls.py 加上路径

python 复制代码
from django.urls import path

from app01 import views
urlpatterns = [
    path('tpl/', views.tpl),

]

2、在views.py 中增加函数

python 复制代码
from django.shortcuts import render, HttpResponse
import requests
# Create your views here.

def tpl(req):
    headers = {
        "Content-Type": "application/json;charset=UTF-8",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
    }
    res = requests.get("http://www.chinaunicom.com.cn/api/article/NewsByIndex/2/2023/06/news",headers=headers)
    data_list = res.json()
    print(data_list)

    return render(req,"tpl.html",{"new_list":data_list})

3、在templates增加一个tpl.html

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
   <h1>新闻中心</h1>
   <ul>
       {% for item in new_list %}
       <li>{{item.news_title}}</li>
       {% endfor %}
   </ul>
</body>
</html>

http://127.0.0.1:8000/tpl/ 效果:

4、请求和响应

在views.py 的函数中传入的request参数是一个对象,封装了用户发送过来的所有请求相关数据

python 复制代码
def dosomething(request):
    #request是一个对象,封装了用户发送过来的所有请求相关数据
    #1、获取请求方式,GET/POST
    print(request.method)

    #2、在URL上传递值 /something/?n1=123&n2=999
    print(request.GET)

    #3、在请求体中传递数据
    print(request.POST)

    #4、响应 HttpResponse("返回内容"),内容字符串内容返回给请求者。
    #return HttpResponse("返回内容")

    #5、响应读取HTML的内容 + 渲染(替换)   ->字符串,返回给用户浏览器
    #return render(request,'something.html',{"title":"你好"})
    
    #6、响应,让浏览器重定向到其他的页面,需要导入redirect模块
    return redirect("https://www.baidu.com")

重定向的时候,浏览器向Django发起请求,Django把重定向的地址返回给浏览器,然后浏览器在自己去请求重定向后的网站

相关推荐
西柚研究生12345619 分钟前
论文分析17:YOLOv11_UAVNet:无人机航拍图像专用目标检测算法
人工智能·python·深度学习·算法·目标检测
沧海一笑-dj1 小时前
【Python】Python学习笔记-初识 Python
python·python安装·python解释器
打工仔折腾 AI1 小时前
FastAPI 从本机到生产服务器:Nginx+Gunicorn+Uvicorn 完整部署实录
人工智能·后端·python·nginx·fastapi·gunicorn
hanchenxing1 小时前
AI 数据管道重构:从函数堆到链式管道的可读性实践
python
hhzz1 小时前
【OpenCV 入门到精通 10】视频分析与光流跟踪:背景减除与运动检测
人工智能·python·opencv·性能优化
蓝胖的四次元口袋1 小时前
Python基础语法入门
python
Patrick在香港2 小时前
Python 抓 0.91 GB 香港法例:Agent 的进度该写进磁盘,不是写进上下文
爬虫·python·api·claude·香港
ClinicTech2 小时前
实验室洗瓶机的清洗系统架构与自动化控制解析
java·python
洋洋不叫杨杨2 小时前
Codex 实战:用 AI 写运维脚本
大数据·python
高级程序源2 小时前
django大学生创新创业项目管理系统94923-计算机课程设计、毕业设计
javascript·vue.js·spring boot·后端·python·django·课程设计