我正在尝试使用django和熊猫进行数据分析。在这方面似乎没有简单的一步一步的教程。我在网上看到的所有这些都只是解释了如何在你的django views.py文件中编写代码,但没有一个显示如何在浏览器中显示最终产品。
下面是我的views.py中的代码
def index2(request):
qs = Product.objects.all()
df = read_frame(qs)
html= df.to_html
return HttpResponse(html)但这是行不通的。任何详细的帮助都将不胜感激。请不要只是指给我一些文档。事实上,django的大部分文档都不是用简单易懂的英语编写的-它甚至让我们中的一些人感到困惑。谢谢。
发布于 2016-10-06 06:39:32
下面是一个使用Django_Pandas和“扩展引导表”(https://github.com/wenzhixin/bootstrap-table)的简单而优雅的解决方案。
它的优雅之处在于能够将Pandas导出为DataFrame,并允许Bootstrap Table脚本使用该JSON内容。
HTML表格是为我们编写的,我们不需要担心它(看看下面我们只包含' table‘标签,而不是自己编写行,甚至是一个for循环。)而且它是交互式的。Bootstrap让它看起来很漂亮。
要求: Bootstrap、JQuery、Django_Pandas、文致信/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.
});
});发布于 2018-05-21 21:16:43
to_html是一个函数,你必须把它叫做。
def index2(request):
df = read_frame(Product.objects.all())
return HttpResponse(df.to_html())发布于 2020-12-21 13:30:43
#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> https://stackoverflow.com/questions/39003732
复制相似问题