[Django]-Django โ€“ tracking authenticated users page vistis

3๐Ÿ‘

โœ…

All i need to know is what my authenciated users are visiting and how many times.

First thing that comes to mind is creating a model with a foreign key to user and a charfield for the view that they requested.

class Request(models.Model):
    user = models.ForeignKey(User)
    view = models.CharField(max_length=250) # this could also represent a URL
    visits = models.PositiveIntegerField()

This will give you the ability to count the number of times a user has hit a page.

def some_view(req, *a, **kw):
    # try to find the current users request counter object
    request_counter = Request.objects.filter(
        user__username=req.user.username, 
        view="some_view"
    )
    if request_counter:
        # if it exists add to it
        request_counter[0].visits += 1
        request_counter.save()
    else:
        # otherwise create it and set its visits to one.
        Request.objects.create(
            user=req.user,
            visits=1,
            view="some_view"
        )

If you take the time you can isolate this logic into one well written function and call it at the beginning of each view.

def another_view(req, *a, **kw):
    count_request() # all logic implemented inside this func.

Alternatively with class based views.

class RequestCounterView(View):
    
    def dispatch(req, *a, **kw):
        # do request counting
        return super(RequestCounterView, self).dispatch(*a, **kw)


class ChildView(RequestCounterView):
    def get(req, *a, **kw):
        # continue with regular view
        # this and all other views that inherit 
        # from RequestCounterView will inherently 
        # count their requests based on user.
๐Ÿ‘คmarcusshep

Leave a comment