How to display text with HTML-markup? (I use ckeditor)
Asked Answered
F

1

1

I heard about the filter |safe, but if I understood correctly, that's unsafe and creates a backdoor for injections.

What are the alternatives to display full posts with formatted text?

Futility answered 30/12, 2016 at 16:14 Comment(0)
A
1

I think when you not use the filter of |safe, then output should return as text only with html markup (not rendered as html output).

But, if you need to exclude some dangerous tags such as <script>location.reload()</script>, you need to handle it with custom templatetag filter..

I got good answer from: https://mcmap.net/q/103715/-remove-html-tags-not-on-an-allowed-list-from-a-python-string, via BeautifulSoup.

from bs4 import BeautifulSoup
from django import template
from django.utils.html import escape

register = template.Library()
INVALID_TAGS = ['script',]

def clean_html(value):
    soup = BeautifulSoup(value)
    for tag in soup.findAll(True):
        if tag.name in INVALID_TAGS:
            # tag.hidden = True # you also can use this.
            tag.replaceWith(escape(tag))
    return soup.renderContents()

# clean_html('<h1>This is heading</h1> and this one is xss injection <script>location.reload()</script>')
# output:
# <html><body><h1>This is heading</h1> and this one is xss injection &lt;script&gt;location.reload()&lt;/script&gt;</body></html>

@register.filter
def safe_exclude(text):
    # eg: {{ post.description|safe_exclude|safe }}
    return clean_html(text)

Hope it usefull..

Artis answered 3/1, 2017 at 0:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.