skip to Main Content

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


  1. import pandas as pd
    
    from django.shortcuts import render
    
    def your_view(request):
    
    # Your SQL query
    a_query = """
    SELECT *
    FROM db
    """
    # Execute the query and fetch the data into a DataFrame
    a = pd.read_sql_query(a_query, connection)
    
    # Convert the DataFrame to an HTML table
    a_html = a.to_html(index=False)
    
    # Pass the HTML table to the template for rendering
    return render(request, 'index.html', {'a_html': a_html})
    
    Login or Signup to reply.
  2. 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:

    <tr>
        <th>Table Headline</th>       
    </tr>
    {% for elem in my_data %}
      <tr>
        <td>{{elem}}</td>
      </tr>
    {% endfor %}
    

    So format your data into an iterable and render it inside the html

    return render(request, 'index.html',{'my_data':function_that_returns_data_as_a_list()})
    
    Login or Signup to reply.
  3. 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:

    {{ a_html | safe }}
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search