我在Django中遇到错误Caught TypeError while rendering: sequence item 1: expected string or Unicode, Property found
。这是我的代码:
def __unicode__( self ) :
return "{} : {}".format( self.name, self.location )
我甚至尝试过
def __unicode__( self ) :
return unicode( "{} : {}".format( self.name, self.location ) )
但同样的错误。
据我所知"this is x = {}".format( x )
返回一个字符串对吗?为什么Python说它是属性?
完整代码:
class Item( models.Model ) :
def __unicode__( self ) :
return "{} : {}".format( self.name, self.location )
name = models.CharField( max_length = 135 )
comment = models.TextField( blank = True )
item_type = models.ForeignKey( ItemType )
location = models.ForeignKey( Location )
t_created = models.DateTimeField( auto_now_add = True, verbose_name = 'created' )
t_modified = models.DateTimeField( auto_now = True, verbose_name = 'modified' )
class Location( models.Model ) :
def __unicode__( self ) :
locations = filter( None, [ self.room, self.floor, self.building ] )
locations.append( self.prop )
return ", ".join( locations ) # This will look in the form of like "room, floor, building, property"
comment = models.TextField( blank = True )
room = models.CharField( max_length = 135, blank = True )
floor = models.CharField( max_length = 135, blank = True )
building = models.CharField( max_length = 135, blank = True )
prop = models.ForeignKey( Property )
t_created = models.DateTimeField( auto_now_add = True, verbose_name = 'created' )
t_modified = models.DateTimeField( auto_now = True, verbose_name = 'modified' )
class Property( models.Model ) :
def __unicode__( self ) :
return self.name
name = models.CharField( max_length = 135 )
答案 0 :(得分:1)
Property
不是指Python属性,而是指Property
类。可能发生的是:
Item.__unicode__
被召唤。self.name
和self.location
。self.name
从__unicode__
方法返回一个unicode字符串。self.location
是外键,因此Location.__unicode__
会被调用。self.room
,self.floor
和self.building
,它们都有__unicode__
方法返回unicode字符串。filter
发现这些字符串都是空的,因此locations
设置为[]
。self.prop
,Property
,附加到locations
。", ".join( locations )
引发TypeError
,因为Property
不是字符串。str.format
中的Item.__unicode__
电话会捕获该异常,并自行投放,这就是您所看到的。解决方案:更改
locations.append( self.prop )
到
locations.append( unicode(self.prop) )
道德:str.format
在其参数上调用str()
,但str.join
没有。{/ p>
答案 1 :(得分:0)
你试过吗?:
def __unicode__( self ):
return "{name}: {location}".format(name=self.name, location=self.location)
或
def __unicode__( self ):
return "{0}: {1}".format(self.name, self.location)
或
def __unicode__( self ):
return "%s: %s" % (self.name, self.location)
希望有所帮助:)