(django)url路由配置及渲染方式

一,url路由path及轉(zhuǎn)化器

URL(uniform Resoure Locator)統(tǒng)一資源定位符,是對可以從互聯(lián)網(wǎng)上得到的資源的位置和訪問方法的一種簡潔的表示,是互聯(lián)網(wǎng)上標(biāo)準(zhǔn)資源的地址,互聯(lián)網(wǎng)上的每個文件都有唯一的URL,它包含的信息指出文件的位置以及瀏覽器應(yīng)該怎么處理它。

設(shè)置好url,用戶才能訪問

1,URL的格式:

例如:http://127.0.0.1:8000/hello/

解釋:

schema://host[:port#]/path/.../[?query-string][#anchor]

schema:指定使用的協(xié)議(如:http,https,ftp)

host:Http服務(wù)器的IP地址或者域名

port:端口號,http默認(rèn)是80端口

path:訪問資源的路徑

query-string:發(fā)送給http服務(wù)器的數(shù)據(jù)

anchor:錨點

2,urls.py的作用

URL配置(URLconf)就像是Django所支撐網(wǎng)站的目錄。它的本質(zhì)是URL模式以及URL模式調(diào)用的視圖函數(shù)之間的映射表。以這樣的方式告訴Django,對于哪個URL調(diào)用那段代碼。URL的加載就是從配置文件中開始

例如:在項目下urls.py文件:

from django.contrib import admin

from django.urls import path

from . import views

urlpatterns = [

? path('admin/', admin.site.urls),

path("abc/",views.hello),

path("ab/", views.hello_python),

path("ab//", views.hello_name),#獲取變量name

]

views.py文件:

from django.shortcuts import render

from django.http import HttpResponse

# Create your views here.

def hello(request):

?? return HttpResponse("123344")

?def hello_python(request):

?? return HttpResponse("HELLO PYTHON!!")

def hello_name(request,name):

?? return HttpResponse("hello %s"%name)#傳進去變量name

3,path基本規(guī)則

path('test//',views.test)

1:使用尖括號(<>)從url中捕獲值。包含一個轉(zhuǎn)化器類型(converter type)沒有轉(zhuǎn)化器,將匹配任何字符串,當(dāng)然也包括了 / 字符

2:當(dāng)前面的url匹配成功后就會調(diào)用后面的視圖函數(shù)

4,轉(zhuǎn)化器:

path('test/int:xx/',views.test3)

path("/", views.hello_name),

#類型轉(zhuǎn)換(path已經(jīng)提供好的轉(zhuǎn)換器int)

默認(rèn)的轉(zhuǎn)換器:

str,匹配除了路徑分隔符(/)之外的非空字符串,這是默認(rèn)的形式int,匹配正整數(shù),包含0。

slug,匹配字母、數(shù)字以及橫杠、下劃線組成的字符串。

uuid,匹配格式化的uuid,如 075194d3-6885-417e-a8a8-6c931e272f00。

path,匹配任何非空字符串,包含了路徑分隔符

二,re_path及incloude例子

1,正則表達式對應(yīng)的要用re_path(類型轉(zhuǎn)化器)

re_path("(?p\d+)",views.hello_name),#正則表達式寫法(轉(zhuǎn)換器)

#url.py

re_path('^hello/$',views.test5), ? ?

re_path('^hello/(?P[0-9]+)/',views.test6),

#views.py

def test5(request): ? ?

? ? return HttpResponse('這是用的re_path設(shè)置的')

def test6(request,yy): ? ?

? ? print(yy,type(yy)) ? ?

? ? return HttpResponse('hello %s'%yy)

2,incloude分配路由:

一個project有一個總的urls.py各個app也可以自己建立自己的urls.py用include()函數(shù)在project的urls.py文件進行注冊

主目錄下分配路由到其他目錄urls.py

from django.contrib import admin

from django.urls import path,include

from . import views

urlpatterns = [

?? path('admin/', admin.site.urls),

?? path('book/',include('book.urls')),

]

path('book/', include("book.urls")),#給APP分配路由

分路由下配置url.py

from django.urls import path

from . import views?

urlpatterns = [

?? path('index/', views.hello),

?? ]

APP下的視圖文件views.py

