简体   繁体   中英

Django - Rendering Markdown Sanitizied with Bleach

When I do markdown(text), without bleach, I get the desired result (raw):

<p>blah</p>

and it displays correctly as:

blah

where the "p" tags are rendered correctly as a paragraph block.

When I do bleach.clean(markdown.markdown(text)), I get (raw):

&lt;p&gt;blah&lt;/p&gt;

and it displays incorrectly as:

<p>blah</p>

where the "p" tags are part of the text and not an HTML paragraph block.

You need to mark the bleach ed HTML as safe

from django.utils.safestring import mark_safe

...
    return mark_safe(bleach.clean(markdown.markdown(text)))

But, there is also django-bleach that provides integration with Django and ready-made tags to use bleach in Django.

{% load markdown_deux_tags bleach_tags %}
{{ view_user.profile.about|markdown:"user"|bleach }}

In settings.py you can tell django-bleach what tags are okay

BLEACH_ALLOWED_TAGS = ['h1', 'h2', 'p', 'b', 'i', 'strong', 'a']
BLEACH_ALLOWED_ATTRIBUTES = ['href', 'title', 'style']
BLEACH_ALLOWED_STYLES = ['font-family', 'font-weight']
BLEACH_STRIP_TAGS = True

etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM