【问题标题】:django format_html not working with unicodedjango format_html 不适用于 unicode
【发布时间】:2014-11-13 22:55:46
【问题描述】:
我在 django 中使用 format_html(..) 函数。当我使用重音等特殊字符时,它会失败。有没有办法使用带有特殊字符的 format_html(..)?
我找到的解决方案是:
format_html('<label>{0}</label>', smart_text(classes).encode('ascii', 'ignore'))
但它只删除特殊字符。
【问题讨论】:
标签:
python
django
unicode
【解决方案1】:
如果您传递任何 unicode 参数,则格式字符串必须是 unicode。如果格式字符串为 ASCII,则所有参数也必须为 ASCII。
这是python的str.format()方法的要求,format_html()使用。
所以在字符串前面加上u,使它成为一个unicode字符串:
u'<label>{0}</label>'
在您的代码中是:
format_html(u'<label>{0}</label>', smart_text(classes))
【解决方案2】:
正确的解决方案是像 Django 一样使用from __future__ import unicode_literals,或者在unicode 上调用.format,而不是在str 上调用。
【解决方案3】:
试试
format_html(u'<label>{0}</label>', smart_text(classes))
我相信这就是 Krzysztof Szularz 在他的第二个建议中的意思。