zoukankan      html  css  js  c++  java
  • Django的路由系统01-路由分发

    1. Including other URLconfs

    原urls.py文件,多个app的路由系统写在一起,不方便管理

    范例:

    from django.conf.urls import url
    from django.contrib import admin
    from app01 import views
    from app02 import views as app02_views
    
    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        url(r'^publisher_list/$', views.PubList.as_view()),
        url(r'^edit_publisher/$', views.EditPub.as_view()),
        url(r'^book_list/$', views.BookList.as_view()),
        url(r'^templates/$', views.Templates.as_view()),
        url(r'^book/$', app02_views.book),
    ]

    2. 使用include

    使用:

    2.1 注释app01的相关配置

    from django.conf.urls import url
    from django.contrib import admin
    
    from app02 import views as app02_views
    
    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        # url(r'^publisher_list/$', views.PubList.as_view()),
        # url(r'^edit_publisher/$', views.EditPub.as_view()),
        # url(r'^book_list/$', views.BookList.as_view()),
        # url(r'^templates/$', views.Templates.as_view()),
        url(r'^book/$', app02_views.book),
    ]

    2.2 在app01目录中创建urls.py文件

    from django.conf.urls import url
    from app01 import views
    
    
    urlpatterns = [
        url(r'^publisher_list/$', views.PubList.as_view()),
        url(r'^edit_publisher/$', views.EditPub.as_view()),
        url(r'^book_list/$', views.BookList.as_view()),
        url(r'^templates/$', views.Templates.as_view()),
    ]

    但是仅此而已还不够,启动Django项目,发现不能访问app01中的链接

    2.3 导入urls模块的include方法

    方法一:

    from django.conf.urls import url, include
    from django.contrib import admin
    from app02 import views as app02_views
    
    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        # 这种方式不明确,不能根据程序区分
        url(r'^', include('app01.urls')),
        url(r'^book/$', app02_views.book),
    ]

    方法二:

    from django.conf.urls import url, include
    from django.contrib import admin
    from app02 import views as app02_views
    
    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        # 这种方式可以根据不同的程序访问不同的url
        url(r'^app01/', include('app01.urls')),
        url(r'^book/$', app02_views.book),
    ]
    

      


  • 相关阅读:
    for循环
    条件语句练习
    语句
    语言基础
    python -- 异步IO 协程
    转--python -- 收发邮件
    hive vs hbase
    postgresql 常用速查
    转--利用hexo搭建个人静态博客
    转- --python 3 编码
  • 原文地址:https://www.cnblogs.com/gongniue/p/10933500.html
Copyright © 2011-2022 走看看