Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Form values without HTML escape

I need to set the Django forms.ChoiceField to display the currency symbols. Since django forms escape all the HTML ASCII characters, I can't get the $ ( ) or the £ ( £ ) to display the currency symbol.

<select id="id_currency" name="currency">
    <option value="&amp;#36;">&#36;</option>
    <option value="&amp;pound;">&pound;</option>
    <option value="&amp;euro;">&euro;</option>
</select>

Could you suggest any methods to display the actual HTML Currency character at least for the value part of the option?

<select name="currency" id="id_currency">
    <option value="&amp;#36;">$</option>
    <option value="&amp;pound;">£</option>
    <option value="&amp;euro;">€</option>
</select>

Update: Please note I use Django 0.96 as my application is running on Google App Engine.
And the <SELECT> above is rendered using Django Forms.

currencies = (('&#36;', '&#36;'), 
              ('&pound;', '&pound;'), 
              ('&euro;', '&euro;'))    
currency = forms.ChoiceField(choices=currencies, required=False)

Thanks,
Arun.

like image 433
asp Avatar asked Jan 23 '23 16:01

asp


1 Answers

You can use "safe" in the template or "mark_safe" in the view, turn off autoescaping in the template, or use Unicode characters instead of HTML entities in your form.

Using mark_safe

from django.utils.safestring import mark_safe

currencies = ((mark_safe('&#36;'), mark_safe('&#36;')), 
              (mark_safe('&pound;'), mark_safe('&pound;')), 
              (mark_safe('&euro;'), mark_safe('&euro;')))    

Using autoescape off

As an alternative in your template you can turn off escaping for a block of code. Everything between tags {% autoescape off %} and {% endautoescape %} will not be escaped.

Using Unicode characters

When nothing else works try the following. In the file that contains your currencies tuple put the following line as the very first or second line:

# coding=utf-8

and then in your currencies tuple put the actual unicode characters:

currencies = (('$', '$'), 
              ('£', '£'), 
              ('€', '€')) 
like image 156
Sergey Golovchenko Avatar answered Jan 26 '23 05:01

Sergey Golovchenko