Python 从 django 数据库中检索数据并显示在表中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23180762/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:25:43  来源:igfitidea点击:

To retrieve data from django database and display in table

pythondjangosqlite

提问by user1862399

I am trying to retrieve data from db in django. I want to display it in a table. I am getting an error as:\

我正在尝试从 django 中的 db 检索数据。我想在表格中显示它。我收到如下错误:\

coercing to Unicode: need string or buffer, TransType found

强制转换为 Unicode:需要字符串或缓冲区,找到 TransType

There are two models in my Models.py file:

我的 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`

My views.py file

我的 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))

My url.py file

我的 url.py 文件

url(r'^updatetrans/$', 'booki.account.views.updatetrans', name='updatetrans'),

My updatetrans.html file

我的 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>

Plz help....

请帮忙....

Traceback

追溯

Environment: Request Method: GET

环境:请求方式: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

回答by Daniel Roseman

The traceback shows that the error is coming in your Trans model's __unicode__method. As the error says, you need to actually return unicode from that method, but you are returning the related TransType.

回溯显示错误出现在您的 Trans 模型的__unicode__方法中。正如错误所说,您实际上需要从该方法返回 unicode,但您正在返回相关的 TransType。

You could fix this by explicitly converting to unicode in that method:

您可以通过在该方法中显式转换为 unicode 来解决此问题:

return unicode(self.transtype)

but you should probably pick a better string representation of your data: there are going to be many Trans objects with the same TransType, so your unicode should distinguish between them, perhaps by also showing the script field.

但是您可能应该为您的数据选择更好的字符串表示形式:将有许多具有相同 TransType 的 Trans 对象,因此您的 unicode 应该区分它们,也许还显示脚本字段。

回答by user1862399

I got the answer. It is working fine now.

我得到了答案。它现在工作正常。

Views.py:

视图.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:

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:

网址.py:

url(r'^displaytrans/$', 'booki.account.views.displaytrans', name='displaytrans'),