在Django视图中(重)使用字典
我在我的应用模型文件里有一个字典:
TYPE_DICT = (
("1", "Shopping list"),
("2", "Gift Wishlist"),
("3", "test list type"),
)
使用这个字典的模型是:
class List(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=200)
type = models.PositiveIntegerField(choices=TYPE_DICT)
我想在我的视图中重复使用它,所以从 apps.models 导入了这个字典。我正在创建一个字典列表,用于在我的视图中使用,像这样:
bunchofdicts = List.objects.filter(user=request.user)
array = []
for dict in bunchofdicts:
ListDict = {'Name':dict.name, 'type':TYPE_DICT[dict.type], 'edit':'placeholder' }
array.append(ListDict)
当我在模板中使用这个列表时,结果却很奇怪。它没有返回我想要的列表类型(购物清单),而是返回了 ('2', '礼物愿望清单')。
我能理解它在做什么(在这种情况下,dict.type 等于 1,它应该返回 "购物清单",但它却返回了 [1] - 列表中的第二个元素)。我不明白的是,为什么在 Python shell 中做同样的事情却得到不同的结果。
在 Django 中这样做 ( TYPE_DICT[dict.type] ),如上所述会产生错误,而在 Python shell 中使用 TYPE_DICT[str(dict.type)] 则可以正常工作,但在 Django 中会出现这个错误:
TypeError at /list/
tuple indices must be integers, not str
Request Method: GET
Request URL: http://127.0.0.1/list/
Exception Type: TypeError
Exception Value:
tuple indices must be integers, not str
Exception Location: /home/projects/tst/list/views.py in list, line 22
Python Executable: /usr/bin/python
Python Version: 2.6.2
也许我在 Python shell 中做错了什么或做得不同。我做的事情是:
python
Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> dict = {'1':'shoppinglist', '2':'giftlist','3':'testlist'}
>>> print dict[1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 1
>>> print dict[str(1)]
shoppinglist
>>> x = 1
>>> print dict[x]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 1
>>> print dict[str(x)]
shoppinglist
>>>
那么这里到底出了什么问题呢?
Alan
4 个回答
你好,我从昨天开始就一直在尝试这个,今天我意识到你可以自己制作过滤器,这样就可以传递存储在数据库中的字典键。
我想用这个来处理州(states),因为我在很多模型中都用到它,所以我把它添加到了设置中,步骤如下:
在 settings.py 文件中
...
CSTM_LISTA_ESTADOS = (
('AS','Aguascalientes'),
('BC','Baja California'),
...
('YN','Yucatan'),
('ZS','Zacatecas')
)
...
在我的 customtags.py 文件中
@register.filter(name='estado')
def estado(estado):
from settings import CSTM_LISTA_ESTADOS
lista_estados = dict(CSTM_LISTA_ESTADOS)
return lista_estados[estado]
在我的模板 basicas.html 文件中
{{oportunidad.estado|estado}}
oportunidad 是我传递给模板的变量
希望这对其他人也有帮助
首先,把你的元组改成字典格式。然后,在Django模板中访问时,你需要把字典的键当作属性来使用。假设这个是字典:
TYPE_DICT = {
1: 'Shopping list',
2: 'Gift Wishlist',
3: 'test list type',
}
在Django模板中访问这个字典时,你应该这样使用:
TYPE_DICT.1
你在模型文件里的 TYPE_DICT
其实不是一个字典,而是一个元组的元组。
不过,如果你想的话,可以很简单地把它变成一个字典:
TYPE_DICT_DICT = dict(TYPE_DICT)
这样你就可以把 TYPE_DICT_DICT
当作一个真正的字典来使用了。