【问题标题】:Counting page views for a User uploaded PDF in Django计算用户在 Django 中上传的 PDF 的页面浏览量
【发布时间】:2020-07-27 12:43:29
【问题描述】:

我有一个网络应用程序,用户可以在其中上传 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() 语句来拉入视图实例,然后增加它。

有什么想法吗?

【问题讨论】:

  • 能否请您分享您的模型以保存 pdf 和视图。
  • 数据不足请分享您的模型和观点。

标签: django pdf hitcounter


【解决方案1】:

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

示例 models.py

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

views.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 响应之前重定向,而不是使用锚点。

index.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>

【讨论】:

    【解决方案2】:

    对于二维码,您可以将 URL 编码为URL + "&amp;qr=true"。这样,它就会以不同的 URL 显示在您的 HTTP 日志中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-24
      • 2015-03-24
      • 1970-01-01
      • 2018-01-08
      • 2013-06-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多