Last active
August 29, 2015 14:11
-
-
Save cansadadeserfeliz/3b1768a1cb13f7e457d4 to your computer and use it in GitHub Desktop.
Generate .zip file in Django
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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