python - 将 pandas 数据框放入 django 模板中

标签 python html django pandas

我想将 pandas 数据框放入 django 模板中。例如我想要这样的东西:

<html>
  <head><title>HTML Pandas Dataframe with CSS</title></head>
  <body>
    THE PANDAS DATAFRAME
  </body>
</html>

我尝试过的是这些代码。首先在我的 djangoviews.py 中,这是我的函数:

from django.shortcuts import render
import pandas as pd

def about(request):
    df = pd.DataFrame({'a': [12, 3, 4], 'b': [5, 6, 7]})
    df = df.to_html(classes='mystyle')
    return render(request, 'blog/about.html', {'table': df})

模板是:

{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'blog/style.css' %}">
<html>
  <head><title>HTML Pandas Dataframe with CSS</title></head>
  <body>
    {{table}}
  </body>
</html>

并且,style.css 是:

body {
  background: black;
  color: white;
}

显然,当我在浏览器中检查模板时,模板已正确加载 CSS 代码,但它给出了以下输出,而不是我想要的表格:

<table border="1" class="dataframe mystyle"> <thead> <tr style="text-align: right;"> <th></th> <th>a</th> <th>b</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>12</td> <td>5</td> </tr> <tr> <th>1</th> <td>3</td> <td>6</td> </tr> <tr> <th>2</th> <td>4</td> <td>7</td> </tr> </tbody> </table>

我是 django 的新手,所以也许我的方法是完全错误的。

最佳答案

我自己找到了解决方案。显然我应该在模板文件中将 {table} 更改为 {table|safe} 。所以,代码如下所示:

{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'blog/style.css' %}">
<html>
  <head><title>HTML Pandas Dataframe with CSS</title></head>
  <body>
    {{table|safe}}
  </body>
</html>

关于python - 将 pandas 数据框放入 django 模板中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59408681/

相关文章:

Python:鼠标交互获取数据点对应信息

javascript - 图形 map 对象表示网站

python - 为什么只有 `static`文件夹下的图片才能显示?

python - Django REST 框架 CSRF 失败 : CSRF cookie not set

python - 终结点查询字符串参数中有多个 "where clauses"

python - 我怎样才能得到 token 而不是字符串?

html - 在 Visual Studio Code 的下一行格式化组件属性

javascript - 使链接使用 POST 而不是 GET

阿拉伯语和其他外语的 Django slug 字段

Django - 使用单选按钮或下拉列表进行输入