0

I'me using Django generic views for the detail page. I know I can use detailview for the detail page I want to stick with a generic view. But my requirement is to implement Django hit count. I didn't know how to implement this one. Here is my model example:

class A(models.Mode):
    title = models.CharField(..)
    ...

The view is here:

class PostDetailView(View):
    def get(self, request):
        ...

iknow
  • 8,358
  • 12
  • 41
  • 68
Sandeep
  • 33
  • 1
  • 5

2 Answers2

0

You mean something like this?

class A(models.Mode):
    title = models.CharField(..)
    times_viewed = models.IntegerField(...

class PostDetailView(View):
  def get_object(self):
          obj = super().get_object()
          obj.times_viewed += 1
          obj.save()
          return obj
bkrop
  • 228
  • 2
  • 10
0
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 %}
Arthur
  • 21
  • 4