使用django的MTV开发模式返回一个网页

1.MTV开发模式介绍

M:Models 模型(数据)

与数据组织相关的功能。组织和存储数据的方法和模式,与数据模型相关的操作。

T:Templates 模板(样式)

与表现相关的所有功能。页面展示风格和方式,与具体数据分离,用于定义表现风格。

V:Views 视图(处理)

针对请求选取数据的功能。选择哪些数据用于展示,指定显示模板,每个URL对应一个回调函数。

2.新建一个应用

在上一篇的基础上继续改进。django最小程序开发流程

python manage.py startapp hello2app

3.修改hello2app

hello2app中的views.py代码如下

from django.shortcuts import render

# Create your views here.
def hello(request):
    return render(request,"hello.html")

其中的render()是一个打包函数,第一个参数是request,第二个参数是页面。

还需要在hello2app中增加一个templates文件夹,并在文件夹内放入模板文件,此处为hello.html

4.增加本地路由

所谓本地路由,就是在这个应用内的路由文件。在hello2app中新增urls.py,代码如下

from django.urls import path
from . import views  ##引入第3步写的views.py

urlpatterns=[
    path('',views.hello)  ##本地路由的函数调用
]

啧,写这一步还踩了个坑。打字老是把字母顺序打反,之前也有这样的经历,看了半天不知道哪错了。最后才发现把from打成form了,唉

5.增加对本地路由的引用

在全局路由文件中增加对本地应用路由的引用。修改mysite\mysite\urls.py文件为如下内容

from django.contrib import admin
from django.urls import path,include  ##include函数,用于引入其他路由文件
from helloapp import views

urlpatterns = [
    path('index2/',include('hello2app.urls')),  ##将hello2app的局部路由增加到全局路由中
    path('index/',views.hello),
    path('admin/', admin.site.urls),
]

6.设置模板路径

修改mysite\mysite\settings.py。修改其中的TEMPLATES = []。将DIRS中增加templates目录

'DIRS': [os.path.join(BASE_DIR,'hello2app/templates')],  ##将BASE_DIR主路径和后面的路径合并

DIRS是一个列表,还可以继续添加其他路径。

 

posted @ 2019-07-06 08:42  roadwide  阅读(275)  评论(0编辑  收藏  举报