Answer the question
In order to leave comments, you need to log in
csv export from django/subprocess database?
Good afternoon.
You need to do something when you click on the button, all information from the database is exported to csv and it is downloaded.
View:
def export_view(request):
"""
Export a csv file with data from database.
"""
subprocess.call('python to_csv.py', shell = True)
f = open('output.csv', 'r')
response = HttpResponse(f, content_type='application/force-download')
response['Content-Disposition'] = 'attachment; filename=' + 'output.csv'
return response
import pandas as pd
import sqlite3
import os
import subprocess
subprocess.call("rm output.csv", shell = True)
con = sqlite3.connect("db.sqlite3")
df = pd.read_sql("SELECT * FROM app_contacts", con)
df.to_csv('output.csv', index=False, encoding='utf-8')
Answer the question
In order to leave comments, you need to log in
Is to_csv.py exactly executed? I didn't really understand why subprocess.call() should be used at all? Why not shove this code into the view? And why not remove with os.remove()
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question