我有一个django项目,想通过单击html模板中的按钮从html(xxx)表中的数据创建一个csv文件。该代码应具有什么样的功能?这是我项目的view.py,Model和html模板。真的谢谢你!
HTML: HTML(xxx):
<table>
<tr>
<th><div class="panel-heading">No.</div></th>
<th><div class="panel-heading">Search Content</div></th>
<th><div class="panel-heading">Title</div></th>
</tr>
<tr>
{% for i in datas %}
<td><div class="panel-body"><small>{{forloop.counter}}</div></td>
<td><div class="panel-body">{{ i.0 }}</div></td>
<td><div class="panel-body">{ i.1 }}</div></td>
</tr>
</table>
view.py:
def table(request):
user = request.user
data = Outputting.objects.filter.order_by('batch_id').values_list('col_a1', 'col_b1')
return render(request, "xxx.html", {"datas": data})
型号:
class Outputting(models.Model):
date_added = models.DateTimeField(default=timezone.now)
batch_id = models.AutoField(primary_key=True)
col_a1 = models.CharField(max_length=1000)
col_b1 = models.CharField(max_length=1000)
单击按钮后,csv会自动生成。
答案 0 :(得分:0)
我建议您在[此处] [1]看一下Django官方文档。
从下面的代码段中可以看到(摘自上述链接),您可以实现一个简单的视图,以便在新视图中将表导出到csv中。
import csv
from django.http import HttpResponse
def some_view(request):
# Create the HttpResponse object with the appropriate CSV header.
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'
writer = csv.writer(response)
writer.writerow(['First row', 'Foo', 'Bar', 'Baz'])
writer.writerow(['Second row', 'A', 'B', 'C', '"Testing"', "Here's a quote"])
return response