Hello
I have this dictionary in my apps model file:
TYPE_DICT = (
("1", "Shopping list"),
("2", "Gift Wishlist"),
("3", "test list type"),
)
model, which uses this dict is this:
class List(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=200)
type = models.PositiveIntegerField(choices=TYPE_DICT)
I want to re-use it in my views and imported it from apps.models. I am creating a list of dictioneries to use in my view like this:
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)
When i use this list in my template then it gives me very strange results. Instead of returning me the type of the list (shopping list) it returns me ('2', 'Gift Wishlist').
So i can understand what it is doing (in ths case, the dict.type equals 1, and it should return me "shopping list" , but it returns me [1] - second, element in list). What i do not understand, why doing exactly the same thing in python shell gives different results.
doing it the way i do in django ( TYPE_DICT[dict.type] ), works as described above and creates error in python shell. using TYPE_DICT[str(dict.type)] in python shell works just fine, but creates this error in 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
Perhaps i did something wrong or different in python shell. What i did was:
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
>>>
so what is wrong here?
Alan