Tôi đang gặp sự cố khi sử dụng {% ifequal s1 "một số văn bản"%} để so sánh các chuỗi với các ký tự mở rộng trong các mẫu Django. Khi chuỗi s1 chứa các ký tự ascii> 127, tôi nhận được ngoại lệ trong việc hiển thị mẫu. Tôi đang làm gì sai? Tôi đang sử dụng mã hóa UTF-8 trong suốt phần còn lại của ứng dụng trong cả dữ liệu, mẫu và mã Python mà không gặp bất kỳ vấn đề gì.Sự cố với mã hóa trong các mẫu Django
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 %}
Output
s1=dados
s2=aprovação
s1="dados" is true