【问题标题】:error in view python django视图中的错误 python django
【发布时间】:2014-08-04 07:53:53
【问题描述】:
def projectDetail(request):
    data = {'error':''}
    projects = Project.objects.all()
    if len(projects) == 0:
        data['error']='NO Project Information Available'
        html ="<html><body>%s</body></html>"%data['error']
        return HttpResponse(html)
    project = projects[0]
    html ="<html><body><ul>Project Description \
              <li>Project Name:"+project.name+"</li>\
              <li>Project Phase:"+ project.phase+"</li>\
              <li>Project City: "+ project.city+"</li>\
              <li>Project Description:"+project.description+"</li>\
              <li>Builder Name:"+ project.builders.all()[0].name+"</li>\
              <li>Builder Description:"+ project.builders.all()[0].description+"</li>\
              <li>Builder Type:"+ project.builders.all()[0].builder_type.name+"</li>\
              </ul></body></html>"
    return HttpResponse(html)

这是我的代码,当我请求这个视图时,我得到了错误:

Exception Type: TypeError
Exception Value:    
coercing to Unicode: need string or buffer, City found

解决办法是什么

【问题讨论】:

    标签: python django unicode views


    【解决方案1】:

    该错误将来自此行:

    <li>Project City: "+ project.city+"</li>\
    

    您可能需要在 City 模型上添加 __str____unicode__ 方法。

    也就是说——你真的不应该建立这样的 HTML 响应——改用Django's template enginePart 3 of the Django tutorial 可能会帮助您从这里开始。

    【讨论】:

      【解决方案2】:
       projects = Project.objects.all()
      

      它是一个迭代器对象,您需要对其进行迭代才能获得项目详细信息。 对于项目中的项目: 项目.city 项目.你的领域

      如果city是不同的表或关系键,则需要定义

       def __str__(self):     # for django 2.* version    
           return self.name 
      

      def __unicode__(self):
           return self.name       # for django 3.* version 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-09-29
        • 2020-06-11
        • 2010-09-22
        • 1970-01-01
        • 2021-12-08
        • 2012-05-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多