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)
]


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值