afficher django-pandas dataframe dans un modèle django

j'essaie d'utiliser django avec pandas pour l'analyse des données. Il ne semble pas y avoir de tutoriel simple étape par étape sur ce point. Tous ceux que j'ai vu en ligne seulement d'expliquer comment écrire le code dans votre django views.py fichier mais aucune montre comment afficher le produit final dans le navigateur.

voici le code dans mon views.py

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

mais cela ne fonctionne pas. Toute aide sera appréciée. S'il vous plaît, ne me montrez pas juste quelques documents. En fait, la plupart des django la documentation n'est pas rédigée dans un anglais simple et simple --- elle est encore plus déroutante pour certains d'entre nous. Remercier.

8
demandé sur vsminkov 2016-08-17 21:18:28

2 réponses

Voici une solution minimale mais élégante en utilisant Django_Pandas et une 'table de Bootstrap étendue' (https://github.com/wenzhixin/bootstrap-table)

l'élégance vient de la possibilité d'exporter une DataFrame Pandas vers JSON, et pour le script de table Bootstrap de consommer ce contenu JSON.

la table HTML est écrite pour nous, nous n'avons pas besoin de nous en inquiéter (Regardez ci-dessous où nous incluons juste la balise 'table' sans écrire les lignes nous-mêmes, ou même boucle.) Et c'est interactif. Et Bootstrap le fait paraître joli.

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)

produit.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.
  });
});
10
répondu Steve W 2016-10-05 23:31:02

to_html est une fonction, il faut l'appeler.

def index2(request):
    df = read_frame(Product.objects.all())
    return HttpResponse(df.to_html())
1
répondu Bertrand Bordage 2018-05-21 13:16:42