开发者

model.__unicode__() returning russian string cause TemplateSyntaxError

开发者 https://www.devze.com 2022-12-21 10:37 出处:网络
code: class Gallery(models.Model): title = models.CharField(max_length=100) description = models.TextField(blank=True)

code:

class Gallery(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField(blank=True)
    created = models.DateField(auto_now_add=T开发者_开发技巧rue)    
    class Meta:
        verbose_name = 'галерея'
        verbose_name_plural = 'галереи'
    def __unicode__(self):
        return 'Галерея %s' % self.title

error:

TemplateSyntaxError at /admin/galleries/gallery/
Caught an exception while rendering: ('ascii', '\xd0\x93\xd0\xb0\xd0\xbb\xd0\xb5\xd1\x80\xd0\xb5\xd1\x8f ', 0, 1, 'ordinal not in range(128)')

what should I do?


Try

return u'Галерея %s' % self.title


Because self.title is a unicode string and your string literal is not (its type is str), when Python executes the expression 'Галерея %s' % self.title, it needs to coerce the string literal into unicode before performing the interpolation. It needs a character encoding to do this, and by default resorts to ASCII, which can encode less than 128 different characters.

To avoid this problem, use a unicode string literal : u'Галерея %s'. When in doubt, your strings should be unicode strings, especially in Django.


to avoid errors like this, put it at the beginning of your file

# -*- coding: utf-8 -*-
0

精彩评论

暂无评论...
验证码 换一张
取 消