from django.shortcuts import render

from django.http import HttpResponse

# Create your views here.

def hello(request):

?? return HttpResponse("這是book主頁")

有變量也可用在app里(與主項目用法相同)

def hello(request,book_name,**kwargs):

?? print(book_name)

?? return HttpResponse("這是book主頁")

path('index//', views.hello),

三,kwarg,name,redirect,reverse頁面重定向

1,kwargs的作用

傳遞一個Python 字典作為額外的參數(shù)傳遞給視圖函數(shù)。

# 主urls.py文件

from django.contrib import admin

from django.urls import path,include

urlpatterns = [ ? ?

? ?? path('admin/', admin.site.urls), ? ? ? path('book/',include('book.urls'),{'switch':'true'}),

? ?? ]

視圖函數(shù)中可以通過關(guān)鍵字參數(shù)獲取到

# APP books里面的views.py

from django.http import HttpResponse

import datetime

def index(request,**kwargs): ? ?

?? if kwargs.get('switch') == 'true':

? ? ? ? print(datetime.datetime.now())

?? return HttpResponse('這個book的首頁!!')

Kwargs為字典類型可以傳遞額外的參數(shù)到views中使用include的時候需要統(tǒng)一給下面的url一些參數(shù)的時候顯得尤其有用

2,name

name參數(shù)可以給這個url取一個合適的名字。通過給url取名字,以后在view或者模板中使用這個URL,就只需要通過這個名字就可以了。這樣做的原因是防止url的規(guī)則更改,會導(dǎo)致其他地方用了這個url的地方都需要更改,但是如果取名字了,就不要做任何改動了。

給一個匹配的url地址取名字一般用于模板,也可以使用reverse進行頁面重定向

頁面重定向

from django.shortcuts import render,redirect

from django.http import HttpResponse

# Create your views here.

?def article(request,**kwargs):

?? return redirect("/book/article_new/") #頁面跳轉(zhuǎn)

? ? return HttpResponse("這是老的頁面")

def article_new(request,**kwargs):

?? return HttpResponse("這是新的頁面")?

from django.urls import path

from . import views

urlpatterns = [

?? path('article/', views.article),

?? path('article_new/', views.article_new),

redirect是重定向,reverse是將url的name解析成url本身的函數(shù)

from django.shortcuts import render,redirect,reverse

from django.http import HttpResponse

# Create your views here.

?def article(request,**kwargs):

?? return redirect(reverse("new_article"))

?? return HttpResponse("這是老的頁面")

def article_new(request,**kwargs):

?? return HttpResponse("這是新的頁面")

from django.urls import path

from . import views

urlpatterns = [

?? path('article/', views.article),

?? path('article_new/', views.article_new,name="new_article"),

?? #name與path匹配

]

四,模板渲染

Django怎樣去調(diào)用漂亮的HTML前端頁面呢?

1.直接將html字符串硬編碼HttpResponse中

def index_1(request):

return HttpResponse("hello django world!")

2.django.template.loader 定義了函數(shù)以加載模板

1.在主目錄下創(chuàng)建一個templates目錄用來存放所有的html的模板文件.2.templates目錄里面在新建各個以app名字命名的目錄來存放各個app中模板文件.

?2,將我們的設(shè)置好的存放html模板的templates目錄路徑添加到DIRS中

#在setting.py中找到templates,修改"DIRS"?

TEMPLATES = [

?? {

? ? ?? 'BACKEND': 'django.template.backends.django.DjangoTemplates',

? ? ?? 'DIRS': [os.path.join(BASE_DIR, 'templates')]

? ? ?? ...

render方法上傳(views.py文件)

from django.template.loader import get_template

def index(request,**kwargs):

? ? ? ?t=get_template("book/index.html")

? ? ? ?html=t.render()

? ? ? return HttpResponse(html)

3.使用render進行渲染。

只用render 方法上傳**

def index(request,**kwargs):

?? return render(request,"book/index.html")

模板里傳參

#有變量name渲染(views.py)

def index(request,name,**kwargs):

render(request,"book/index.html",context={"name":name})

#urls.py

from django.urls import path

from . import views

urlpatterns = [? ?

path('index//', views.index),?

? ]

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容