Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if the user is visiting the page for the first time

In general how do we know if user is visiting the page for the first time? Technically, do we store the number of visits to each page in the Model(I am using django) or is there some other pattern that I could follow to ease up the operation.

I m just looking for a design for implementing this.

like image 327
chipmunk Avatar asked Mar 29 '13 08:03

chipmunk


1 Answers

I think you will have to create your own mechanism for this.

I would make a model storing first visits for every url and user called e.g FirstVisit. Then if a user requests a page in a view you can search if there is an entry in FirstVisit for current user and url and find out if it's his first time or not. After that, if he hasn't visited yet, you store the entry to the FirstVisit model, because he is just going to get the content of the page.

I will try and write the code:

#models.py

class FirstVisit(models.Model):
    url = models.URLField()
    user = models.ForeignKey('auth.User')


#views.py

def my_view(request):
   if not FisrtVisit.objects.filter(user=request.user.id, url=request.path).exists():
      #he visits for the first time
      #your code...
      FisrtVisit(user=request.user, url=request.path).save()

You can create a decorator and put in there this functionality. Then add the decorator to any view you want to store this information and from the decorator pass a flag argument to the view determining if user is there for the first time.

like image 128
davekr Avatar answered Oct 21 '22 17:10

davekr