Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why are my converted Markdown HTML tags returned as text?

A function in my views.py file converts Markdown files and returns the HTML to another function which is used to show the current entry (entry()). In entry(), I have a dictionary that is gives a HTML template access to the converted content. However, when the tags like <h1> and <p> are shown on the page instead of being hidden.

So,

<h1>CSS</h1> <p>CSS is a language that can be used to add style to an <a href="/wiki/HTML">HTML</a> page.</p>

is shown instead of

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

CSS

CSS is a language that can be used to add style to an HTML page.

How do I get rid of the tags on the page and have them actually be used in the HTML file?

entry.html:

{% block body %}
<div class="entry-container">
    <div class="left">
        {{ entry }}
    </div>
    <div class="right">
        <a href="{% url 'edit' %}" class="edit-btn">
            <button class="edit">EDIT</button>
        </a>
    </div>
</div>
{% endblock %}

views.py:

import markdown
from . import util

def entry(request, name):
    entry = util.get_entry(name)
    converted = convert(entry)
    if util.get_entry(name) is not None:
        context = {
            'entry': converted,
            'name': name
        }
        global current_entry
        current_entry = name
        return render(request, 'encyclopedia/entry.html', context)
    else:
        return render(request, "encyclopedia/404.html")

def convert(entry):
    return markdown.markdown(entry)

urls.py:

path('<str:name>', views.entry, name='entry'),

util.py:

def get_entry(title):
    """
    Retrieves an encyclopedia entry by its title. If no such
    entry exists, the function returns None.
    """
    try:
        f = default_storage.open(f"entries/{title}.md")
        return f.read().decode("utf-8")
    except FileNotFoundError:
        return None

>Solution :

Django applies a filter for HTML tags in varibles. If you want the unfiltered output you have to apply the filter safe:

{{ entry | safe }}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading