Skip to main content
2025 Python Packaging Survey is now live!  Take the survey now

Count visits using cache for Django models

Project description

Django Visit Count

Count visits using cache for Django models.

Installation

  1. Set-up Django's cache framework.

  2. Install the Python package.

    pip install django_visit_count
    

Usage

Use VisitCountMixin. It adds a visit_count field to your model.

from django_visit_count.mixins import VisitCountMixin

class MyBlogPost(VisitCountMixin, models.Model):
    ...

Create and run migrations on your model.

$ python manage.py makemigrations my_blog_app
$ python manage.py migrate my_blog_app

Count visits in your view like this:

def view_blog_post(request, post_id):
    post = get_object_or_404(MyBlogPost, pk=post_id)
    post.count_visit(request)
    ...

Advanced Usage

If you need more control, you can use is_new_visit function.

class MyBlogPost(models.Model):
    total_visits = models.PositiveIntegerField(default=0)
    ...
from django_visit_count.utils import is_new_visit

def view_blog_post(request, post_id):
    post = get_object_or_404(MyBlogPost, pk=post_id)

    if is_new_visit(request, post):
        post.total_visits = F("total_visits") + 1
        post.save(update_fields=["total_visits"])

    ...

You can pass an optional keyword argument session_duration (integer, number of seconds) to count_visit or is_new_visit.

Settings

Default settings:

VISIT_COUNT_DEFAULT_SESSION_DURATION = 5 * 60  # seconds

Development

  • Install development dependencies in your virtualenv with pip install -e '.[dev]'
  • Install pre-commit hooks using pre-commit install.

License

MIT

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page