How can I turn off Django's automatic HTML escaping, when I write into model's TextField?
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.
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.
Just use django's safe filter. In your template you would do something like this:
{{ instance.my_text_field|safe }}
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 }}
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