M: Models 模型 与数据相关的功能操作(常对应数据库或者一些其他储存数据的文件)·
V: Views 视图 针对请求选取数据的功能(选择哪些数据用于显示,指定显示模板,每个URL对应一个回掉函数)对应一个views.py文件。
T:Templates 模板 与表现相关的所有功能 (页面展示风格和方式,与具体数据分离,用于定义和表现风格,一般是 外部的html、css、javascript文件)
MVT是创建一项目或应用时主要要考虑和修改的。其中,我们用django创建应用时,Models默认生成,views默认生成,但Templates不默认生成,需要手工创建目录,并将文件导入。
Django实现对应http请求返回HTML页面
思路:建立模板(T),对应特定请求,返回模板页面。新建hello2app,通过index2来访问
步骤
- 新建hello2app应用 />python manage.py startapp hello2app
- 在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文件(本地路由文件)
from django.urls import path
from . import views
urlspatterns=[
path(' ',views.hello)
]
其中,.代表当前app,urlspatterns 是一个固定的变量名。
- 在全局路由文件中添加对本地路由文件的引用
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框架找到模板所在目录
......
TEMPLATES=[
{
......
'DIRS':[os.path.join(BASE_DIR,'hello2app/tempaltes')],
......
}
]
......
指定templates所在路径
最后开服务器进行查看,会看到html页面。