I am getting an error in Django saying Caught TypeError while rendering: sequence item 1: expected string or Unicode, Property found. Here is my code:
def __unicode__( self ) :
return "{} : {}".format( self.name, self.location )
I even tried
def __unicode__( self ) :
return unicode( "{} : {}".format( self.name, self.location ) )
but the same error.
From what I know "this is x = {}".format( x ) returns a string right? Why is Python saying it’s a Property?
Full code:
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 )
Propertyisn’t referring to a Python property, but to yourPropertyclass. What’s probably happening is this:Item.__unicode__gets called.self.nameandself.location.self.namereturns a unicode string from its__unicode__method.self.locationis a foreign key, soLocation.__unicode__gets called.self.room,self.floor, andself.building, which all have__unicode__methods that return unicode strings.filtersees that these strings are all empty, solocationsis set to[].self.prop, which is aProperty, gets appended tolocations.", ".join( locations )Throws aTypeErrorbecause aPropertyisn’t a string.str.formatcall inItem.__unicode__catches that exception and throws its own, which is what you see.Solution: change
to
Moral:
str.formatcallsstr()on its arguments, butstr.joindoes not.