Disable HTML escaping in Django's TextField
How开发者_StackOverflow can I turn off Django's automatic HTML escaping, when I write into model's TextField?
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 }}
I think the better way to do it is as @Daniel Vassallo described.
Why?
Because this way, you can do some security operations on the HTML code that you want to display without escaping, particularly to protect against cross site scripting (XSS).
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.
Here:
from django.utils.safestring import mark_safe
class MyModel(models.Model):
my_textfield = models.TextField()
is_malisious = models.BooleanField(default=False)
def display_my_safefield(self):
if '<script>' in self.my_textfield:
self.is_malicious = True
self.save()
return self.my_textfield
return mark_safe(self.my_textfield)
And all of this doesn't need any migrations to the database.
Alternative approach
I think that you can do this security operation by overriding the save()
method of your model, and including the check and any other necessary operation against malicious content inside of it. Then, you might use @bjunix solution if you ensured that any saved content is safe.
精彩评论