I am trying to download a CSV from the result of a search, as an option. Meaning that the user should be able to do a search and view the result in a template, and then download the csv for that search result as needed. The templates are not the issue, it's the views I need to resolve. I have the following views:
First is the search view
def binder_search(request):
if request.method == "POST":
searched = request.POST['searched']
binders_searched = Binders.objects.filter(Q(description__contains=searched) | Q(step__name__contains=searched) | Q(status__name__contains=searched))
return render(request, "binder_search.html", {'searched': searched, 'binders_searched': binders_searched})
else:
return render(request, "binder_search.html", {})
Then is the csv. This view creates the list of all items in the database. What I am trying to do is get the search result from the above view, and then create the csv file. I would end up with a CSV file that has only the search result in it.
def binders_csv(request):
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename=binders_result.csv'
# create a csv writer
writer = csv.writer(response)
# designate the model
binders = Binders.objects.all()
# add column at the heading of csv file
writer.writerow(['Item Code', 'Description', 'Item Type', 'Current Step', 'Current Status', 'Last change by'])
# loop thru and output
for binder in binders:
writer.writerow([binder.itemcode, binder.description, binder.itemtype, binder.step, binder.status, binder.user])
return response
I looked around at different solutions, but none actually debugged me. Any idea how to do this?