1. 程式人生 > >django-urls(路由)

django-urls(路由)

quest base app cut def 設置 after ron resp

Django的路由入口是urls.pyurlpatterns參數。
通過查找urlpatterns中的對應關系分發請求到各個視圖函數或類。

一、分發請求到函數
1、應在對應app的views.py中定義好處理函數,如:

1 def business_new(request):
2     return HttpResponse("Django")

2、在urls.py中導入對應的模塊

1 from app1 import views

3、在urlpatterns中加入對應關系

1 path(app1/,views.business_new)  #fbv  function base view

二、分發請求到類
1、應在對應app的views.py中定義好處理類,如:

 1 from django.views import View
 2 class Blog(View):   #應繼承View
 3     def dispatch(self, request, *args, **kwargs):
 4         print("before")
 5         result = super(Blog,self).dispatch(request, *args, **kwargs)   #根據請求方式分發
 6         print("after")
 7         return
result 8 9 def get(self,request): 10 return HttpResponse("BLOG") 11 12 def post(self,request): 13 pass

2、在urls.py中導入對應的模塊

1 from app1 import views

3、在urlpatterns中加入對應關系

1 path(blog/,views.Blog.as_view()),     #CBV    class base view

三、路由的特殊寫法
1、使用正則,如:

1 re_path(
article-(\d+)-(\d+)/,views.article) 2 re_path(article-(?P<article_type_id>\d+)-(?P<category_id>\d+)/,views.article) #分組

可同過形如:address/article-1-2 的方式訪問
方法二會將1傳給article_type_id,2傳給category_id

使用正則時應導入re_path方法

1 from django.urls import path,re_path

2、name屬性,如

1 re_path(article-(?P<article_type_id>\d+)-(?P<category_id>\d+)/,views.article,name=article)

設置該屬性後可以通過reverse方法反向生成url,如:

1 file: views.py
2 from django.shortcuts import reverse
3 def article(request,**kwargs):
4     ......
5     url = reverse(article,kwargs=kwargs)
6         print(url)
7     ......

3、分發到app的urls,如:

1 from django.urls import path,include #導入include
2 
3 urlpatterns = [
4     path(admin/, admin.site.urls),
5     path(app1/,include(app1.url))
6 ]

此時訪問形如 address/app1/XXX 的url時會進入app1 -> url.py 中查找urlpatterns

django-urls(路由)