【问题标题】:Problem with encoding in Django templatesDjango模板中的编码问题
【发布时间】:2010-10-03 19:35:32
【问题描述】:

我在使用 {% ifequal s1 "some text" %} 将字符串与 Django 模板中的扩展字符进行比较时遇到问题。当字符串 s1 包含 >127 的 ascii 字符时,我在模板渲染中遇到异常。我究竟做错了什么?我在数据、模板和 Python 代码的其余应用程序中使用 UTF-8 编码,没有任何问题。

views.py

def test(request):
    return render_to_response("test.html", {
                                            "s1": "dados",
                                            "s2": "aprovação",
                                            }
                              )

test.html

s1={{s1}}<br>
s2={{s2}}<br>

{% ifequal s1 "dados" %}
  s1="dados" is true
{% endifequal %}

{% ifequal s1 "aprovação" %}
  s1="aprovação" is true
{% endifequal %}

{% comment %}
The following two comparions cause the following exception:
Caught an exception while rendering: 'ascii' codec can't decode byte 0xc3 in position 6: ordinal not in range(128)

{% ifequal s2 "dados" %}
  s2="dados" is true
{% endifequal %}

{% ifequal s2 "aprovação" %}
  s2="aprovação" is true
{% endifequal %}
{% endcomment %}

{% ifequal s2 u"dados" %}
  s2="dados" is true
{% endifequal %}

{% comment %}
The following comparison causes the following exception:
Caught an exception while rendering: 'ascii' codec can't encode characters in position 8-9: ordinal not in range(128)
{% ifequal s2 u"aprovação" %}
  s2="aprovação" is true
{% endifequal %}
{% endcomment %}

输出

s1=dados
s2=aprovação
s1="dados" is true 

【问题讨论】:

    标签: python django unicode internationalization django-templates


    【解决方案1】:

    有时没有什么比向其他人描述问题来帮助您解决问题更重要的了。 :) 我应该像这样将 Python 字符串标记为 Unicode,现在一切正常:

    def test(request):
        return render_to_response("test.html", {
                                                "s1": u"dados",
                                                "s2": u"aprovação",
                                                }
                                  )
    

    【讨论】:

      猜你喜欢
      • 2017-10-24
      • 2012-05-14
      • 1970-01-01
      • 2018-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-16
      相关资源
      最近更新 更多