user1025948
user1025948

Reputation:

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.

Upvotes: 0

Views: 965

Answers (1)

C14L
C14L

Reputation: 12558

You need to mark the bleached 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.

Upvotes: 3

Related Questions