'Total download count for an item in Django

I am making a website where users can download the freebies. I want to log the total downloads for each item and then display this value in my backend. Currently, I am using this function to allow users to download files from the static folders.

MODEL:

upload = models.FileField(upload_to ='uploads/')
downloads = models.ManyToManyField(User, related_name='post_download')

URL:

path('downloads/<int:pk>', DownloadView, name= 'download_post'),

VIEW:

def DownloadView(request, pk):
    post = get_object_or_404(Item, id=request.POST.get('item_id'))
    post.downloads.add(request.user)
    return HttpResponseRedirect(reverse('item_detail', args=[str(pk)]))

TEMPLATE:

<div class="flex items-center justify-center">
            <a href="{{item.upload.url}} " class="text-white w-full  text-center bg-black p-4 rounded-lg mt-8 hover:bg-gray-800"><button>Download this file | <span class="text-xs text-green-400">{{object.upload.size|filesizeformat}}</span></button></a>
        </div>


Solution 1:[1]

Simple solution would be to add a model field to your model, indicating the total count of downloads for each object like so:

class MyModel(models.Model):
    ....
    download_count = models.PositiveIntegerField(default=0, blank=False, 
    null=False)
    
    def increment_download_count(self):
        """ Increments download_count of an instance by 1"""
        self.download_count += 1

Next, in your view, you'd have to add something along these lines to increment the download count for the current object.

def DownloadView(request, pk):
    post = get_object_or_404(Item, id=request.POST.get('item_id'))
    post.downloads.add(request.user)
    post.increment_download_count()
    return HttpResponseRedirect(reverse('item_detail', args=[str(pk)]))

In your template, you could display the current count of the downloads by doing:

{{obj.download_count}}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 psky