Mastering Markdown in Django: Enhance Content Formatting

Django

Learn how to integrate Markdown into your Django projects using Django Markdownify. This guide will show you how to enhance content formatting, making it easier to write clean, readable content in your web applications. Whether you're looking to streamline your workflow or improve content management, this tutorial covers everything you need to know about using Markdown in Django effectively.

Django Markdownify is a template filter to convert Markdown to HTML in Django. Markdown is converted to HTML and sanitized. Django Markdownify requires Markdown and Bleach. When installing Django Markdownify, dependencies will be installed automatically.

Project Structure

Check out the full Django project structure we’ll be using in this guide here.

How to add Markdown

Add markdownify to your installed apps in settings.py:

# core/settings.py
INSTALLED_APPS = [
    ...
    'markdownify.apps.MarkdownifyConfig',
]

Use the filter in our template:

# templates/base.html
{% load markdownify %}

# templates/app/post_detail.html
{{ post.content|markdownify }}

You can change the behavior of Markdownify by adding them to your settings.py. All settings are optional and will fall back to default behavior if not specified. Define a dictionary MARKDOWNIFY in your core/settings.py:

# Markdownify Settings
MARKDOWNIFY = {
    "default": {
        "WHITELIST_ATTRS": ["href", "src", "alt", "class"],
        "WHITELIST_TAGS": ["a", "p", "ul", "li", "h2", "div", "span", "strong", "em", "td", "pre", "code", "img"],
        "MARKDOWN_EXTENSIONS": ["markdown.extensions.fenced_code", "markdown.extensions.codehilite"],
        "STRIP": False,
        "LINKIFY_TEXT": {
            "PARSE_URLS": False,
        }
    }
}

0