4.對urls.py的解釋

來源:互聯網
上載者:User

標籤:啟動   att   url參數   images   傳遞   django   map   文法   方式   

解釋:

  路由設定檔(URL分發器),它的本質是URL模式以及要為該URL模式調用的視圖函數之間的映射表。就是以這種方式告訴Django對於每個URL的處理類。Django啟動的時候回去載入urls.py檔案,載入那個檔案可以在hello_django\hello_django\setting.py中通過ROOT_URLCONF配置,如ROOT_URLCONF = ‘hello_django.urls‘(預設配置)

理解:

  相當於spring mvc裡的@RequestMapping的作用

基本文法:

  urlpatterns = [
    url(Regex, view函數, 參數, 別名, 首碼),
  ]

 

用法一(不帶參數):

  from django.contrib import admin
  urlpatterns = [
    # url(r‘^hello/‘, views.hello),
  ]

用法二(不帶參數):
  urlpatterns = [
    url(r‘^hello/‘, ‘hello.views.hello‘),
  ]

 

備忘:用法一和用法二是一樣的,但是方法二在1.9版本後將不再推薦使用,被標記為過時

 

用法三(帶參數):
  urlpatterns = [
    url(r‘^hello/‘, ‘hello.views.hello‘, {‘name‘:‘xiaol‘}),
  ]

  相應的,view裡去接收這個參數,修改為:

   

 

  

 

關於  Regex:

  1.定義url訪問路徑:

    urlpatterns = [

      url(r‘^hello/\d{2}‘, views.hello),
    ]

  訪問的時候必須在hello後面帶個兩位元:http://localhost:8000/hello/22

 

  2.傳遞url參數:

    urlpatterns = [

      url(r‘^hello/(?P<id>\d{2})‘, views.hello),
    ]

  意思是:在hello後面帶個兩位元字,並且,這個兩位元字被作為參數傳進去,參數名是id

  相應的,view裡去接收這個參數,修改為:

  

  

 

以下英文為urls.py檔案內建的注釋,裡面的三個例子值得看

The `urlpatterns` list routes URLs to views. For more information please see:https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
  Function views
    1. Add an import: from my_app import views
    2. Add a URL to urlpatterns: url(r‘^$‘, views.home, name=‘home‘)
  Class-based views
    1. Add an import: from other_app.views import Home
    2. Add a URL to urlpatterns: url(r‘^$‘, Home.as_view(), name=‘home‘)
  Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns: url(r‘^blog/‘, include(‘blog.urls‘))

 

4.對urls.py的解釋

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.