5

{% ifequal s1 "some text" %} を使用して、Django テンプレートで文字列を拡張文字と比較する際に問題が発生しています。文字列 s1 に 127 を超える ASCII 文字が含まれている場合、テンプレートのレンダリングで例外が発生します。私は何を間違っていますか?データ、テンプレート、Python コードの両方で、残りのアプリケーション全体で UTF-8 コーディングを問題なく使用しています。

ビュー.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 
4

1 に答える 1

8

問題を解決するために、他の人に問題を説明するのに勝るものがない場合があります。:) Python 文字列を次のように Unicode としてマークする必要があり、すべてが機能するようになりました。

def test(request):
    return render_to_response("test.html", {
                                            "s1": u"dados",
                                            "s2": u"aprovação",
                                            }
                              )
于 2009-01-27T17:29:17.833 に答える