この問題は、テーブルに参加してダウンロードする外部関数を作成し、そのダウンロードファイルを指す静的ファイルにリンクを提供することで解決します。
はここ
def database_downloader():
import pymysql # run pip install pymysql if this fails
import sys
import time
import csv
start = time.time()
connect = 0
attempt = 1
while connect==0: #if connection is not secured, will try again in 3 seconds.
try:
print "connecting, attempt "+str(attempt)
conn = pymysql.connect(host='url', port=3306, user='username', passwd='pass', db='db', autocommit=True) #setup our credentials
cur = conn.cursor()
connect = 1
except:
print "try again in 3 seconds"
time.sleep(3)
attempt+=1
continue
print "connected to server in " +str(time.time()-start)+ " seconds."
out_file = open("main_app/static/main_app/reports/output.csv", "wb")
writer = csv.writer(out_file)
sql = "SELECT * FROM main_app_basic_info b LEFT JOIN main_app_add_info a ON a.Student_ID = b.Student_ID;"
cur.execute(sql)
column_names = []
for i in cur.description:
column_names.append(i[0])
writer.writerow(column_names)
for i in cur.fetchall():
writer.writerow(i)
print "Downloading completed in " + str((time.time()-start)) + " seconds."
out_file.close() # you need to close to save before sending
は、その後、私はこの機能にページがロードは、それが更新され、ダウンロードする準備ができて維持するたびに実行、私のヘルパー関数です。このように、
def index(request):
student_list = basic_info.objects.order_by('-id')[:5]
student_list_full = basic_info.objects.order_by('-id')
context = {'student_list': student_list, 'student_list_full': student_list_full}
database_downloader() # this downloads the database in every refresh to main_app/reports/output.csv
return render(request, 'main_app/index.html', context)
は最後に、私は
{% load static %}
<div><a href="{% static "main_app/reports/output.csv" %}" download>Click Here to Download to Database</a></div>
私はまだこれが最善の解決策であることを完全にはよく分からない、私のテンプレートにこれを追加します。しかし、これは私が今やっている能力であり、うまくいきます。
私はdjangoインポート/エクスポートを検討することをお勧めします – Foon