Search code examples
djangounicodeutf-8asciiadmin

UnicodeEncodeError at /admin/ in Django app


I get the following error at the admin pages when I try to view the list of existing objects.

UnicodeEncodeError at /admin/character/charlevel/

'ascii' codec can't encode character u'\xd6' in position 0: ordinal not in range(128)

Request Method:     GET
Request URL:    http://127.0.0.1:8000/admin/character/charlevel/
Django Version:     1.4.1
Exception Type:     UnicodeEncodeError
Exception Value:    

'ascii' codec can't encode character u'\xd6' in position 0: ordinal not in range(128)

Exception Location:     /home/***/workspace/***/***/character/models.py in __unicode__, line 413
Python Executable:  /usr/bin/python
Python Version:     2.7.3

This occurs when I open the object list of this class:

class CharLevel(models.Model):
    char = models.ForeignKey(Character)
    prof = models.ForeignKey(Profession)
    level = models.SmallIntegerField()

    def __unicode__(self):
        return ('{c}/{l}/{p}'.format(c=self.char.name, l=self.level, p=self.prof )).encode('utf-8')

The issue disappear if I remove the {c} component of the string format

However this problem does not occur for the class Charater with the following __unicode__:

class Character(models.Model):
    name = models.CharField(max_length=32)
    def __unicode__(self):
        return self.name

What have I done wrong?


Solution

  • __unicode__ should return unicode:

    def __unicode__(self):
        return u'{c}/{l}/{p}'.format(c=self.char.name, l=self.level, p=self.prof)