pip install django-hitcount
INSTALLED_APPS = (
'hitcount',
)
models.py
class Post(models.Model):
title = models.CharField(max_length=100)
hit_count_generic = GenericRelation(HitCount,
object_id_field='object_pk',
related_query_name='hit_count_generic_relation')
views.py
#you need to import and use HitCountDetailView instead of just DetailView
from hitcount.views import HitCountDetailView
class PostListView(ListView):
model = Post
template_name = 'post_list.html'
context_object_name = 'post'
class PostDetailView(HitCountDetailView):
model = Post
template_name = 'post_detail.html'
context_object_name = 'post'
slug_field = 'slug'
count_hit = True
def get_context_data(self, **kwargs):
context = super(PostDetailView, self).get_context_data(**kwargs)
context.update({
'popular_posts': Post.objects.order_by('-hit_count_generic__hits')[:3],
})
return context
In your main project's urls.py you need to add hitcount
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('hitcount/', include(('hitcount.urls', 'hitcount'),
namespace='hitcount')),
]
post_list.html
{% extends 'base.html' %}
{% load hitcount_tags %}
{% block content %}
<h2>Posts List</h2>
<ul>
{% for post in posts %}
<p>Views: {% get_hit_count for post %}</p>
{% endfor %}
</ul>
{% endblock %}