Django中views如何设置全局变量
6 回答
胡子哥哥
TA贡献1825条经验 获得超6个赞
问题在于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) |
慕标5832272
TA贡献1966条经验 获得超4个赞
简单使用的话,不要使用整数这种不可变的对象类型。使用列表或者字典。比如:
| 1234567 | test = [0]def a(request): test[0] += 1 passdef b(request): print(test[0]) pass |
一只甜甜圈
TA贡献1836条经验 获得超5个赞
首先,在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 关注
- 949 浏览
添加回答
举报
0/150
提交
取消
