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
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 >
<div >
{{ entry }}
</div>
<div >
<a href="{% url 'edit' %}" >
<button >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
CodePudding user response:
Django applies a filter for HTML tags in varibles. If you want the unfiltered output you have to apply the filter safe
:
{{ entry | safe }}
CodePudding user response:
Django will be auto-escaping the converted HTML that you pass to the template and won't render any HTML tags. To stop this you can use the safe
templatetag:
{{ entry|safe }}
https://docs.djangoproject.com/en/4.0/ref/templates/builtins/#safe