Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
697 views
in Technique[技术] by (71.8m points)

display django-pandas dataframe in a django template

I am trying to use django with pandas for data analysis. There seem to be no simple step by step tutorial on this. All the ones i have seen online just explain how to write the code in your django views.py file but none shows how to display the final product in the browser.

Here is the code in my views.py

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

but this does not work. Any detailed help will be appreciated. Please dont just point me to some documentation. In fact, most of django's documentation is not written in simple plain english --- it is even more confusing to some of us. Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is a minimal but elegant solution using Django_Pandas and an 'extended Bootstrap table' (https://github.com/wenzhixin/bootstrap-table)

The elegance comes from the ability to export a Pandas DataFrame to JSON, and for the Bootstrap Table script to consume that JSON content.

The HTML table is written for us, we don't need to worry about it (look below where we just include the 'table' tag without writing the rows ourselves, or even a for loop.) And it's interactive. And Bootstrap makes it look pretty.

requirements: 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.
  });
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...