backend/django

django hitcount: counting hit (views) in django

seul chan 2018. 2. 20. 21:35

It’s not that difficult to counting every detail page in your website.

But I found very easy and great library for that - [django-hitcount](https://github.com/thornomad/django-hitcount/blob/master/example_project/blog/models.py)

Installing

using pip

pip install django-hitcount

and add it to INSTALLED_APPS

# settings.py
INSTALLED_APPS = (
    ...
    'hitcount'
)

Also you can use several settings - active days, ip limit, exclude user group and so on. check here for more information.

Usage

You should inherit hitcount for model, and detailview.

Model

Just inherit HitCountMixin. And that’s all!

from hitcount.models import HitCount, HitCountMixin


@python_2_unicode_compatible
class Post(models.Model, HitCountMixin):
    title = models.CharField(max_length=200)
    content = models.TextField()
    ...

    def __str__(self):
        return "Post title: %s" % self.title

View

You just inherit HitCountDetailView and add count_hit = True.

from hitcount.views import HitCountDetailView

from community.models import Post


class PostDetailView(HitCountDetailView):
    model = Post
    count_hit = True
    ...

Template

{# the primary key for the hitcount object #}
{{ hitcount.pk }}

{# the total hits for the object #}
{{ hitcount.total_hits }}


'backend > django' 카테고리의 다른 글

django test plus  (0) 2018.02.27
django model test - model_mommy  (0) 2018.02.26
django: reversed forloop in template  (0) 2018.02.19
django: using queryset chainable model manager  (0) 2018.02.17
django: postgres full text search mixin  (0) 2018.02.16