【django】配置URLconf
用戶通過在瀏覽器的地址欄中輸??址請求?站;對于Django開發(fā)的?站,都是通過匹配路由找到相應(yīng)視圖來處理?戶的請求。
一、配置URLconf
1、setting.py文件中
a、指定根路由位置
ROOT_URLCONF = ‘項??程同名?錄.urls’
2、編輯項目中的urls.py文件(根路由)
匹配成功后,include到子應(yīng)用的urls.py文件中尋址(子路由)
re_path(正則,include('子應(yīng)用.urls'))
3、創(chuàng)建子應(yīng)用中的urls.py文件(子路由)
匹配成功后,調(diào)用views.py對應(yīng)的函數(shù)
re_path(正則,views.函數(shù)名)
4、路由文件urls.py
例1:include子路由
主路由
子路由:
urlpatterns = [path('hello/',views.helloview),#正則表達式re_path('^hello/$',views.helloview)]視圖:
def helloview(request):return HttpResponse('helloview')例2:子路由中有參數(shù)
關(guān)鍵字傳參:路由中的參數(shù)和視圖函數(shù)中的參數(shù)必須保持一致
主路由
from django.urls import include, path,re_path urlpatterns = [path('admin/', admin.site.urls),path('film/',include('film.urls')), ]子路由:
urlpatterns = [path('hello/<uname>/',views.helloview),#正則表達式re_path(r'^hello/(?P<uname>\w+)/$', views.helloview), ]視圖:
def helloview(request,uname):return HttpResponse('helloview')訪問url
http://127.0.0.1:8000/film/hello/666/
例3:指定傳參類型
主路由
子路由:
只能傳遞整數(shù)型,其他類型的字符會報404,如果不指定數(shù)據(jù)類型,默認為字符串類型
視圖:
def helloview(request,age):return HttpResponse('helloview')訪問url
http://127.0.0.1:8000/film/hello/666/ 正常訪問
http://127.0.0.1:8000/film/hello/abc/ 404
二、API講解
path(route, view, kwargs=None, name=None)
re_path(route, view, kwargs=None, name=None)
include(module, namespace=None)
route: 匹配路徑開始不加 /,末尾加/
route:稱為匹配路徑
url: http://www.baidu.com/news/?wd=django
url中的news/ 稱為請求路徑
程序執(zhí)?后是將?址中的請求路徑和匹配路徑進?匹配。
三、說明
說明:雖然路由結(jié)尾帶/能帶來上述好處,但是卻違背了HTTP中URL表示資源位置路徑的設(shè)計理念。
是否結(jié)尾帶/以所屬公司定義?格為準。
當 Django 找不到所匹配的請求 URL 時,或引發(fā)了異常時,Django 會調(diào)??個錯誤處理視圖。
總結(jié)
以上是生活随笔為你收集整理的【django】配置URLconf的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【django】基础条件查询
- 下一篇: 【django】 F 和 Q 对象