Answer the question
In order to leave comments, you need to log in
What is the correct way to give zipfile in django response?
I'm making a section with files in the application. When you click on the "Download all" button, an archive with all the files attached to the desired folder should be written. I received the path to the folder, wrote the files to the archive, it remains to give the file for downloading in FileResponse.
There are two problems here:
1) If you give the file as a variable, this error occurs - A server error occurred. Please contact the administrator. Although the files are sent one by one.
2) The archive, for some reason, is always saved in the django root folder, although I tried to change the paths in every possible way. For good, you need to make sure that it appears in the media folder.
I've only recently encountered files on the web and have almost no idea how to send them in a response. Help someone good advice or documentation, please!
views.py
def DownloadAllFilesView(request, objId):
if request.method == 'POST':
project_folder = Doc.objects.filter(idProj=Project.objects.get(id=objId)).first().idProj.name.replace(' ', '_')
path = settings.MEDIA_ROOT + '/project_%s/' % project_folder
z_name = '%s.zip' % Project.objects.get(id=objId).name.replace(' ', '_')
z = zipfile.ZipFile(z_name, 'w') # Создание нового архива
for root, dirs, files in os.walk(path): # Список всех файлов и папок в директории folder
for file in files:
z.write(os.path.join(root, file)) # Создание относительных путей и запись файлов в архив
z.close()
return FileResponse(z)
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question