问题描述
在我的 django 应用程序中,我有一些对象导致 django admin 中的相应 URL 不是 ascii.(例如:http://mysite/admin/myapp/myclass/Présentation/
)
In my django app, I have some objects that cause the corresponding URL in the django admin to be non ascii. (for example: http://mysite/admin/myapp/myclass/Présentation/
)
我可以毫无问题地编辑对象,但是当我保存它时出现以下错误:
I can edit the object without any problem but when I save it I have the following error:
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
奇怪的是对象被正确保存到数据库中.
The strange thing is that the object is correctly saved into the database.
有人知道 Django 管理员是如何管理 unicode 的吗?任何可以帮助解决此问题的信息、指针或想法将不胜感激.
Does anybody know how the Django admin manages unicode? Any info, pointer or idea that can help to fix this problem would be appreciated.
提前致谢
更新:这是模型的代码
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 字符.这就是我的问题的原因,我已经改变了它.
Update: That's clear that non-ascii character are not recommended in an URL. That's the cause of my problem and I have changed that.
有人知道 Django 管理员使用什么来构建对象的 URL.我猜它是主键.这样对吗?有没有办法强制 Django 使用其他东西并安全地检索对象?
Does anybody know what is used by the Django admin to build the URL of an object. I guess that it is the primary key. Is it right? is there a way to force Django to use something else and to retrieve the object safely?
推荐答案
我现在使用默认 id 作为模型每个类的主键.因此,从管理站点访问对象时,我的 url 中没有禁止字符.
I am now using the default id as primary key for every class of my model. As a consequence, I don't have forbidden characters in the url when accessing objects from the admin site.
我建议在大多数情况下保留默认 id 作为主键
I do recommend to keep the default id as primary key in most cases
这篇关于在 django admin 中保存对象时出现 unicode 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!