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.


Asked by: Emily515 | Posted: 06-12-2021






Answer 1

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 = (('$', '$'), 
              ('£', '£'), 
              ('€', '€')) 

Answered by: Maya874 | Posted: 07-01-2022



Similar questions

python - Send mass mail in Django -- Too many values to unpack

I'm experimenting with Django's mass_mail function. The code below keeps raising a "Too Many Values to Unpack" error, and I can't figure out why. I'm following the docs (https://docs.djangoproject.com/en/1.5/topics/email/#send-mass-mail) which seem pretty straightforward--what am I doing wrong? If it matters, the send-email a...


python - Django urls with empty values

I have a django app where i am making calls to the api as follows: (api.py) class studentList(APIView): def get(self, request, pk, pk2, format=None): student_detail = Student.objects.filter(last_name = pk, campus_id__name = pk2) serialized_student_detail = studentSerializer(student_detail, many=True) return Response(serialized_student_detail.data) a...


python - django get values from a model field

I have model : class Question(models.Model): user = models.ForeignKey(User) title = models.CharField(max_length=120) description = models.TextField() category = models.ForeignKey('Category') answers = models.ManyToManyField('Answer',related_name='answer_name', blank=True) post_date = models.DateTimeField(auto_now=True) published = models.BooleanField(default=False) vote = mod...


python - django get json values

Hello i get json data back and would like to get the key, value pairs but i have been unable to do so. I work with python 3.4 and Django 1.8. Would someone please help me to get the key, value pairs? for example i would like to access all of the values inside Value only from page_fans_add_unique r = requests.get('https://graph.facebook.com/v2.3/some/insights?access_token='+access_token.token) c...


python - Django Q set too many values to unpack

I am new to django and trying to filter multiple fields that contain text. columns = ['ticketId', 'checkSum'] q_objects = [Q(fieldname +'__contains', myString) for fieldname in columns] objects = objects.filter(reduce(operator.or_, q_objects)) I get Exception Type: ValueError Exception Value: too many values to unpack on the "filter" last line. Any ideas


python - Which django form field type should I use for an array of values?

I'm receiving an array of up to N uuid4 values in the POST data for a SPA. I'm then supposed to be feeding into a view that deletes the specified object instances: &lt;QueryDict: {'uuids[]' : [ 'a1a241bd-147f-4672-86d7-1a6225b8080e' '791db3f0-5134-4927-b328-347c7261d7f6' 'b8087a1b-710e-47b4-af5a-bae4d5e30532' '6d1a96b2-1b99-4707-a8e3-376a0d596d95' ... ]}&gt; As far as I...


Python - Django - Sum values of a list, too slow

I have a Django project I use to show energy consumptions of a certain time period. I use the following code in order to obtain the data from the database: consumptions = Measurement.objects.filter(idhouse=house) filtered = consumptions.values_list("cost",flat=True).filter(enddatetimestamp__gt=startdate,enddatetimestamp__lte=enddate) total = sum(filtered) I obtain a list of 9000 values, bu...


python - django too many values to unpack error

i have stored a list in django and now i want to convert that list to query set . ques=list(sorted(Upload.objects.filter(unique_id=tdetail), key=lambda x: random.random())) platform=Platform() platform.user=request.user platform.test_key=article platform.list=ques platform.save() ques is the list which i have stored in database.. it is the list of questions in random...


python - In Django, how to filter a model using a list of values but each value can be used only once?

(Scroll down for updates.) I'm new to Django. I'm using Mezzanine 4.2.3 (Django 1.10.8 under the hood according to requirements.txt). I have a Postgres database of details about movies. I want to display 10 movies on a page. I have 2 issues: Each movie must be from a different country. So far, I can only get a list of 10 random countries from a larger list. I don't know how to use .ob...


python - Django - Form Does Not Save User Values

I currently have a form on the “myaccount.html” page of my web application. This form renders how I want however I cannot submit the form values for some reason to appear in the django admin. When a user hits “submit”, the page refreshes and the values stay in the input fields. I’ve tried many methods to solve this but no luck. I thought I had everything together but maybe I’m missing something so...


python - How to use temp table count values into into the where query in Django Raw Sql?

I need to use raw sql in my django project. I'm using count command and then I associated it with as command like "the_count" but i got an error. The error like this, the_count does not exist. And my my code here, # First Model class AModel(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_lenth=100) # Second Model class BModel(models.Model): ...


python - Django HTML can't read the values of the dict

When I pass a simple dict (myDict = {&quot;key&quot;: &quot;value&quot;}) throught render to html, it creates an error as the html can't read the values of the dict .. {{ myDict[&quot;key&quot;] }} &lt;!--- prompts an error--&gt; django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '['key']' from 'myDict['key']' Why didn't I pass the...


python - django check values if they are empty

All fields have values, however, the app is redirected to the first if condition('Fields are empty!'). If I remove the condition the form is submitted. What am I missing here? Any help is appreciated, thank you! def application(request): if request.method == 'POST': name = request.POST['name'] surname = request.POST['surname'] email = request.POST['email'] address = reques...


python - Django count and store values in models

I have multiple Models which look like this: class Classes(models.Model): User = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) A1 = models.IntegerField(default=0) B1 = models.IntegerField(default=0) etc A2 = models.IntegerField(default=0) B2 = models.IntegerField(default=0) etc A3 = models.IntegerField(default=0) B3 = models.IntegerField(default=0) etc A4 = models.IntegerField(default=0) B4 =...


python - Django -vs- Grails -vs-?

I'm wondering if there's such a thing as Django-like ease of web app development combined with good deployment, debugging and other tools? Django is a very productive framework for building content-heavy sites; the best I've tried and a breath of fresh air compared to some of the Java monstrosities out there. However it's written in Python which means there's little real support in the way of deployment/packaging,...


python - Django Admin app or roll my own?


python - In Django how do i return the total number of items that are related to a model?

In Django how can i return the total number of items (count) that are related to another model, e.g the way stackoverflow does a list of questions then on the side it shows the count on the answers related to that question. This is easy if i get the questionid, i can return all answers related to that question but when am displaying the entire list of question it becomes a bit tricky to display on the side the cou...


python - Valid use case for django admin?

I want to build a django site where a certain group of trusted users can edit their profile information. Does it make sense to have each trusted user go through the django admin interface? I'd only want them to be able to see and edit their own information (obviously). It doesn't seem like this fits the way the django people define "trust", especially the bolded bit... From


python - Django "Did you mean?" query

I am writing a fairly simple Django application where users can enter string queries. The application will the search through the database for this string. Entry.objects.filter(headline__contains=query) This query is pretty strait forward but not really helpful to someone who isn't 100% sure what they are looking for. So I expanded the search. from django.utils import stopw...


python - How to query as GROUP BY in django?

I query a model: Members.objects.all() And it returns: Eric, Salesman, X-Shop Freddie, Manager, X2-Shop Teddy, Salesman, X2-Shop Sean, Manager, X2-Shop What I want is to know the best Django way to fire a group_by query to my database, like: Members.objects.all().group_by('designation') Which doesn't work, of ...


python - group by in django

How can i create simple group by query in trunk version of django? I need something like SELECT name FROM mytable GROUP BY name actually what i want to do is simply get all entries with distinct names.


python - Why does Django only serve files containing a space?

I'm writing a basic Django application. For testing / development purposes I'm trying to serve the static content of the website using Django's development server as per http://docs.djangoproject.com/en/dev/howto/static-files/#howto-static-files. My urls.py contains: (r'^admin/(.*)...


python - Django forms

I had asked a question pertaining to this. But I think it would be better to ask my question directly. I have a "User" table with manytomany relationship with two other tables "Domain" and "Groups". So in the admin interface I see the Groups and Domains as 2 ModelMultipleChoiceFields. But I want to present them on the UI in a more user friendly way. I would like to show each available choice in Domain and Group with a chec...


python - How to chain views in Django?

I'm implementing James Bennett's excellent django-contact-form but have hit a snag. My contact page not only contains the form, but also additional flat page information. Without rewriting the existing view the contact form uses, I'd like to be able to wrap, o...


python - What's the best Django search app?


How can I use a DLL file from Python?

What is the easiest way to use a DLL file from within Python? Specifically, how can this be done without writing any additional wrapper C++ code to expose the functionality to Python? Native Python functionality is strongly preferred over using a third-party library.


python - PubSub lib for c#

Is there a c# library which provides similar functionality to the Python PubSub library? I think it's kind of an Observer Pattern which allows me to subscribe for messages of a given topic instead of using events.


python - What is the best way to copy a list?

This question already has answers here:


python - Possible Google Riddle?

My friend was given this free google website optimizer tshirt and came to me to try and figure out what the front logo meant. t-shirt So, I have a couple of guesses as to what it means, but I was just wondering if there is something more. My first guess is that eac...


How do you check whether a python method is bound or not?

Given a reference to a method, is there a way to check whether the method is bound to an object or not? Can you also access the instance that it's bound to?


ssh - How to scp in Python?

What's the most pythonic way to scp a file in Python? The only route I'm aware of is os.system('scp "%s" "%s:%s"' % (localfile, remotehost, remotefile) ) which is a hack, and which doesn't work outside Linux-like systems, and which needs help from the Pexpect module to avoid password prompts unless you already have passwordless SSH set up to the remote host. I'm aware of Twisted'...


python - How do I create a new signal in pygtk

I've created a python object, but I want to send signals on it. I made it inherit from gobject.GObject, but there doesn't seem to be any way to create a new signal on my object.


python - What do I need to import to gain access to my models?

I'd like to run a script to populate my database. I'd like to access it through the Django database API. The only problem is that I don't know what I would need to import to gain access to this. How can this be achieved?


python - How do I edit and delete data in Django?

I am using django 1.0 and I have created my models using the example in the Django book. I am able to perform the basic function of adding data; now I need a way of retrieving that data, loading it into a form (change_form?! or something), EDIT it and save it back to the DB. Secondly how do I DELETE the data that's in the DB? i.e. search, select and then delete! Please show me an example of the code ...






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top