'How to export data from front Web to CSV files using jquery?
I'm practiced Python+Django edited Web, followed sample trying to export from db data into front Web and I want download CSV file. Here is my whole function. Its download a file, but it shows the for the title and not any data out.
Thanks all.
Views: sid search funtion
def search_by_sid(request,pk=1):
sdepartments = Department.objects.all()
cdepartments = CDepartment.objects.all()
ssid = CourseData.objects.all()
if request.method == "POST":
sid = request.POST.get("sid").strip()
if "," in sid:
course = CourseData.objects.filter(sid="NA")
sids = sid.split(",")
for n in sids:
courses = CourseData.objects.filter(sid = n.strip())
course =course | courses
else:
course = CourseData.objects.filter(sid=sid).order_by("teacher")
num = len(course)
return render(request, "list.html")
return redirect("/")
donwload file function:
def down_file(request):
sdepartments = Department.objects.all()
cdepartments = CDepartment.objects.all()
ssid = CourseData.objects.all()
if request.method == "POST":
sids = request.POST.get("sid")
dfs = CourseData.objects.filter(sid__in=['sid']).values_list("sid","name","phone","email","sdept")
response = HttpResponse(content_type="text/csv")
response.write(codecs.BOM_UTF8)
response['Content-Disposition'] = 'attachment; filename = "Report.csv"'
writer = csv.writer(response)
print(writer)
writer.writerow(["sid","name","phone","email","sdept"])
for sop in dfs:
writer.writerow(sop)
return response
Templates: button function
<form id="sid" action="/bysid/" method="post">
{% csrf_token %}
Search:<input name="sid" size="50" placeholder="Search">
<input type="submit" value="Go Search">
<input id="btnType" type="hidden" value="Search">
<button type="button" id="down_file" >Download Files</button>
</form>
js funtion:
$(document).ready(function(){
$("#down_file").click(function(){
$("#btnType").val('accpeted'); <!--Why Null ?!-->
$("#sid").submit();
});
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
