Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django : transform a function download view into a class view

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"),
   ]

html

<a href="{% url 'download' file.Uuid %}">
       <i class='bx bxs-download'></i>
</a>

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading