0

我正在为详细信息页面使用 Django 通用视图。我知道我可以将detailview其用于我想坚持使用通用视图的详细信息页面。但我的要求是实现 Django 命中计数。我不知道如何实现这一点。这是我的模型示例:

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

视图在这里:

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

4

2 回答 2

0

你的意思是这样的?

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
于 2020-07-22T16:25:17.710 回答
0
pip install django-hitcount
    
INSTALLED_APPS = (
    'hitcount',
)

模型.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')

视图.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

在您的主项目的 urls.py 中,您需要添加 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 %}
于 2020-07-22T17:03:59.923 回答