0

Can I return multiple files in a Django response?

Normally, I see many websites have uploaded multiple pictures. However, I've not seen responses in multiple pictures or files. Now, I can export an excel file from Django, but I want to export multiple excel files at the same time.

this code below export a single excel file from the response

from openpyxl import Workbook    

response = HttpResponse(
    content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    )
response['Content-Disposition'] = 'attachment; filename={date}-user.xlsx'.format(
        date=datetime.now().strftime('%Y-%m-%d'),
        )
workbook = Workbook()

worksheet = workbook.active
worksheet.title = 'Test'
    
row_num = 1
columns   = ["Username", "First_name", "Last_name", "Email"]
for col_num, column_title in enumerate(columns, 1):
    cell = worksheet.cell(row=row_num, column=col_num)
    cell.value = column_title
        
user_queryset = User.objects.all().values("username", "first_name", "last_name", "email")
for user in user_queryset:
    row_num += 1
    
    # Define the data for each cell in the row 
    row = [
        user['username'],
        user['first_name'],
        user['last_name'],
        user['email'],
    ]
    
    # Assign the data for each cell of the row 
    for col_num, cell_value in enumerate(row, 1):
        cell = worksheet.cell(row=row_num, column=col_num)
        cell.value = cell_value

workbook.save(response)

return response
Sumithran
  • 6,217
  • 4
  • 40
  • 54
  • 1
    I think you'll have to archive them together into one file using something like `tar` or `zip`. – D Malan Mar 02 '21 at 10:37
  • Does this answer your question? [How to return multiple files in HttpResponse Django](https://stackoverflow.com/questions/42814732/how-to-return-multiple-files-in-httpresponse-django) – Sumithran Mar 02 '21 at 10:57

1 Answers1

1

I just get new solution for my problem. I zip multiple excel file and return one zip file to the Response. but I concern, Is this way good or not? or another way better than this solution

from datetime import datetime, timedelta, date

import os, zipfile

from openpyxl import Workbook // (library for create file.xlsx)

openpyxl documentation

first, I create file.xlsx and I use arr_name to collect name of file.xlsx to delete in final process

 arr_name = []
 for each_search in all_query_search :
    workbook = Workbook()

    # Get active worksheet/tab
    worksheet = workbook.active
    worksheet.title = 'Test'
    
    row_num = 1
    columns   = ["Username", "First_name", "Last_name", "Email"]
    for col_num, column_title in enumerate(columns, 1):
        cell = worksheet.cell(row=row_num, column=col_num)
        cell.value = column_title
        
    user_queryset = User.objects.filter(search = each_search).values("username", "first_name", "last_name", "email")
    for user in user_queryset:
        row_num += 1
    
        # Define the data for each cell in the row 
        row = [
            user['username'],
            user['first_name'],
            user['last_name'],
            user['email'],
        ]
    
        # Assign the data for each cell of the row 
        for col_num, cell_value in enumerate(row, 1):
            cell = worksheet.cell(row=row_num, column=col_num)
            cell.value = cell_value
    date = datetime.now().strftime('%d-%m-%Y')
    var_name = f"{date} {...some name for each file...}"
    workbook.save(var_name)
    arr_name.append(name) // collect name to delete
    

second, I create zip file. if zip was not close, the response will err.

zipObj = zipfile.ZipFile('Reservation.zip', 'w', zipfile.ZIP_DEFLATED)
for name in arr_name:
    zipObj.write(name)
zipObj.close()

third, I collect zip file on response. (open zip file and read in response)

response = HttpResponse(open('your_zip_file_name.zip', 'rb'),content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename=Reservation.zip'

fourth, I delete all files which were make during process

if arr_name:
    for name in arr_name:
        if os.path.exists(name):
            os.remove(name)
    os.remove("your_zip_file_name.zip")

finally, I return the response

return response