从Django数据库中获取数据并在表格中显示
我正在尝试从数据库中获取数据,使用Django框架。我想把这些数据展示在一个表格里。
但是我遇到了一个错误,错误信息是:
转换为Unicode时出错:需要字符串或缓冲区,但找到了TransType
在我的Models.py文件中有两个模型:
class TransType(models.Model):
name = models.TextField()
created = models.DateTimeField(auto_now_add = True)
updated = models.DateTimeField(auto_now = True)
def __unicode__(self):
return self.name
class Trans(models.Model):
transtype = models.ForeignKey(TransType)
script = models.CharField(max_length=200)
created = models.DateTimeField(auto_now_add = True)
updated = models.DateTimeField(auto_now = True)
class Meta:
unique_together = (("transtype", "script"),)
def __unicode__(self):
return self.transtype`
这是我的views.py文件:
def updatetrans(request):
json_data=open('/home/ttt/Ali/a.json').read()
data = json.loads(json_data)
for pk, pv in data.iteritems():
for k,v in pv.iteritems():
try:
trans_type = TransType.objects.get_or_create(name=k)
trans = Trans()
trans.transtype_id = trans_type[0].id
if isinstance(pv[k], basestring):
script = pv[k]
else:
print "****** List ****"
script = pv[k][1]
trans.script = script
trans.save()
print " Inserted ==>", script
except Exception, e:
print e
#print "Not inserted ==>", pv[k][1]
pass
#return HttpResponse("Done")
info = TransType.objects.all()
info2 = Trans.objects.all()
bookdata = { "details" : info, "details" : info2 }
print bookdata
return render_to_response("account/updatetrans.html", bookdata, context_instance=Context(request))
这是我的url.py文件:
url(r'^updatetrans/$', 'booki.account.views.updatetrans', name='updatetrans'),
这是我的updatetrans.html文件:
{% load i18n %}
<!doctype html>
<html>
<body>
<button type="button" onclick="alert('Hello world!')">Click Me!</button>
<table border="1" style="width:800px">
<tr><td>
{% for s in details %}
{{ s.script }}
{% endfor %}
</td>
<td>
{% for n in detail %}
{{ n.name }}
{% endfor %}
</td>
</tr>
</table>
</body>
</html>
请帮帮我……
错误追踪信息
环境信息:
请求方法:GET
enter code here
Django Version: 1.3
Python Version: 2.7.3
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'django.contrib.messages',
'south',
'booki.editor',
'booki.account',
'booki.reader',
'booki.portal',
'booki.messaging',
'sputnik',
'booktypecontrol']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.middleware.transaction.TransactionMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "/home/ttt/abc_booktype/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 111. response = callback(request, *callback_args, **callback_kwargs)
File "/home/ttt/abc_booktype/Booktype/lib/booki/account/views.py" in updatetrans 808.print bookdata
File "/home/ttt/abc_booktype/local/lib/python2.7/site-packages/django/db/models/query.py" in __repr__72. return repr(data)
File "/home/ttt/abc_booktype/local/lib/python2.7/site-packages/django/db/models/base.py" in __repr__370. u = unicode(self)
Exception Type: TypeError at /accounts/updatetrans/
Exception Value: coercing to Unicode: need string or buffer, TransType found
2 个回答
0
错误信息显示,问题出在你的 Trans 模型的 __unicode__
方法里。正如错误所说,你需要在这个方法中返回一个 unicode 字符串,但你现在返回的是相关的 TransType。
你可以通过在这个方法中明确地转换为 unicode 来解决这个问题:
return unicode(self.transtype)
不过,你可能应该选择一个更好的字符串来表示你的数据:因为会有很多 Trans 对象具有相同的 TransType,所以你的 unicode 字符串应该能够区分它们,或许可以通过显示脚本字段来实现。
4
我找到了答案。现在一切都正常了。
Views.py:
def displaytrans(request):
TransType.objects.all()
info = TransType.objects.all()
info2 = Trans.objects.all()
print info
bookdata = { "detail" : info, "details" : info2 }
print bookdata
resp = render_to_response("account/displaytrans.html", bookdata, context_instance=Context(request))
return resp
displaytrans.html:
<!doctype html>
<html>
<body>
<table border="1" style="width:800px">
<tr>
<td> {% for s in details %} </td>
<td> {{ s.script }} </td>
</tr>
<tr>
<td> {{ s.transtype_id}} </td>
{% endfor %}
</tr>
</table>
</body>
</html>
url.py:
url(r'^displaytrans/$', 'booki.account.views.displaytrans', name='displaytrans'),