Convert Markdown to HTML in your Django App with Markdownify Library

Markdownify is a library of the Django framework that supplies a Django template filter to convert markdown syntax to HTML codes in Django templates.

It is under the publicly available Python Package Index (PyPI) at https://pypi.org/project/django-markdownify/

Markdownify implements the python-markdown package to convert markdown syntax to HTML. It also uses the “LINK bleach LINK” library to prevent the HTML produced from Cross Site Scripting (XSS) attacks.

Steps to Setup Markdownify

  1. Include in Requirements.txt
    For best practices, include it in your requirements.txt file as follows:
django-markdownify —  0.8.0

2. Install with Package Manager

Install with pip installer on your terminal/CLI:

pip install -r requirements.txt

3. Add to installed apps

The next step is to add markdownify to the list of installed apps. Open your settings.py file and include the following line inside the INSTALLED_APPS list as follows.

INSTALLED_APPS = [

‘markdownify’,
]

'…’ above represents other apps already inside the INSTALLED_APPS list.

4. Define HTML Elements you want converted

Now, you will have to specify which exact HTML elements you want to be converted by markdownify. Add the following lines to the settings.py files

MARKDOWNIFY_STRIP = False
MARKDOWNIFY_WHITELIST_TAGS = {
‘a’, ‘p’,
‘h1’, ‘h2’, ‘h3’,’h4', ‘h5’, ‘h6’, ‘h7’,
‘ul’, ‘li’, ‘span’,
}

MARKDOWNIFY_STRIP = False ensures that markdownify HTML encodes all other HTML elements.

5. Implement
To use markdownify in your template, you have to supply it as a filter like the following:

<div>
{{ name.text | markdownify }}
</div>

Thanks for reading through! 😊 I’d appreciate your suggestions and criticism in the comment section. Don’t forget to clap 👏and bookmark this article if you find it helpful.

Let’s connect on Twitter @jkayLight and let’s keep the conversation going. 😉

Software | Aerospace Undergrad • ex-Lead @GoogleDevs’ DSC KWASU

Software | Aerospace Undergrad • ex-Lead @GoogleDevs’ DSC KWASU