您必须在单击按钮时对您的 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>