码迷,mamicode.com
首页 > 其他好文 > 详细

04.路由配置

时间:2021-05-24 17:08:46      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:pac   admin   res   eve   student   att   htm   方法   dmi   

1.1 Django路由分发

# mysite/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path(admin/, admin.site.urls),
    # 配置路由分发
    path(app01/, include((app01.urls, app01), namespace=app01)),
]

1.2 普通url

1.2.1 app01/urls.py

from django.urls import path, re_path
from app01 import views

urlpatterns = [
    re_path(index1/$, views.index1, name=indexname1),          # 方法1:无正则匹配url
]

1.2.2 app01/views.py

from django.shortcuts import HttpResponse

# 方法1:无正则匹配url( http://127.0.0.1:8000/index1/?uid=1 )
def index1(request):
    print( request.GET )             # {"uid": "1"}
    nid = request.GET.get(uid)    # 1
    return HttpResponse(无正则匹配url)

1.3 正则的url (\d+)

1.3.1 app01/urls.py

 

from django.urls import path, re_path
from app01 import views

urlpatterns = [
    re_path(index2/(\d+)/$, views.index2, name=indexname2),     # 方法2:基于(\d+)正则的url
]

1.3.2 app01/views.py

from django.shortcuts import HttpResponse

# 方法2:基于(\d+)正则的url(  http://127.0.0.1:8000/index2/1/  )
def index2(request, uid):
    print( uid )                    # 1
    return HttpResponse(基于(\d+)正则的url)

1.4 正则分组(?P<nid>\d+)

  • 基于正则分组(?P<nid>\d+),可以不考虑接收参数顺序 (推荐)

1.4.1 app01/urls.py

from django.urls import path, re_path
from app01 import views

urlpatterns = [
    re_path(index3/(?P<nid>\d+)/(?P<pid>\d+)/$, views.index3, name=indexname3),        # 方法3:基于(\d+)正则的url
]

1.4.2 app01/views.py

from django.shortcuts import HttpResponse

# 方法3:基于正则分组(?P<nid>\d+)(  http://127.0.0.1:8000/app01/index3/1/2/  )
def index3(request, nid, pid):
    print(nid)                     # 1
    print(pid)                     # 2
    return HttpResponse(基于正则分组url)

1.5 使用name构建自己想要的url

1.5.1 app01/urls.py 

from django.urls import path, re_path
from app01 import views

urlpatterns = [
    re_path(index4/$, views.index4),                               # 方法4:使用name构建自己想要的url
]

1.5.2 app01/views.py

from django.shortcuts import HttpResponse
from django.urls import reverse

# 方法4:使用name构建自己想要的url (http://127.0.0.1:8000/index4/)
def index4(request):
    url1 = reverse(indexname1)                         # /index1/
    url2 = reverse(indexname2, args=(1,))                  # /index2/1/2/
    url3 = reverse(indexname3, kwargs={pid: 1, "nid":2})       # /index3/1/2/
    return render(request, index.html)

1.5.3 反解出url中的name

  根据request.path中的绝对路径反解出url中的name名字

resolve_url_obj = resolve(request.path)         # request.path路径: /student/homework_detail/52
resolve_url_obj.url_name                   # 从path中解析出url名字 url_name = homework_detail

 

 
 
 
 
 
 
 
 
 
 
 
 
 

04.路由配置

标签:pac   admin   res   eve   student   att   htm   方法   dmi   

原文地址:https://www.cnblogs.com/xiaoxiamiaichiyu/p/14788722.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!