3

In a Django project of mine, I want to log all unique user IDs visiting a certain section of the web application. Currently, the only distinguishing feature of this section is that it's url patterns are written in a separate module.

What would be the best way to track unique users who visit these url patterns? Doing it as costlessly (resources wise) as possible is what I mean by 'best'. An illustrative example would be great.

Hassan Baig
  • 15,055
  • 27
  • 102
  • 205

1 Answers1

2

Something like google analytics would suit this task

However, if you wish to implement something yourself in Django I would suggest something like the following

class TrackUniqueVisitsMiddleware(object):

    def process_request(self, request):
        if not request.user.is_authenticated:
            return
        if request.resolver_match.namespace in settings.NAMESPACES_TO_TRACK:
            UniqueUserVisit.objects.get_or_create(
                user=request.user,
                namespace=request.resolver_match.namespace,
                view_name=request.resolver_match.view_name
            )

Where UniqueUserVisit is a model that stores all unique views that a user has visited. UniqueUserVisit can then be queried to generate reports on user activity.

request.resolver_match.namespace contains the namespace of the visited url.

request.resolver_match.view_name contains the full name of the url.

Iain Shelvington
  • 31,030
  • 3
  • 31
  • 50
  • Yep, GA would be good for this, but I need some really customized, micro reporting, and there's no GA expert in sight (have tried their various generic report views already). So just looking to quickly build something myself that gets the job done efficiently, without fuss. – Hassan Baig Jul 27 '17 at 16:09
  • I'm using `redis` as a backend for this, so there's going to be that one change in the code you wrote. Otherwise, looks good! – Hassan Baig Jul 27 '17 at 16:14