【问题标题】:display django-pandas dataframe in a django template在 django 模板中显示 django-pandas 数据框
【发布时间】:2016-12-24 12:44:01
【问题描述】:

我正在尝试使用 django 和 pandas 进行数据分析。这似乎没有简单的分步教程。我在网上看到的所有只是解释了如何在你的 django views.py 文件中编写代码,但没有一个显示如何在浏览器中显示最终产品。

这是我的views.py中的代码

def index2(request):
    qs = Product.objects.all()
    df = read_frame(qs)
    html= df.to_html
    return HttpResponse(html)

但这不起作用。任何详细的帮助将不胜感激。请不要只是指向我一些文档。事实上,大多数 django 的文档都不是用简单的纯英文写的——这对我们中的一些人来说甚至更令人困惑。谢谢。

【问题讨论】:

  • 不起作用是什么意思?没有按预期工作,或者只是没有完全停止工作? dataframe 的 .to_html 函数只是为您提供了一个裸 html 表,而不是网页,这取决于您可能需要使用 django 模板在其周围添加适当标签的浏览器。 print(Product.objects.all().count()) 输出什么?
  • 我的意思是我的浏览器中没有显示任何内容,没有表格(什么都没有)。我将尝试打印语句并查看输出谢谢。
  • html=df.to_html() 会为您完成这项工作。 () 是必需的。

标签: django pandas


【解决方案1】:

#app/models.py

    from django.db import models
    class Consumer(models.Model):
        username = models.CharField(max_length=100, null=True)
        phone = models.BigIntegerField(null=True)
        first_name = models.CharField(max_length=100, null=True)
        last_name = models.CharField(max_length=100, null=True)
        
        def __str__(self):
            return self.first_name

#app/views.py

    from django.shortcuts import render
    import pandas as pd 
    from .models import Consumer
    import json 
    def ConsumerView(request): 
        qs = Consumer.objects.all()
        consumers = [{"UserName":x.username,"FirstName":x.first_name,"LastName":x.last_name} for x in qs]
         
        df = pd.DataFrame(consumers)
      
        # parsing the DataFrame in json format. 
        json_records = df.reset_index().to_json(orient ='records') 
        data = [] 
        data = json.loads(json_records) 
        context = {'d': data} 
        return render(request, "CR.html", context)

#app/urls.py

from django.urls import path
from .views import ConsumerView
urlpatterns = [
    path('',ConsumerView, name='CR'),
]

#templates/CR.html

<!DOCTYPE html> 
<html lang="en"> 
<head> 
<title>Django-Pandas-Template</title> 
<meta charset="utf-8"> 
<meta name="viewport" content="width=device-width, initial-scale=1"> 
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script> 
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script> 
</head> 
<body> 

<div class="container"> 
<h2 class="text-center"><u>Django models --> Pandas DataFrame --> render to --> Templates(.html)  </u></h2><br>          
<table class="table table-dark table-striped"> 
    <thead> 
    <tr> 
        <th>User Name</th> 
        <th>First Name</th> 
        <th>Last Name</th> 
        
    </tr> 
    </thead> 
    <tbody> 
    <!-- jinja2 Technique -->
    {% if d %} 
    {% for i in d %} 
    <tr> 
        <td>{{i.UserName}}</td> 
        <td>{{i.FirstName}}</td> 
        <td>{{i.LastName}}</td> 
        
    </tr> 
    {% endfor %} 
    {% endif %} 
    </tbody> 
</table> 
</div> 

</body> 
</html> 

【讨论】:

    【解决方案2】:

    to_html 是一个函数,你必须调用它

    def index2(request):
        df = read_frame(Product.objects.all())
        return HttpResponse(df.to_html())
    

    【讨论】:

    • 它没有按预期工作。它添加了 标签,但在模板中无法正确显示。
    • @MehdiZare,您必须将安全过滤器添加到上下文中:{{df|safe}}
    • 这对我有用,并且通过在模板中添加“{{your_df_data|safe}}”来修复作为表格的 df 外观....感谢 Braulio。跨度>
    【解决方案3】:

    这是一个使用 Django_Pandas 和“扩展引导表”(https://github.com/wenzhixin/bootstrap-table) 的最小但优雅的解决方案

    优雅之处在于能够将 Pandas DataFrame 导出为 JSON,并让 Bootstrap Table 脚本使用该 JSON 内容。

    HTML 表格是为我们编写的,我们不需要担心(看看下面我们只包含 'table' 标记而不自己编写行,甚至是 for 循环.) 它是交互式的。 Bootstrap 让它看起来很漂亮。

    要求:Bootstrap、JQuery、Django_Pandas、wenzhixin/bootstrap-table

    models.py

    from django.db import models
    from django_pandas.managers import DataFrameManager
    
    class Product(models.Model):
      product_name=models.TextField()
      objects = models.Manager()
      pdobjects = DataFrameManager()  # Pandas-Enabled Manager 
    

    views.py

    from models import Product
    def ProductView(request):
      qs = Product.pdobjects.all()  # Use the Pandas Manager
      df = qs.to_dataframe()
      template = 'product.html'
    
      #Format the column headers for the Bootstrap table, they're just a list of field names, 
      #duplicated and turned into dicts like this: {'field': 'foo', 'title: 'foo'}
      columns = [{'field': f, 'title': f} for f in Product._Meta.fields]
      #Write the DataFrame to JSON (as easy as can be)
      json = df.to_json(orient='records')  # output just the records (no fieldnames) as a collection of tuples
      #Proceed to create your context object containing the columns and the data
      context = {
                 'data': json,
                 'columns': columns
                }
      #And render it!
      return render(request, template, context)
    

    product.html

    <script src='/path/to/bootstrap.js'>
    <script src='/path/to/jquery.js'>
    <script src='/path/to/bootstrap-table.js'>
    <script src='/path/to/pandas_bootstrap_table.js'>
    <table id='datatable'></table>
    <!-- Yep, all you need is a properly identified
         but otherwise empty, table tag! -->
    

    pandas_bootstrap_table.js

    $(function() {
      $('#datatable')({
        striped: true,
        pagination: true,
        showColumns: true,
        showToggle: true,
        showExport: true,
        sortable: true,
        paginationVAlign: 'both',
        pageSize: 25,
        pageList: [10, 25, 50, 100, 'ALL'],
        columns: {{ columns|safe }},  // here is where we use the column content from our Django View
        data: {{ data|safe }}, // here is where we use the data content from our Django View. we escape the content with the safe tag so the raw JSON isn't shown.
      });
    });
    

    【讨论】:

    • 我没有编辑你的答案,因为你可能正在使用我不熟悉的功能,但我相信你的 js 中的语法应该是:$('#datatable.pandas')。 bootstrapTable({。话虽如此,我不认为您正在使用的功能在 bootstrap 中。有一个名为 bootstraptables 的单独附加组件看起来具有相同的语法?
    • K.B.您至少对我之前忽略提及的第三方工具是正确的:github.com/wenzhixin/bootstrap-table。相应更新。
    • K.B.我认为为了简单起见,我可以删除表类并将其硬编码到 ID 中,如下所示: $('#datatable')({
    • 非常感谢您抽出宝贵时间如此清楚地解释一切。这个周末我会试试看。谢谢。
    • 如果我在视图中而不是模型中有数据框,我该如何使用此方法?
    猜你喜欢
    • 2018-03-07
    • 2012-03-18
    • 2020-04-11
    • 2014-11-12
    • 2011-07-10
    • 1970-01-01
    • 2015-10-27
    • 2013-02-17
    • 2016-05-06
    相关资源
    最近更新 更多