Python中Django的MTV开发模式(服务器返回html页面功能实现)

M: Models 模型 与数据相关的功能操做(常对应数据库或者一些其余储存数据的文件)·

V: Views 视图 针对请求选取数据的功能(选择哪些数据用于显示,指定显示模板,每一个URL对应一个回掉函数)对应一个views.py文件。

T:Templates 模板 与表现相关的全部功能 (页面展现风格和方式,与具体数据分离,用于定义和表现风格,通常是 外部的html、css、javascript文件)

MVT是建立一项目或应用时主要要考虑和修改的。其中,咱们用django建立应用时,Models默认生成,views默认生成,但Templates不默认生成,须要手工建立目录,并将文件导入。javascript

Django实现对应http请求返回HTML页面

思路:创建模板(T),对应特定请求,返回模板页面。新建hello2app,经过index2来访问css

步骤

  1. 新建hello2app应用 />python manage.py startapp hello2app
  2. 在hello2app中新建一个python包,咱们命名为templates,在其中建立或添加要返回给用户的页面(假设为try.html),修改views.py
form django.shortcuts import render

def hello(request){
    return render(request,"try.html");
}

此处,render()是一个打包函数,第一个参数是request,第二个参数是页面 3. 在hello2app中,新建urls.py文件(本地路由文件)html

from django.urls import path
from . import views
urlspatterns=[
path(' ',views.hello)
]

其中,.表明当前app,urlspatterns 是一个固定的变量名。java

  1. 在全局路由文件中添加对本地路由文件的引用
from django.contrib import admin
from django.urls import include,path
from helloapp import views

urlpatterns=[
path('index2/',include('hello2app.urls')),
path('index/',views.hello),
path('admin/',admin.site.urls),
]

其中,include() 函数用于引入其余路由文件,第一个path将hello2app中的局部路由增长到全局路由中。 5. 设置模板路径,让Django框架找到模板所在目录python

......  
TEMPLATES=[
{
    ......
'DIRS':[os.path.join(BASE_DIR,'hello2app/tempaltes')],  
......
}  
]  
......

指定templates所在路径数据库

最后开服务器进行查看,会看到html页面。django

相关文章
相关标签/搜索