Embedding Images With Django Markdownify

Thursday, August 05, 2021

I do not yet have the capability to embed images in my blog using Django-Markdownify. Let's fix that! If I get it to work then we should see this image at the bottom of the page: https://i.imgur.com/OFyhsBt.jpeg. The first thing I am going to try is following this GitHub issue to see if I can create a templatetag to stop bleach from stripping out any src.

There is one thing about this that bothers me and that is relying on a site like imgur to host images for me. What is the image retention policy of imgur? Apparently forever unless deleted!

I was going to try to include the code here as ![Alt text](../../images/nice_hot_cup_of_coffee.jpeg). But then this becomes extremely challenging to begin thinking about how I would possibly serve this static image using Nginx. Unless... it was in the static folder? Would that work? Before we go down that road, why don't we make sure that an image that I can render in Atom's markdown preview can get rendered on the old website in local development (not the case right now). To do this I think I'll need to pursue the bleach solution, which would be a fine solution in its own right.

The full templatetag from the GitHub issue, including imports, is:

from django import template
import markdown
import bleach
from django.conf import settings

register = template.Library()

@register.filter
def markdownify(text):
    # safe mode is deprecated, see: https://pythonhosted.org/Markdown/reference.html#safe_mode
    untrusted_text = markdown.markdown(text, safe_mode='escape')
    html = bleach.clean(untrusted_text,
            tags=settings.MARKDOWNIFY_WHITELIST_TAGS,
            attributes=settings.MARKDOWNIFY_WHITELIST_ATTRS, ) # Add this line
    html = bleach.linkify(html)
    return html

Ugh. That completely broke Django Markdownfiy, so that is not cool.

Excellent! Looks like all I needed to do was add img to MARKDOWNIFY_WHITELIST_TAGS.

Alt text