Django模板中的编码问题

use*_*478 5 python django unicode django-templates internationalization

我在使用{%ifequal s1"某些文本"%}时遇到问题,以便在Django模板中比较字符串和扩展字符.当字符串s1包含> 71的ascii字符时,我在模板渲染中得到异常.我究竟做错了什么?我在数据,模板和Python代码中的其余应用程序中使用UTF-8编码没有任何问题.

views.py

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

的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 %}
Run Code Online (Sandbox Code Playgroud)

产量

s1=dados
s2=aprovação
s1="dados" is true 
Run Code Online (Sandbox Code Playgroud)

use*_*478 8

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

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