标签:pac admin res eve student att htm 方法 dmi
# 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‘)), ]
from django.urls import path, re_path from app01 import views urlpatterns = [ re_path(‘index1/$‘, views.index1, name=‘indexname1‘), # 方法1:无正则匹配url ]
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‘)
(\d+)
from django.urls import path, re_path from app01 import views urlpatterns = [ re_path(‘index2/(\d+)/$‘, views.index2, name=‘indexname2‘), # 方法2:基于(\d+)正则的url ]
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‘)
(?P<nid>\d+)
(?P<nid>\d+)
,可以不考虑接收参数顺序 (推荐)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 ]
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‘)
from django.urls import path, re_path from app01 import views urlpatterns = [ re_path(‘index4/$‘, views.index4), # 方法4:使用name构建自己想要的url ]
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‘)
根据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
标签:pac admin res eve student att htm 方法 dmi
原文地址:https://www.cnblogs.com/xiaoxiamiaichiyu/p/14788722.html