Oleksii Oleksii - 3 years ago 228
Python Question

Return file using HttpResponse

Good afternoon. I need to download data from database in excel format. Below, my code and its working correct when i'm trying to download file through firefox, but using chrome this view returning archive with some

openpyxl
files.
Openpyxl
- this library i'm using to filling excel table from database in
excel_download()
function. Will you please help me to solve it?

def excel_download_view(request, **kwargs):
if 'sorting_argument' in kwargs:
queryset = Lot.objects.filter(
Q(bank__slug__iexact=kwargs['sorting_argument']) |
Q(auction_date__iexact=kwargs['sorting_argument']) |
Q(which_time_auction__iexact=kwargs['sorting_argument']) |
Q(fgvfo_number__iexact=kwargs['sorting_argument']) |
Q(prozorro_number__iexact=kwargs['sorting_argument']) |
Q(decision_number__iexact=kwargs['sorting_argument'])
)
else:
queryset = Lot.objects.all()

excel_download(queryset)

data = None

with open('media/excel/lots.xlsx', 'rb') as f:
data = f.read()

return HttpResponse(data, content_type='application/vnd.ms-excel')

Answer Source

by the response-as-a-file-attachment, try it:

response = HttpResponse(data, content_type='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename="lots.xlsx"'
return response
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download