Sunday, May 1, 2011

Django Form values without HTML escape.

Hi,

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.

From stackoverflow
  • You can use "safe" in the template or "mark_safe" in the view

    update

    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;')))
    

    update 2

    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.

    update 3

    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 = (('$', '$'), 
                  ('£', '£'), 
                  ('€', '€'))
    
    Arun Shanker Prasad : Hi, Thanks for the quick reply. But I don't how either of this can be applied in the case of django Forms. To Add: I should have mentioned that I use Django 0.96 as my application runs on Google's App Engine.
    Arun Shanker Prasad : Hi, Thanks again for the reply. I use Django 0.96 as my application runs on Google's App Engine. As far as I can understand django.utils.safestring was introduced after 0.96
    Arun Shanker Prasad : Hi, Thanks for that. But again the problem will be the version of Django I am using 0.96. I think only Django 1.0 has the "autoescape" tag. It's times like these I wish I had Django 1.0. But changing the version now will be a very large overhead, since I am in Google App Engine.
    Arun Shanker Prasad : Thanks umnik700 "update 3" worked great.
    : You are welcome I am glad it helped.

0 comments:

Post a Comment