view是处理浏览器显示内容的
1.定义一个视图函数
在view.py 文件中设置
from django.shortcuts import render from django.http import HttpResponse # Create your views here. #视图函数 def index(request): return HttpResponse('django hello')
2.绑定路由
在urls.py文件中设置
新建一个urls.py文件(新建一个子路由)在其中填入主路由的代码,修改
from django.urls import path
from book.views import index
urlpatterns = [
path('home/', index),
]
主路由配置
然后访问,发现404报错,是由于我们现在进入的是主路由,http://127.0.0.1:8000/
然后里面有连个子路由可以选择,需要在后面加上子路由http://127.0.0.1:8000/home/
3.浏览器访问django数据流程
浏览器首先访问主路由(bookmanager文件夹下的urls文件),然后根据主路由设置访问子路由,
子路由绑定了视图的话,就会访问子app下的视图函数,运行
4.模板导入
4.1文件夹创建
首先在工程中新建一个templates文件夹,用来保存html文件的
由于一个项目不可能只有一个app所以
再在templates文件夹下新建一个app文件夹,用来区分不同app的不同html文件
4.2配置templates路径
找到setting文件中templates设置
配置路径
os.path.join(BASE_DIR,'templates')
4.3设置html文件
4.4绑定路由
总路由设置
子路由设置
4.5视图设置
4.6查看结果