Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Bottle template issue: AttributeError("'dict' object has no attribute 'city'",)

As a learning project, I'm using MongoDB with Bottle for a web service. What I want to do is fetch results from MongoDB and display them in a template. Here's the output I want from my template:

output.tpl
<html><body>
%for record in records:
   <li>{{record.city}} {{record.date}}
%end
</body></html>

I can pull the data out no problem:

result = db.records.find(query).limit(3)
return template('records_template', records=result)

But this resulted in no output at all - some debugging shows me that result is some sort of cursor:

<pymongo.cursor.Cursor object at 0x1560dd0>

So I attempted to convert this in to something that the template would like:

result = db.records.find(query).limit(3)
viewmodel=[]
for row in result:
  l = dict()
  for column in row:
    l[str(column)]=row[column]
  viewmodel.append(l)
return template('records_template', records=viewmodel)

Debugging shows me that my view data looks OK:

[{'_id': ObjectId('4fe3dfbc62933a0338000001'),
  'city': u'CityName',
  'date': u'Thursday June 21, 2012'},
 {'_id': ObjectId('4fe3dfbd62933a0338000088')
  'city': u'CityName',
  'date': u'Thursday June 21, 2012'},
 {'_id': ObjectId('4fe3dfbd62933a0338000089')
  'city': u'CityName',
  'date': u'Thursday June 21, 2012'}]

But this is the response I'm getting. Any ideas why?

AttributeError("'dict' object has no attribute 'city'",)

Edit: I added that bit about l[str(column)]=row[column] to convert the dictionary keys to non-unicode strings in case that was the problem, but it doesn't seem to matter either way.

like image 782
Kyle Avatar asked Dec 05 '25 19:12

Kyle


1 Answers

You need to use the dictionary syntax to lookup the properties:

{{record['city']}} {{record['date']}}
like image 82
Trevor Avatar answered Dec 08 '25 10:12

Trevor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!