Skip to content

Instantly share code, notes, and snippets.

@cansadadeserfeliz
Last active August 29, 2015 14:11
Show Gist options
  • Save cansadadeserfeliz/3b1768a1cb13f7e457d4 to your computer and use it in GitHub Desktop.
Save cansadadeserfeliz/3b1768a1cb13f7e457d4 to your computer and use it in GitHub Desktop.
Generate .zip file in Django
import os
import zipfile
import cStringIO as StringIO
class ContractDownloadGalleryDetailView(LoginRequiredMixin, DetailView):
model = Contract
def render_to_response(self, context, **httpresponse_kwargs):
contract = self.object
if not contract.images.exists():
return HttpResponseRedirect(
reverse('contract:contract_detail', args=(contract.id,)),
)
dirname = u'imagenes_contrato_{0}'.format(contract.number)
filename = u'{0}.zip'.format(dirname)
buffer = StringIO.StringIO()
z = zipfile.ZipFile(buffer, 'w')
for contract_image in contract.images.all():
z.write(contract_image.image.path, os.path.join(dirname, os.path.basename(contract_image.image.path)))
z.close()
buffer.seek(0)
response = HttpResponse(buffer.read())
response['Content-Disposition'] = u'attachment; filename={0}'.format(filename)
response['Content-Type'] = 'application/x-zip'
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment