2、URL配置技巧(2)

修改之前的代码

# demo
from django.contrib import admin
from django.urls import path,include, re_path
from nemo import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('huice/', include('index.urls')),
    path('wood/', include('wood.urls')),
    re_path(r'^nemo/charge1/', views.nemo_charge1),
    re_path(r'^nemo/charge2/', views.nemo_charge2),
    re_path(r'^nemo/charge3/', views.nemo_charge3),
    re_path(r'^nemo/charge4/', views.nemo_charge4),
    """..."""
  • 写法一:
from django.contrib import admin
from django.urls import path,include, re_path
from nemo import views

extra_patterns = [
    path('charge1/', views.nemo_charge1),
    path('charge2/', views.nemo_charge2),
    path('charge3/', views.nemo_charge3),
    path('charge4/', views.nemo_charge4),
    """..."""
]

urlpatterns = [
    path('admin/', admin.site.urls),
    path('huice/', include('index.urls')),
    path('wood/', include('wood.urls')),
    re_path(r'^nemo/', include(extra_patterns))
]
  • 写法二:
from django.contrib import admin
from django.urls import path,include, re_path
from nemo import views


urlpatterns = [
    path('admin/', admin.site.urls),
    path('huice/', include('index.urls')),
    path('wood/', include('wood.urls')),
    re_path(r'^nemo/', 
        include([
            path('charge1/', views.nemo_charge1),
            path('charge2/', views.nemo_charge2),
            path('charge3/', views.nemo_charge3),
            path('charge4/', views.nemo_charge4),
    
        ])
    )
]
  • 写法三:(推荐)

1.在应用文件夹下也新建urls.py文件
2.将项目下的urls.py路由引到应用名下的urls.py下即可

from django.contrib import admin
from django.urls import path,include, re_path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('huice/', include('index.urls')),
    path('wood/', include('wood.urls')),
]

上述代码中将,项目下的路由分别引入到应用index和wood下的urls.pyh中,然后再分别在对应url.py中指向对应视图函数即可

  • 下面代码以index中的urls.py为例
# index>urls.py
from django.urls import path,include,re_path
from index import views

urlpatterns = [
    path(r'login/', views.login),
    path('is_login/', views.is_login),
    path('bugs/', views.bugs_num),
    path('current/', views.current_date),
    path('app_current/', views.app_current_date),
    path('time/', views.now_time),
    # 这里是用正则表达式定义URL
    re_path(r'page/(\d+)/$', views.page_num)
]


你可能感兴趣的:(Django)