I followed these method to track how much downloaded the file was. But total_downloads
always remains same (it’s 0). How to increment total_downloads
field by 1 after every download?
My models.py:
JavaScript
x
12
12
1
from django.db import models
2
3
class FilesAdmin(models.Model):
4
id_no = models.IntegerField()
5
name = models.CharField(max_length=20)
6
loc = models.CharField(max_length=20)
7
adminupload = models.FileField(upload_to='media')
8
total_downloads = models.IntegerField(default=0)
9
10
def __str__(self):
11
return self.name
12
views.py. In this program, I want to increment the number of downloads. But it’s 0 in admin site.
JavaScript
1
21
21
1
from django.shortcuts import render
2
from django.http import HttpResponse
3
import os
4
from .models import FilesAdmin
5
6
def index(request):
7
context = {'file': FilesAdmin.objects.all()}
8
return render(request,'libooki/index.html',context)
9
10
11
def download(request,path,pk):
12
file_path = os.path.join(settings.MEDIA_ROOT,path)
13
if os.path.exists(file_path):
14
with open(file_path,'rb') as fh:
15
response = HttpResponse(fh.read(),content_type="application/adminupload")
16
response['Content-Disposition']='inline;filename'+os.path.basename(file_path)
17
n = FilesAdmin.objects.get(pk=pk)
18
n.total_downloads += 1
19
n.save()
20
return response
21
urls.py
JavaScript
1
17
17
1
from django.contrib import admin
2
from django.urls import include,path
3
from django.conf import settings
4
from django.conf.urls.static import static
5
from libooki import views #here's libooki is my app name
6
from django.conf.urls import url
7
from django.views.static import serve
8
9
urlpatterns = [
10
path('', views.index,name='index'),
11
path('admin/', admin.site.urls),
12
url(r'^download/(?P<path>.*)$',serve,{'document_root': settings.MEDIA_ROOT}),
13
]
14
if settings.DEBUG:
15
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
16
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
17
index.html from where people can download the file
JavaScript
1
17
17
1
<!DOCTYPE html>
2
<html lang="en">
3
<head>
4
<meta charset="UTF-8">
5
<title>hello</title>
6
</head>
7
<body>
8
{% for post in file%}
9
<h2>{{post.name}}</h2>
10
<a href="{{post.adminupload.url}}" download="{{post.adminupload.url}}">Download</a>
11
12
{% endfor %}
13
14
15
</body>
16
</html>
17
Advertisement
Answer
Try using Axios to download the file,
In the template, Try this-
JavaScript
1
45
45
1
<!DOCTYPE html>
2
<html lang="en">
3
4
<head>
5
<meta charset="UTF-8">
6
<title>hello</title>
7
</head>
8
9
<body>
10
{% for post in file %}
11
<h2>{{post.name}}</h2>
12
<button onclick="downloadFile('{{ post.adminupload.url }}', '{{ post.id }}')">Download file</button>
13
{% endfor %}
14
</body>
15
16
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.1/axios.min.js"></script>
17
<script>
18
function downloadFile(file_url, id) {
19
axios({
20
method: "GET",
21
url: file_url,
22
responseType: 'blob',
23
onDownloadProgress: event => {
24
if (event.loaded === event.total) {
25
// send a GET request to the backend telling that download is complete
26
axios({
27
method: "GET",
28
url: "/post-downloaded/" + id, // send id of the post, user is downloading
29
})
30
.then(console.log("download incremented"))
31
.catch(error => console.log(error))
32
}
33
}
34
}).then(response => {
35
// download the file
36
const aTag = document.createElement("a");
37
aTag.href = URL.createObjectURL(resp.data);
38
aTag.download = "filename." + resp.data.type.split("/")[1];
39
aTag.click();
40
})
41
}
42
</script>
43
44
</html>
45
Now in the backend, create a route for /post-downloaded/
In your urls.py file-
JavaScript
1
16
16
1
from django.contrib import admin
2
from django.urls import include, path
3
from django.conf import settings
4
from django.conf.urls.static import static
5
from libooki import views
6
from django.views.static import serve
7
8
urlpatterns = [
9
path('', views.index,name='index'),
10
path('post-downloaded/<int:pk>', views.post_downloaded), # add this route
11
path('admin/', admin.site.urls),
12
]
13
if settings.DEBUG:
14
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
15
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
16
And in the views.py file create this-
JavaScript
1
14
14
1
from django.shortcuts import render
2
from django.http import HttpResponse
3
from .models import FilesAdmin
4
5
def index(request):
6
context = {'file': FilesAdmin.objects.all()}
7
return render(request,'libooki/index.html',context)
8
9
def post_downloaded(request, pk):
10
file = FilesAdmin.objects.get(pk=pk)
11
file.total_downloads += 1
12
file.save()
13
return HttpResponse("download added")
14
This should get the work done