简体   繁体   中英

how to make a videos view counter like instagram in django?

for example count the number of views if played for 3 or more seconds and unique for each user. should i make a timer in front end and request the update counter if played for more than 3 seconds. how does Instagram do it. my model attributes.

class video():
    name
    views_counter
    video_file

I guess you can take a look at HTML Audio/Video DOM ontimeupdate event and CurrentTime property

here's an example

model

class Video(models.Model):
title = models.CharField()
video_file = models.FileField()
viewers = models.ManyToManyField(UserModel)

views

def video_viewer_add(request, pk):
video = get_object_or_404(Video, pk=pk)
if request.method == 'GET':
    if request.user not in video.viewers.all():
        video.viewer.add(request.user)
    video.save()
    return HttpResponse()

urls

path('videos/<int:pk>/', views.video_viewer_add, name='add_video_view')

html

<video id = "video" width = "" height = "" video-url = "{% url 'add_video_view' video.pk %}" controls >

js

<script>var vid = document.getElementById("video") vid.ontimeupdate = function(){myFunction()}function myFunction(){(vid.currentTime=5) {$.ajax({url: vid.attr("video-url"),type: 'get',dataType: 'json',success: function() {alert('video viewed')}})}}</script >

check video views with

{{video.viewers.count}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM