一、路由分发
1.1介绍
Django项目里多个app目录共用一个urls容易造成混淆,另外一个路由写错了则全部应用都受影响了。
1.2创建app02
E:\python_study\xiangys34_01>python manage.py startapp app02
备注:创建完成之后IDE编辑器可以看到分别有app01、app02
1.3添加配置
- setting.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',
]
1.4路由分发配置
from django.contrib import admin
from django.urls import path,re_path,include
urlpatterns = [
re_path(r'app01/',include("app01.urls")),
re_path(r'app02/',include("app02.urls")),
]
1.5配置子应用url分发
分别在两个app应用下创建urls.py
- app01.urls.py
from django.urls import path,re_path,include
from . import views
urlpatterns = [
re_path(r'^index/(\d{4})/',views.index),
re_path(r'^order/(?P<year>\d{4})/(?P<month>\d{2})/',views.order),
]
1.6视图函数
- views.py
from django.shortcuts import render,HttpResponse,redirect
import datetime
def index(request,id):
hi = " Give me the strength to make my love fruitful in service."
l1 = [11,22,33]
now = datetime.datetime.now()
L1 = ['alex', '金老板', '武佩琪']
return render(request,'index.html',{"hi":hi,"l1":l1,"now":now,"L1":L1,"id":id})
def order(request,month,year):
return render(request,'order.html',locals())
1.7 模板渲染
- order.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h3>有名分组</h3>
<p>年份:{{ year }}</p>
<p>月份:{{ month }}</p>
</body>
</html>
1.8访问测试
http://127.0.0.1:8000/app01/order/2005/04/
有名分组
年份:2005
月份:04
备注:打印结果如上,说明路由分发成功了
二、反向解析
随着功能的增加,路由层的url发生变化,就需要去更改对应的视图层和模板层的url,非常麻烦,不便维护。这时我们可以利用反向解析,当路由层url发生改变,在视图层和模板层动态反向解析出更改后的url,免去修改的操作。反向解析一般用在模板中的超链接及视图中的重定向。
2.1定义反向解析name
- urls.py
from django.urls import path,re_path,include
from . import views
urlpatterns = [
re_path(r'^index/',views.index),
re_path(r'^order/(?P<year>\d{4})/(?P<month>\d{2})/',views.order),
re_path(r'^login/$',views.login,name="login"),
]
2.2模板文件定义反向解析
- login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action={% url 'login' %} method="post">
{% csrf_token %}
用户名:<input type="text" name="user">
密码:<input type="text" name="pwd">
<input type="submit" value="submit">
</form>
</body>
</html>
留言