I am totally a new bee in Django, it’s my 2nd day to learn it. I have already connected to the database and use the pandas.read_sql_query to get the df from database (I know there is ORM but since we use MSSQL, so it need more time for me to figure it out, and I really need to show sth at lease so I use pandas.read_sql_query)
I have already got the df and I want it to show in the html. According to some other posts, I use the code below:
view.py
a_query="""
select *
FROM db
"""
a = pandas.read_sql_query(a_query,connection)
a_html = a.to_html(index=False)
print(a)
print(type(a))
return render(request, 'index.html',{'a_html':a_html})
the type shows: So I think it’s all good.
<class 'pandas.core.frame.DataFrame'>
index.html
I put {{a_html}} in the body part, it's the only thing I change after the original format.
after I run the manage.py, it shows this in html:
<table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th>IT Business Service</th> <th>IT Service Instance</th> </tr> </thead> <tbody> <tr> <td>
sth like that.
But I want to to show the table, how should I do for it? Any help is really apprecaited!
3
Answers
Beginner here myself, so take my answer with a grain of salt.
If you have a container like a list, you can loop trough it and generate the table depending on the amount of entries:
So format your data into an iterable and render it inside the html
The issue here seems to be related to Django’s auto-escaping feature. It’s a security feature that Django has in place to protect from HTML injection attacks. The {{a_html}} in your template is being escaped by Django’s template engine, so HTML tags are being displayed as text.
To resolve the issue, you need to tell Django that you want to allow HTML content to be displayed as HTML and not text. This can be done with Django’s safe filter.
Here’s how you can do it:
This should allow the HTML content to be displayed properly as a table.
However, remember that using safe means that you’re bypassing Django’s automatic HTML escaping, which can expose your site to cross-site scripting (XSS) attacks if you’re not careful about what HTML you’re marking as safe. In your case, since you’re generating HTML from a Pandas dataframe, the risk is likely low, but it’s still something to be aware of in general.