user1025948 user1025948 - 1 year ago 100
HTML Question

Django - Rendering Markdown Sanitizied with Bleach

I have a Django site that allows for user inputted Markdown text. I'd like to sanitize and display the text, but I can't get it to display correctly.

from django import template
import markdown
import re
import bleach

register = template.Library()

def markdown_processor(text):
return bleach.clean(markdown.markdown(text))

Template File:

{% autoescape off %}
{{ text|markdown_processor }}
{% endautoescape %}

Suppose text="blah".

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


and it displays correctly as:


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

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


and it displays incorrectly as:


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

I can't figure out how to correctly display the bleached text. I used to do escape=True for Python Markdown (without bleach), but that's now deprecated. Any help is much appreciated.

Answer Source

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 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']