Search code examples
pythondjangopython-unicodekeyerror

unicode string format misterious KeyError. What's wrong?


I have the following code at the unicode representation of a django models.Model:

def __unicode__(self):
    if self.right:
        return u"{left} ({left_score}) | {right} ({right_score})".format({
            'left': self.left, 
            'left_score': self.left_score, 
            'right': self.right, 
            'right_score': self.right_score,
        })
    else:
        return "%s" % self.left

I get

Exception Type: KeyError
Exception Value: u'left'

I also tried using unicode keys in the dictionary. self.left is not None.
I have read lots of forums still can't figure out what I am doing wrong. :(

How can I fix this?


Solution

  • The format method requires you to pass your arguments as kwargs, not as a dictionary.

    def __unicode__(self):
        if self.right:
            return u"{left} ({left_score}) | {right} ({right_score})".format(
                left=self.left, 
                left_score=self.left_score, 
                right=self.right, 
                right_score=self.right_score,
            )
        else:
            return "%s" % self.left