From 52d63128fc0460eed2ae36eb36e91cd984ed3cd1 Mon Sep 17 00:00:00 2001 From: Alexandre Iooss Date: Fri, 8 Oct 2021 20:41:20 +0200 Subject: [PATCH] Add download gallery as zip --- .../templates/photologue/gallery_detail.html | 2 +- photologue_custom/urls.py | 3 +- photologue_custom/views.py | 29 ++++++++++++++++++- 3 files changed, 31 insertions(+), 3 deletions(-) diff --git a/photologue_custom/templates/photologue/gallery_detail.html b/photologue_custom/templates/photologue/gallery_detail.html index 729ad37..d5545f4 100644 --- a/photologue_custom/templates/photologue/gallery_detail.html +++ b/photologue_custom/templates/photologue/gallery_detail.html @@ -38,5 +38,5 @@ {% endfor %} -{% trans 'Download all gallery' %} +{% trans 'Download all gallery' %} {% endblock %} diff --git a/photologue_custom/urls.py b/photologue_custom/urls.py index 939a305..1401caf 100644 --- a/photologue_custom/urls.py +++ b/photologue_custom/urls.py @@ -1,7 +1,8 @@ from django.urls import path -from .views import TagDetail +from .views import TagDetail, GalleryDownload urlpatterns = [ path('tag//', TagDetail.as_view(), name='tag-detail'), + path('gallery//download/', GalleryDownload.as_view(), name='gallery-download'), ] diff --git a/photologue_custom/views.py b/photologue_custom/views.py index 647137b..cea94e7 100644 --- a/photologue_custom/views.py +++ b/photologue_custom/views.py @@ -1,10 +1,15 @@ # Copyright (C) 2021 by BDE ENS Paris-Saclay # SPDX-License-Identifier: GPL-3.0-or-later +import os +import zipfile +from io import BytesIO + from django.contrib.auth.mixins import LoginRequiredMixin +from django.http import HttpResponse from django.views.generic import DetailView -from taggit.models import Tag from photologue.models import Gallery +from taggit.models import Tag class TagDetail(LoginRequiredMixin, DetailView): @@ -19,3 +24,25 @@ class TagDetail(LoginRequiredMixin, DetailView): context['galleries'] = Gallery.objects.on_site().is_public() \ .filter(extended__tags__name=current_tag) return context + + +class GalleryDownload(LoginRequiredMixin, DetailView): + model = Gallery + + def get(self, request, *args, **kwargs): + """ + Download a zip file of the gallery on GET request. + """ + # Create zip file with pictures + gallery = self.get_object() + byte_data = BytesIO() + zip_file = zipfile.ZipFile(byte_data, "w") + for photo in gallery.public(): + filename = os.path.basename(os.path.normpath(photo.image.path)) + zip_file.write(photo.image.path, filename) + zip_file.close() + + # Return zip file + response = HttpResponse(byte_data.getvalue(), content_type='application/x-zip-compressed') + response['Content-Disposition'] = f"attachment; filename={gallery.slug}.zip" + return response