path
# 导包
from django.urls import path
# 格式
path('路由',路由对应视图函数,参数,路由的命名值)
re_path
# 导包
from django.urls import re_path
# 格式
re_path(r'正则',路由对应的视图函数,参数,路由的命名值)
**注**:只要符合正则,都可以访问到该视图
路由
from django.urls import path,re_path
from myapp import views
urlpatterns = [
path('register/',views.RegisterView.as_view()),
# path('//',views.index), # 指明类型
path('index2//' ,views.IndexView2.as_view()),
# re_path(r"^(?P\d+)/(?P[a-zA-Z]+)/$"), # (?Ppattern) 正则分组
re_path(r'^(?P\d+)/(?P[a-zA-Z]+)/$' ,views.IndexView3.as_view())
]
视图
# 导包
from django.views import View
from django.http import HttpResponse
class IndexView2(View):
def get(self,request, id):
return HttpResponse(f'匹配到的id为:{id}')
class IndexView3(View):
def get(self,request,x,y):
return HttpResponse(f'x为{x},y为{y}')
**注**:路由后的参数要和get里的参数一样
from django.urls import path,re_path
from myapp import views
urlpatterns = [
path('register/',views.RegisterView.as_view()),
path('login/',views.LoginView.as_view()),
path('index/',views.IndexView.as_view()),
# 参数一:正则表达式
re_path(r'^[a-z]{5}/$',views.IndexView.as_view()),
# 动态路由
path('index2//' ,views.IndexView2.as_view()),
re_path(r'^(?P\d+)/(?P[a-zA-Z]+)/$' ,views.IndexView3.as_view())
]
from django.contrib import admin
from django.urls import path,include # 导入分发
# 把子应用路由导入
from myapp import urls
urlpatterns = [
path('admin/', admin.site.urls),
# 路由分发
path('',include(urls))
]
注:主路由应导入include,导入子应用路由