django - 计算用户在 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() 语句来拉入视图实例,然后增加它。
有任何想法吗?
解决方案
您必须在按钮单击时对您的 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>
推荐阅读
- laravel - 直接在控制器中从 AWS S3 返回图像的最佳方法?
- git - VS2019 Preview 4:将 Blazor Server App 添加到 Visual Studio Team Foundation Server Source Control 将其添加到 Git
- android - Kotlin CoroutineScope 无法在 android 视图中取消
- html - 如何调整 bootstrap-vue 表的高度并使其可使用固定标题滚动
- python - Pandas 数据框应用速度问题 - 还有其他方法吗?
- debugging - 是否有任何代码可以使用任何 UWP 操作本地存储
- neo4j - 相关节点上的 Cypher 查询过滤器
- android - 如何使用 android 中的互联网连接检查手机检查服务器连接是否可用?
- c# - 使用 SQL Server Management Studio 时如何在 web.config 中添加连接字符串?
- xamarin.forms - 消息中心未从 xamarin ios 任务调用