Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Troubles with downloading and saving a document in django

I have a few problems, cannot figure it out, maybe there are connected.

Problem 1.1: file is exported in django documentation and it works, but when I try to rename it, it has some error. I want to be like this with pd.ExcelWriter(newdoc + 'output.xlsx') as writer: in order to every file has a "new" name. I got this error, TypeError at / unsupported operand type(s) for +: 'InMemoryUploadedFile' and 'str'

Problem 1.2: How to add path where to save?

Problem 2: I get to download file but it is empty, and name of document is Donwload.xlsx. I want to be like this, but this got many errors...

filename = newdoc + '_calculated.xlsx'
response = HttpResponse(output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; filename=%s' % filename
return response

When I do this, I got this... in terminal UserWarning: Calling close() on already closed file. and this in browser TypeError at / unsupported operand type(s) for +: 'InMemoryUploadedFile' and 'str'

This is views.py, and if code is like this, there are no errors but I got to download empty document.

def my_view(request):
    if request.method == "POST":
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            output = io.BytesIO()    
            newdoc = request.FILES['docfile']

            dfs = pd.read_excel(newdoc, sheet_name=None, index_col=[0])

            with pd.ExcelWriter('output.xlsx') as writer: #problem 1 
                for name, df in dfs.items():
                    #pandas code for uploaded excel file
                    out.to_excel(writer, sheet_name=name)
                 
            output.seek(0)

            response = HttpResponse(output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
            response['Content-Disposition'] = 'attachment; filename=%s.xlsx' % 'Download' #problem 2
            return response

    else:
        form = DocumentForm()
    return render(request, 'list.html', {'form': form})
like image 278
project.py Avatar asked Sep 01 '21 11:09

project.py


Video Answer


1 Answers

output = io.BytesIO() You created here was not used at all.

try changing

with pd.ExcelWriter('output.xlsx') as writer:

to

writer = pd.ExcelWriter(output)

Otherwise the BytesIO might be closed by the ExcelWriter, then Django would try to close it again. Giving you the double close error.

Your problem 2 seems to be a type error.

filename = newdoc + '_calculated.xlsx'

your newdoc here is not a string, but a "InMemoryUploadedFile", you probably need to access its name by doing

filename = f"{newdoc.name}_calculated.xlsx"
like image 68
rabbit.aaron Avatar answered Oct 17 '22 15:10

rabbit.aaron