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:
JavaScript
x
17
17
1
def download(request, fileUUID):
2
file = Documents.objects.get(Uuid=fileUUID)
3
filename = file.Filename
4
5
file_type, _ = mimetypes.guess_type(filename)
6
url = file.Url
7
blob_name = url.split("/")[-1]
8
blob_content = AzureBlob().download_from_blob(blob_name=blob_name)
9
10
if blob_content:
11
response = HttpResponse(blob_content.readall(), content_type=file_type)
12
response['Content-Disposition'] = f'attachment; filename={filename}'
13
messages.success(request, f"{filename} was successfully downloaded")
14
return response
15
16
return Http404
17
urls.py:
JavaScript
1
9
1
from django.urls import path
2
from upload.views import *
3
4
5
urlpatterns = [
6
path('upload/', DocumentUpload.as_view(), name="upload"),
7
path('download/<str:fileUUID>/', DocumentDownload.as_view(), name="download"),
8
]
9
template file or html:
JavaScript
1
4
1
<a href="{% url 'download' file.Uuid %}">
2
<i class='bx bxs-download'></i>
3
</a>
4
Advertisement
Answer
The path for download
class based view:
JavaScript
1
2
1
path('download/<str:fileUUID>/',views.DownloadView.as_view())
2
The view from the View
:
JavaScript
1
18
18
1
class DownloadView(View):
2
3
def get(self, request, *args, **kwargs):
4
file = UploadFilesBlobStorage.objects.get(Uuid=self.kwargs['fileUUID'])
5
filename = file.Filename
6
file_type, _ = mimetypes.guess_type(filename)
7
url = file.Url
8
blob_name = url.split("/")[-1]
9
blob_content = download_from_blob(blob_name)
10
11
if blob_content:
12
response = HttpResponse(blob_content.readall(), content_type=file_type)
13
response['Content-Disposition'] = f'attachment; filename={filename}'
14
messages.success(request, f"{filename} was successfully downloaded")
15
return response
16
17
return Http404
18