Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable HTML escaping in Django's TextField

How can I turn off Django's automatic HTML escaping, when I write into model's TextField?

like image 788
evgeniuz Avatar asked Jan 17 '10 09:01

evgeniuz


People also ask

How do you turn off Django's automatic HTML escaping?

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.

What is Autoescape in Django?

autoescape. Controls the current auto-escaping behavior. This tag takes either on or off as an argument and that determines whether auto-escaping is in effect inside the block. The block is closed with an endautoescape ending tag.


2 Answers

Just use django's safe filter. In your template you would do something like this:

{{ instance.my_text_field|safe }} 
like image 139
bjunix Avatar answered Oct 14 '22 20:10

bjunix


One way to do it is to put a function in your model which returns the data marked as safe:

from django.utils.safestring import mark_safe   class MyModel(models.Model):      my_textfield = models.TextField()      def display_my_safefield(self):          return mark_safe(self.my_textfield) 

Then in the template you would have to use:

{{ instance.display_my_safefield }} 
like image 25
Daniel Vassallo Avatar answered Oct 14 '22 21:10

Daniel Vassallo