Django(part11)--MTV模式及模板

学习笔记,仅供参考




Django的框架模式


MTV模式


MTV模式MTV代表Model-Template-View(模型一模板一视图)模式。这种模式用于应用程序的分层开发

  • 作用
    • 降低模块的耦合度
  • MTV
    • M–模型层(Model)负责与数据库交互;
    • T–模板层(Template)负责生成 HTML,呈现内容到浏览器;
    • V–视图层(View)负责处理业务逻辑,负责接收请求、获取数据,返回结果;

  • 图示


模板Template


什么是模板


  • 模板是HTML页面,可以根据视图中传递的数据填充值相应的页面元素。
  • 模板层提供了一个对设计者友好的语法用于渲染向用户呈现的信息。

模板的配置


创建一个新的项目

为了方便演示,我们创建一个新项目mywebsite2:


在项目下创建一个模板文件夹templates(这个文件夹用于存放模板文件):


sittings.py文件

在settings.py中有一个TEMPLATES列表,我们可以在这个列表中对模板进行设定。比如:

BACKEND:指定模板的引擎
DIRS:指定保存模板的目录们
APP_DIRS:是否要在应用中搜索模板的版本
OPTIONS:有关模板的选项们

我们看一下settings.py

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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',
            ],
        },
    },
]

现在,我们开始配置模板!


添加路径

首先,我们把模板文件夹的路径添加到DIRS中:

'DIRS': [os.path.join(BASE_DIR, 'templates')],

其中BASE_DIR是全局变量,是当前项目的绝对路径。


编写模板

首先,我们在templates文件夹下,创建模板文件page1.html:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Template</title>
</head>
<body>
	<h1>这是我的第一个模板</h1>
	
</body>
</html>

我们再创建一个views.py文件:

from django.http import HttpResponse

def page1_template(request):
    
    return HttpResponse("OK!")

在urls.py文件中,添加一个路由:

from django.contrib import admin
from django.urls import path
from django.urls import re_path
from . import views

urlpatterns = [
    path('admin/', admin.site.urls),
    re_path(r'page1_template/$', views.page1_template),
]

这时,我们还没有加载模板,只是编写好了模板文件。


加载模板

  • 第一种加载模板的方式

在视图函数中,通过loader方法获取模板,再通过HttpResponse进行相响应。

views.py

from django.http import HttpResponse
#导入loader
from django.template import loader

def page1_template(request):
    #通过loader加载模板
    t = loader.get_template("page1.html")
    #将t转换为字符串
    html = t.render()
    #响应
    return HttpResponse(html)

向http://127.0.0.1:8000/page1_template/发起请求:

  • 第二种加载模板的方式

使用render直接加载并响应模板

views.py:

def test_page1_template(request):
    from django.shortcuts import render
    return render(request, "page1.html")

注意,这里的render方法,返回的依然是HttpResponse对象。

urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    re_path(r'test_page1_template/$', views.test_page1_template),
]

向http://127.0.0.1:8000/test_page1_template/发起请求:


模板的传参


模板传参是指把数据形成字典,传参给模板,由模板渲染来填充数据


编写第二个模板

为了方便之后的学习,我们再写一个模板文件page2.html:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Template</title>
</head>
<body>
	<h1>这是我的第2个模板</h1>
   <h2> 姓名:{{name}}</h2>
   <h2>年龄:{{age}}</h2>
    <!--模板填入数据的格式{{变量名}}-->
	
</body>
</html>

urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    re_path(r'test_page1_template/$', views.test_page1_template),
    re_path(r'page2_template/$', views.page2_template)
]

使用loader加载模板并传参

views.py

def page2_template(request):
    t = loader.get_template("page2.html")
    html = t.render({"name":"Huang",
                     "age":10})
    return HttpResponse(html)

注意,render方法中只接受字典形式的数据。

向http://127.0.0.1:8000/page2_template/发起请求:


使用render直接加载模板并传参

views.py

def page2_template(request):
    d = {"name":"Bai","age":11}  
    return render(request, "page2.html", d)

再次向http://127.0.0.1:8000/page2_template/发起请求:


模板的变量


  • 在模板中使用变量语法
{{变量名}}

后端中,必须将变量封装到字典中才允许传递到模板上,其中键必须是字符串,值可以是列表,字典,自定义对象等等:

dic = {"变量1":1, "变量2":2}

举个例子


page2.html

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Template</title>
</head>
<body>
	<h1>这是我的第2个模板</h1>
   <h2> 姓名:{{name}}</h2>
   <h2>年龄:{{age}}</h2>
	 <h3>兴趣:{{hobby}}</h3>
   <h3>第1个兴趣:{{hobby.0}}</h3>
   <h3>朋友:{{friend.name}}</h3>
   <h3>兔子:{{bunny.name}}</h3>
   <h3>兔子说:{{bunny.speak}}</h3>

</body>
</html>

urls.py

from django.contrib import admin
from django.urls import path
from django.urls import re_path
from . import views

urlpatterns = [
    path('admin/', admin.site.urls),
    re_path(r'page2_template/$', views.page2_template),
]

views.py

class Bunny:
    
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def speak(self):
        string = self.name + "今年已经" + str(self.age) + "个月啦"
        return string
        

def page2_template(request):
    d = {"name":"Ada","age":22,
         "hobby":["羽毛球", "Game", "看书"],
         "friend":{"name":"Wang", "age":23},
          "bunny":Bunny("Huang", 10)}
    return render(request, "page2.html", d)


向http://127.0.0.1:8000/page2_template/发起请求:

猜你喜欢

转载自blog.csdn.net/m0_37422217/article/details/106755876
今日推荐