I am trying to rewrite a function view that download files into a classview. However I don’t see how to do it properly with the right methods, since I have an argument from the url. Then I do not which on of the class view I should be using.
I did an attemps that is worrking, but I do not see why it works with a get method. Anyone can explain me ?
Here is my function view that is working:
Function views.py:
def download(request, fileUUID): file = Documents.objects.get(Uuid=fileUUID) filename = file.Filename file_type, _ = mimetypes.guess_type(filename) url = file.Url blob_name = url.split("/")[-1] blob_content = AzureBlob().download_from_blob(blob_name=blob_name) if blob_content: response = HttpResponse(blob_content.readall(), content_type=file_type) response['Content-Disposition'] = f'attachment; filename={filename}' messages.success(request, f"{filename} was successfully downloaded") return response return Http404
urls.py:
from django.urls import path from upload.views import * urlpatterns = [ path('upload/', DocumentUpload.as_view(), name="upload"), path('download/<str:fileUUID>/', DocumentDownload.as_view(), name="download"), ]
template file or html:
<a href="{% url 'download' file.Uuid %}"> <i class='bx bxs-download'></i> </a>
Advertisement
Answer
The path for download
class based view:
path('download/<str:fileUUID>/',views.DownloadView.as_view())
The view from the View
:
class DownloadView(View): def get(self, request, *args, **kwargs): file = UploadFilesBlobStorage.objects.get(Uuid=self.kwargs['fileUUID']) filename = file.Filename file_type, _ = mimetypes.guess_type(filename) url = file.Url blob_name = url.split("/")[-1] blob_content = download_from_blob(blob_name) if blob_content: response = HttpResponse(blob_content.readall(), content_type=file_type) response['Content-Disposition'] = f'attachment; filename={filename}' messages.success(request, f"{filename} was successfully downloaded") return response return Http404