本博文源于django基础,关于视图的操作。路由分发的本质在于解耦!因此完成本实验也是非常简单愉快的。实验步骤如下:
这里假设在项目test01下完成本实验!templates文件夹创建和os.path也有做
创建app
python manage.py startapp app01
python manage.py startapp app02
修改settings.py
# 主要改动这里
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app01.apps.App01Config', # 新增
'app02.apps.App02Config', # 新增
]
在test01/urls.py作路由分发
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('app01/',include('app01.urls')),
path('app02/',include('app02.urls')),
path('admin/', admin.site.urls),
]
# test01下创建templates
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')], # 新编辑
'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',
],
},
},
]
创建urls.py
from django.urls import path
from app01 import views # 新增
urlpatterns = [
path('index/',views.index),
]
views.py文件转向
from django.http import HttpResponse
from django.shortcuts import render
# Create your views here.
from django.views import View
def index(request):
app_num = 'app01_index'
return render(request,'app01_index.html',locals())
模板文件下创建app01_index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>app01_Idex</title>
</head>
<body>
<h1>我是{{ app_num }}页面</h1>
</body>
</html>
from django.urls import path
from app02 import views # 新增
urlpatterns = [
path('index/',views.index),
]
views.py文件转向
from django.shortcuts import render
# Create your views here.
def index(request):
app_num = 'app02_index'
return render(request,'app02_index.html',locals())
模板文件下创建app02_index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>app02_Idex</title>
</head>
<body>
<h1>我是{{ app_num }}页面</h1>
</body>
</html>