Jay P.
Jay P.

Reputation: 2590

How can I show elapsed time in Django

So, I'm trying to show elapsed time on a page for recent-visited history. On my model, I have the following attribute.

models.py

class History(models.Model):
    ...
    created_on = models.DateTimeField(auto_now_add=True)
    ...

I already checked the date documentation, but it doesn't have a way to represent elapsed time from creating time to now. Doesn't Django support the feature? then should I implement it on my own?

Upvotes: 0

Views: 889

Answers (1)

Lemayzeur
Lemayzeur

Reputation: 8525

As far I know Django doesn't have such function. It's better to implement your own. With js for instance by using setInterval() and Ajax to update a specific time field.

Before that, you need to add a field to record when leaving the page.

created_on = models.DateTimeField(auto_now_add=True)
left_at = models.DateTimeField(auto_now_add=True)

Js
It's important that you have this script in your HTML page, since we'll use Django variables.

var id_obj = '{{ obj.id }}'; // $('tag').val();
totalSeconds = 5;
setInterval(function(){
     recordElapsedTime();
},totalSeconds * 1000);

var recordElapsedTime = function(){
    $.ajax({
         url:"/url/to/view/",
         type:"POST",
         data:{
             id_obj:id_obj,
             csrfmiddlewaretoken:'{{ csrf_token }}'
         },
    });
}

View

 import datetime

 def elapsedTime(request):
     if request.method == 'POST' and request.is_ajax():
         id_obj = request.POST.get('id_obj')
         obj = get_object_or_404(ObjectModel,id=id_obj)
         obj.left_at = datetime.datetime.now()
         obj.save()

Now it's pretty easy to determine the elapsed time, as a property method in Model for instance.

@property
def elapsed_time(self)
    return (self.left_at - self.created_on).seconds

Upvotes: 1

Related Questions