Django中views如何設置全局變量
6 回答

慕仙森
TA貢獻1827條經驗 獲得超8個贊
問題在于test = 1實際上是定義了一個局部變量test,它隱藏了全局作用域中的test變量。
要指明使用全局的test變量,需要使用global關鍵字。
12345678910111213 | from django.http import HttpResponse test = 0 def a(request): global test test = 1 return HttpResponse( 'view a: test = %d' % test) def b(request): global test test + = 1 return HttpResponse( 'view b: test = %d' % test) |

智慧大石
TA貢獻1946條經驗 獲得超3個贊
簡單使用的話,不要使用整數這種不可變的對象類型。使用列表或者字典。比如:
1234567 | test = [ 0 ] def a(request): test[ 0 ] + = 1 pass def b(request): print (test[ 0 ]) pass |

嗶嗶one
TA貢獻1854條經驗 獲得超8個贊
首先,在django 視圖函數中,傳遞 obj_list = [1, 2, 3] 類似這樣的一個列表。 def show_data(request): obj_list = [1, 2, 3] pass return render_to_response('index.html', {'obj_list': obj_list})然后在 index.html 模板文件中
- 6 回答
- 0 關注
- 3208 瀏覽
添加回答
舉報
0/150
提交
取消