代码之家  ›  专栏  ›  技术社区  ›  luc

在Django管理中保存对象时出现Unicode错误

  •  3
  • luc  · 技术社区  · 16 年前

    在我的django应用程序中,我有一些对象会导致django管理中相应的URL不是ASCII。(例如: http://mysite/admin/myapp/myclass/Présentation/ )

    我可以毫无问题地编辑对象,但保存对象时出现以下错误:

    UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 24: ordinal not in range(128), HTTP response headers must be in US-ASCII format

    奇怪的是,对象被正确地保存到数据库中。

    有人知道django管理员如何管理unicode吗?任何有助于解决这个问题的信息、指针或想法都会受到赞赏。

    提前谢谢

    更新:这是模型的代码

    class Plugin(models.Model):
        """Some subcontent that can be added to a given page"""
        class Meta:
            ordering = ['ordering']
    
        name = models.CharField(max_length=32, primary_key=True)
        div_id = models.CharField(default='rightcol', max_length=32)
        published = models.BooleanField(default=True,
            help_text=_("If this is not checked, it is not displayed on the page."))
        ordering = models.IntegerField(default=1,
            help_text=_("plugins are sorted with this number in ascending order"))
        content = models.TextField(blank=True)
        registration_required = models.BooleanField(_('registration required'),
            help_text=_("If this is checked, only logged-in users will be able to view the page."))
    
        def __unicode__(self):
            return u"%s -- %s" % (self.name, self.div_id)
    

    更新: 很明显,不建议在URL中使用非ASCII字符。这就是我问题的原因,我已经改变了。

    有人知道django管理员使用什么来构建对象的URL吗?我想这是钥匙。对吗?有没有办法强迫姜戈使用其他东西并安全地取回物体?

    4 回复  |  直到 10 年前
        1
  •  6
  •   Clash    16 年前

    我很确定你的数据库可能使用的是拉丁语编码。Django假设所有内容都设置为Unicode(UTF8)。

    要查看此信息,请进入mysql shell并键入:

    mysql> show variables like 'char%';
    

    如果你看到一堆拉丁语1(或任何其他非UTF8编码,除了二进制编码),你必须这样做: 打开my.cnf并查找 [mysqld] 部分。 确定后 tmpdir = /tmp ,您有以下行:

    default-character-set=utf8
    collation_server=utf8_unicode_ci
    character_set_server=utf8
    skip-external-locking
    skip-character-set-client-handshake
    

    重新启动服务器。

    您必须重新创建或手动编辑所有数据库和表的编码,更改my.cnf只会影响将要创建的数据库。

    希望我能帮上忙。

    编辑:顺便问一下,你在哪一个版本的姜戈?似乎这是1.1上修复的错误: http://code.djangoproject.com/ticket/10267

        2
  •  2
  •   Iman Mirzadeh    10 年前

    This link 救了我的一天
    您必须在 模特儿 :

    class MyModel (models.Model):
        some_field = models.CharField(max_length=1000)
        def __unicode__(self):
            return u'%s'%(self.some_field)
    

    可能还有其他问题,如: 您的系统编码不是UTF8 , 数据库编码不是utf8 还有…在提供的链接中提到!

        3
  •  1
  •   PirosB3    16 年前

    在你的模型中,你试过

    class Model(models.Model):
       def __unicode__(self):
           return self.name ## having a model object named "name"
    

    不确定这是否是你想要的答案,但你试过了吗?

        4
  •  0
  •   luc    16 年前

    我现在使用默认ID作为模型中每个类的主键。因此,从管理站点访问对象时,URL中没有禁止的字符。

    在大多数情况下,我建议将默认ID保留为主键