天天看點

python django基礎二URL路由系統

URL配置

基本格式

from django.conf.urls import url
#循環urlpatterns,找到對應的函數執行,比對上一個路徑就找到對應的函數執行,就不再往下循環了,并給函數傳一個參數request,和wsgiref的environ類似,就是請求資訊的所有内容
urlpatterns = [
     url(正規表達式, views視圖函數,參數,别名),
]      

urls.py

from app01 import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$', views.base),#首頁比對
    # url(r'^index/', views.index),
    # url(r'index/2003/$',views.year)#這樣隻比對
    # url(r'index/([0-9]{4})/$',views.year)#比對4個數字字元還可以用d
    # url(r'index/(?P<year>[d]{4})',views.year)
    url(r'index/(?P<year>[d]{4})/(?P<month>[0-9]{2})/$',views.year)
]      

找到應用views檔案

def index(request):
    return render(request,'index.html')
def base(request):
    return render(request,'index.html')


# def year(request,a):#()方式傳參
#     return render(request,'year.html',{'a':a})

# def year(request,year):#(?P<>)方案是傳參
#     return render(request,'year.html',{'a':year})

def year(request,year,month):#(?P<>)方案是傳參
    return render(request,'year.html',{'y':year,'m':month})      

template/建立對應的html檔案

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>歡迎來到index頁面</h1>
</body>
</html>      

year.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1> 測試頁 year</h1>
<h1>{{ y }}{{ m }}</h1>
</body>
</html>      

會根據 不同 規則 得到 對應的應答 

補充說明

# 是否開啟URL通路位址後面不為/跳轉至帶有/的路徑的配置項
APPEND_SLASH=True

如果在settings.py中設定了 APPEND_SLASH=False,此時我們再請求 http://www.example.com/blog 時就會提示找不到頁面。
      

多個應用  實作url路由系統

在settings.py裡面

添加2個應用
INSTALLED_APPS = [      
'app01.apps.App01Config',
'app02.apps.App02Config',      
]

      

 在urls檔案中添加

from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    # url(r'^$', views.base),#首頁比對
    url(r'^app01/', include('app01.urls')),#首頁比對
    url(r'^app02/', include('app02.urls')),#首頁比對
]      

在2個應用中 分别添加 urls 檔案

app01中添加 urls.py

from django.conf.urls import include, url
from django.contrib import admin
from app01 import views

urlpatterns = [
    url(r'^$', views.base),#首頁比對

]      

views.py

from django.shortcuts import render,HttpResponse

# Create your views here.
def base(request):
    return render(request,'index.html')      

app02中添加 urls.py

urls.py

from django.conf.urls import include, url
from django.contrib import admin
from app02 import views

urlpatterns = [
    url(r'^$', views.base),#首頁比對

]      

views.py

from django.shortcuts import render

# Create your views here.
def base(request):
    return render(request,'index02.html')      

跳轉 指令url(别名)

from django.shortcuts import render,redirect
    return  redirect('/login')

      
url(r'^home', views.home, name='home'),  # 給我的url比對模式起名(别名)為 home,别名不需要改,路徑你就可以随便改了,别的地方使用這個路徑,就用别名來搞      

在模闆裡面可以這樣引用:

{% url 'home' %}  #模闆渲染的時候,被django解析成了這個名字對應的那個url,這個過程叫做反向解析