I'm having problems using {% ifequal s1 "some text" %} to compare strings with extended characters in Django templates. When string s1 contains ascii characters >127, I get exceptions in the template rendering. What am I doing wrong? I'm using UTF-8 coding throughout the rest of application in both the data, templates and Python code without any problems.
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
What does {{ name }} this mean in Django Templates? Django. It will be displayed as name in HTML. The name will be replaced with values of Python variable. {{ name }} will be the output.
Django TemplateDoesNotExist error means simply that the framework can't find the template file. To use the template-loading API, you'll need to tell the framework where you store your templates. The place to do this is in your settings file ( settings.py ) by TEMPLATE_DIRS setting.
For example, you can check if my_textfield contains a script tag. If so, mark the instance as malicious and return an escaped version of my_textfield (the normal Django behavior). Otherwise, use mark_safe to return your HTML code marked as safe.
If you define a __unicode__() method, Django will call it when it needs to render an object in a context where a string representation is needed (e.g. in the model's admin pages). The documentation says: The __unicode__() method is called whenever you call unicode() on an object.
Sometimes there's nothing like describing a problem to someone else to help you solve it. :) I should have marked the Python strings as Unicode like this and everything works now:
def test(request):
return render_to_response("test.html", {
"s1": u"dados",
"s2": u"aprovação",
}
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With