首页 > 解决方案 > 计算用户在 Django 中上传的 PDF 的页面浏览量

问题描述

我有一个网络应用程序,用户可以在其中上传 pdf。我希望能够查看其他用户查看 PDF 的次数,所有这些用户都是匿名用户。目前我不必编写视图来查看 PDF,在“查看 PDF”按钮中,我只需链接上传的 PDF 的 URL,该 URL 指向 PDF 文档。

用于查看 PDF 的按钮

<a href="{{ doc.File.url }}" class="btn btn-outline-secondary" style="margin: 2px;">View PDF</a>

问题出现了,当用户上传 PDF 文档时,我创建了一个包含该文档 URL 的二维码。所以我只想计算来自 qr 扫描的视图,而不是从按钮重定向的视图。由于我实际上没有呈现 PDF 的视图,我该如何做到这一点?

我想到的一种方法是编写一个返回重定向视图,并为模型中的视图实例添加一个增量器?或者使用 Django F() 语句来拉入视图实例,然后增加它。

有任何想法吗?

标签: djangopdfhitcounter

解决方案


您必须在按钮单击时对您的 views.py 进行 Ajax 调用并更新模型实例 view_count 字段。

示例 模型.py

# I am taking a sample model
class Document(models.Model):
    File = models.FileField(upload_to='uploads/')
    count = models.IntegerField(default=0)

视图.py

from django.http import HttpResponse
def index(request,id):
    doc = Document.objects.get(pk=id) #whatever file you are serving
    if request.is_ajax():
        if request.method == 'POST':
           #if you don't want to increment when file author opens then you can write the condition here 
           doc.count = doc.count+1 #incrementing your file view count
           doc.save()
           return HttpResponse({'msg': 'success'}, content_type="application/json")
    return render(request,'index.html',{'doc':doc}) 

我将使用按钮来避免在 ajax 响应之前重定向,而不是使用锚点。

索引.html

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    
<button id="view_pdf" href="{{ doc.File.url }}" class="btn btn-outline-secondary" style="margin: 2px;">View PDF</button>

<script>
$("#view_pdf").on('click', function(){
     $.ajax({
            type: 'POST',
            url: '',
            dataType: 'json',
            cache: false,
            async: true,
            data: {
               csrfmiddlewaretoken: "{{csrf_token}}",
            },
            success: function(json){
              window.location.href = "{{ doc.File.url }}" // you can redirect to your pdf here
            },
            error: function(XMLHttpRequest, textStatus, errorThrown){
                alert(errorThrown);
            }
     });
});

</script>

推荐阅读