路由系统
创建APP
a. 使用pycharm创建django的时候, 加上app的名字
b. Python manage.py startapp app的名字
路由分组
将业务逻辑写道app中的views中
from app01 import views
urlpatterns = [
# url(r'^admin/', admin.site.urls),
url(r'^test/', views.test),
]
使用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文件
from django.conf.urls import url
from classes import views
urlpatterns = [
url(r'^get_classes/', views.get_classes)
]
在这个app的views中,添加业务逻辑函数
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的约束, 传参的时候, 会根据顺序来获取参数对应的值
而如果有约束的话, 传参的时候, 会固定的将获取的值传给所对应的的约束
自定义404页面、
urls.py
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