简体   繁体   中英

How can I display pandas dataframe into django template?

I have a pandas dataframe and i want to show this dataframe into my django template. But everytime the code compile successfully without showing any table in my django web app. What am i missing here? My data frame looks like this:

dataframe sample

and my html looks like:

 <div class="row" style="margin-bottom: 20px;"> <div class="col-md-3"> </div> <div class="col-md-9"> <div class="card" style="width: auto;"> <div class="card-body"> <h3 class="h3">Total match data and Profit Mergin</h3> <br> <table class="table table-striped"> <tr> <th>Total Contest</th> <th>Total Entry Amount</th> <th>Total Seat</th> <th>Total Winning Amount</th> <th>Total Team Capacity</th> <th>Profit Mergin</th> {% for value in final_data.iterrows %} <tr> <td>{{ value.0 }}</td> <td>{{ value.1 }}</td> <td>{{ value.2 }}</td> <td>{{ value.3 }}</td> <td>{{ value.4 }}</td> <td>{{ value.5 }}</td> </tr> {% endfor %} </table> </div> </div> </div> </div>

i tried final_data.itertuplus but still got the same result. What should i do now?

Looks like there are two options:

  1. Leave the DataFrame as-is and then use a statement in your template.

    Currently, you're using the pandas.DataFrame.iterrows method but it is not called.

    Call the method by adding () at the end of final_data.iterrows .

    (Also, make sure to close your table header row with </tr> .)

  2. Convert the DataFrame to HTML and then use an expression in your template.

    As @david-sielski mentions, consider using the pandas.DataFrame.to_html method.

    Take a look at this example of How to render Pandas DataFrame as HTML Table?

    Uncomment the final_df = final_df.to_html() line and replace the table with {{ final_data }} .

    (Also, make sure to add your styling classes using the classes kwarg.)

Check out how to use developer tools to inspect your HTML if you haven't already.

Comment if you have any questions,

Clay

This a basic html table that shows a pandas dataframe in a django template:

<table>
  <tr>
    {% for col in df.columns %}
      <td>
        {{col}}
      </td>
    {% endfor %}
  </tr>
    {% for index, row in df.iterrows %}
      <tr>
        {% for cell in row %}
          <td>
            {{cell}}
          </td>
        {% endfor %}
      </tr>
    {% endfor %}
</table>

This one is not showing the index, so if you want to render it, you could pass df.reset_index() to the template.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM