How do I count number of visitors on a Django website?

Viewed 8908

How do I count visitors on my website so that it increments every time a user visits the website. I can count number of views by visitors using following codes:

def blog_detail(request, blog_slug):
    blog = get_object_or_404(Blog, slug=blog_slug)
    session_key = 'blog_views_{}'.format(blog.slug)
    if not request.session.get(session_key):
        blog.blog_views += 1  # here
        blog.save()
        request.session[session_key] = True

    context = {
        'blog': blog,
        'categories': get_category_count()
    }

    return render(request, 'blogs/blog-detail.html', context)

while having blog_views field in my models. I don't know if there is any similar way of doing it just to count number of times my website is visited.

Some suggested using hitcount but I couldn't use it anywhere other than generic views. If you suggest it as well please elaborate it further with some codes thank you. Thank you so much.

4 Answers

Instead of adding the "counting" logic on every view you can write a middleware class for that. Something like this:

def hitcount_middleware(get_response):

    def middleware(request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.

        response = get_response(request)

        # Get the URL from the `request` parameter and save it 
        # in a Hitcount model.

        return response

    return middleware

By doing this,

  • all your logic will be in the same place (i.e. easy to mantain),
  • the code in your views will be cleaner,
  • can be enabled/disabled easily,
  • can be optimized easily (using Django cache for example).

Hope it helps.

Unsure if your question remains, but there are few projects that might help you. There's Django-visits that count requested urls (CounterMiddleware) or count object visits.

from visits.models import Visits

def some_object_view(request, pk):
    some_obj = get_object_or_404(SOME_MODEL, pk=pk)
    Visit.objects.add_object_visit(request, obj=some_obj)

There's also the django-hitcount project that enables several options to count hits on pages or objects.

from django.db import models

from hitcount.models import HitCountMixin

# here is an example model with a GenericRelation
class MyModel(models.Model, HitCountMixin):

  # adding a generic relationship makes sorting by Hits possible:
  # MyModel.objects.order_by("hit_count_generic__hits")
  hit_count_generic = GenericRelation(
    HitCount, object_id_field='object_pk',
    related_query_name='hit_count_generic_relation')

# you would access your hit_count like so:
my_model = MyModel.objects.get(pk=1)
my_model.hit_count.hits                 # total number of hits
my_model.hit_count.hits_in_last(days=7) # number of hits in last seven days

Add below code in view function and home.html template page

views.py

 def HOME(request):
    "#Number of visits to this view, as counted in the session variable."
    num_visits = request.session.get('num_visits', 0)
    request.session['num_visits'] = num_visits + 1
    context = {'num_visits': num_visits
    }
    return render(request,'home.html',context=context)

home.html

Visitors Count {{ num_visits }}

This will give count on the mail home page whenever it is refreshed.

Related