Django的路由系统
创建app
创建app:
a. 使用pycharm创建django的时候, 加上app的名字
b. Python manage.py startapp app的名字
路由的分组
a. 将业务逻辑写入到app中的views中
urls.py:
from app01 import views
urlpatterns = [
# url(r'^admin/', admin.site.urls),
url(r'^test/', views.test),
]
b. 使用include来进行app分组;
urls.py:
from django.conf.urls import url, include
urlpatterns = [
url(r'^classes/', include("classes.urls")),
url(r'^staudent/', include("staudent.urls")),
url(r'^teachers/', include("teachers.urls")),
]
在其他剩余的app中, 添加urls.py文件, 以classes为例:
from django.conf.urls import url
from classes import views
urlpatterns = [
url(r'^get_classes/', views.get_classes)
]
在这个app的views中, 添加业务逻辑处理函数, 以classes为例:
from django.shortcuts import render,HttpResponse
# Create your views here.
def get_classes(request):
return HttpResponse('classes list')
路由的分法
- 正则表达式匹配
urlrouters:
url(r'^test/(w+)/(w+)/', views.test),
url(r'^test1/(?P<id>w+)/(?P<name>w+)/', views.test1),
views.py:
def test(request, name, id):
print(id, name)
return HttpResponse('test')
def test1(request, name, id):
print(id, name)
return HttpResponse('test')
注意:
如果没有?P的约束, 传参的时候, 会根据顺序来获取参数对应的值
而如果有约束的话, 传参的时候, 会固定的将获取的值传给所对应的的约束
自定制404notfound的页面:
url(r'^', views.notfound),
views:
def notfound(request);
return render(request, "404.html")
- 反向路由解析:
urls.py:
url(r'^logindbsjhalbdhaskbhdkjsabhdkbashkdbhsabdhsja/$', views.login, name='xxx'),
login.html:
<form action="{% url "xxx" %}" method="post">
<input type="text">
</form>
- FBV (function based views)
使用函数来处理业务逻辑
- CBV (class based views)
使用类来处理业务逻辑
urls.py:
url(r'^login/', views.Login.as_view()),
views.py:
from django.views import View
class Login(View):
def get(self, request):
return render(request, "login.html")
def post(self, request):
pass
当请求过来的时候, 会优先判断你的请求方法是GET还是POST, 如果是GET请求的话, 走GET函数, 反之, 走POSt函数
Http的请求方法:
'get',:获取信息的
'post':提交数据用post方式
'put', :更新数据
'patch', :部分更新
'delete':删除
form表单的方式, 只支持GET/POST
ajax的方式, 全部支持
type: "POST" 、get、delete