python例子 Django專案中的模版特性

2022-08-29 04:57:10 字數 3471 閱讀 9351

一、在網頁上顯示乙個字元變數

在views.py中定義處理函式:(記得在urls.py中繫結url)

#

coding: utf-8 #這裡如果不指定utf-8的話,漢字輸出就會報編碼錯誤.

from django.shortcuts import

render

defhome(request):

string = u"

乙個中文字元

"return render(request, '

home.html

', )

在templates模版資料夾下的模版檔案中的格式:

}

注意:以後顯示變數就使用} 的形式.

二、for迴圈以及list,dict的顯示

在views.py中定義處理函式:(記得在urls.py中繫結url)

#

coding:utf-8

from django.shortcuts import

render

#create your views here.

defhome(request):

string = '

showstring

'list_arry = ['

one','

two','

three

','four

','haha

','it\'s gred']

dict_info =

return render(request,'

home.html

',)

模版檔案中對應:

#

list迴圈:

#迴圈 } #

輸出迴圈變數

#結束迴圈

#dict迴圈

}:}sorry it a empty

#如果在for迴圈中遇到empty就使用進行判斷;empty:當list,dict為空,沒有值時就時為empty,可不是某個下標為空.

#dict迴圈另一種方式

},} #

這裡格式為 dict.key

三、for迴圈以及其中的常見判斷

在views.py中定義處理函式:(記得在urls.py中繫結url)

#

coding:utf-8

from django.shortcuts import

render

#create your views here.

defhome(request):

string = '

showstring

'list_arry = ['

one','

two','

three

','four

','haha

','it\'s gred']

list_range = map(str,range(100))

#empty_list = ['a','b','c','d',' ','f']

empty_list =

return render(request,'

home.html

',)

模版檔案中對應:

#

判斷是否是list中最後乙個

},#判斷list是否為空empty}it

's empty

其他for中判斷:

forloop.counter    索引從 1開始算

forloop.counter0 索引從 0 開始算

forloop.revcounter 索引從最大長度到 1forloop.revcounter0 索引從最大長度到 0

forloop.first 當遍歷的元素為第一項時為真

forloop.last 當遍歷的元素為最後一項時為真

forloop.parentloop 用在巢狀的

for 迴圈中,獲取上一層 for 迴圈的 forloop

在views.py中定義處理函式:

#

coding:utf-8

from django.shortcuts import

render

defadd(request,a,b):

c = int(a) +int(b)

return render(request,'

add.html

',)  #返回的都為同乙個模版檔案

defother(request,c,d):

c = c +d

return render(request,'

add.html

',)  #返回的都為同乙個模版檔案

在urls.py中繫結的url:

urlpatterns =[

url(r

'^jiafa/(\d+)/(\d+)/$

','learn.views.add

',name='

add'

), url(r

'^zifu/(\w+)/(\w+)/$

','learn.views.other

',name='

other'),

url(r

'^admin/

', include(admin.site.urls)),

]

在模版中:(add.html)

#

格式為 注意,如果引數為數字可以不用加引號,為字元需加引號,否則當做變數處理。如果該變數不存在就不會生成該鏈結,這裡處理函式為other,引數為字元 'as' 'bd' 生成連線為 /zifu/as/bd ,客戶端點選該鏈結就會執行相應的請求. 這裡的url就會根據 urls.py中的正則定義帶入引數生成鏈結。as為 取別名"}

"> linkto : }

c:}otherc: }

五、模版中的邏輯操作

==, !=, >=, <=, >, < 這些比較都可以在模板中使用

great

good

ok bad

so bad

and, or, not, in, not in 也可以在模板中使用

num在0到100之間

數值不在範圍之內!

判斷 'zifu' 在不在乙個列表變數 list 中:

字元在list中

字元不在list中

2023年10月22日00:39:05

Django模板例子

使用django開發第乙個render例子。首先準備python開發環境然後建立相應的專案 1 django admin.py startproject hello 3 設定django的template路徑,在hello目錄下的setting.py中設定 template dirs f hello...

pyinstaller打包django專案

安裝pyinstaller pip install pyinstaller製作專案的.spec檔案 進入django專案所在路徑,執行 pyi makespec d manage.py在路徑下,生成乙個.spec檔案 以文字的方式開啟.spec檔案,spec檔案格式如下。具體spec的使用,可以檢視...

Django 的命令及簡單例子

cmd進入建立好的django專案目錄 然後使用下面的命令建立乙個專案testdj。sudo usr lib python3 dist packages django bin django admin.py startproject testdj 第二步 在settings.py中配置mysql連線...