django - 如何在基于函数的 View 而不是类中使用 Django Hitcount?

标签 django django-models django-views django-templates

该文档仅涵盖了 Django-Hitcount 在基于类的 View 中的使用。

from hitcount.views import HitCountDetailView

class PostCountHitDetailView(HitCountDetailView):
    model = Post        # your model goes here
    count_hit = True    # set to True if you want it to try and count the hit
有没有办法在函数中使用它?

最佳答案

有可能,你只需要实现 HitCountDetailView implements [GitHub]的逻辑即可。 .
因此,对于“命中”MyModel 的对象的基于函数的 View 这看起来像:

from hitcount.utils import get_hitcount_model
from hitcount.views import HitCountMixin

def some_view(request, pk):
    object = get_object_or_404(MyModel, pk=pk)
    context = {}

    # hitcount logic
    hit_count = get_hitcount_model().objects.get_for_object(object)
    hits = hit_count.hits
    hitcontext = context['hitcount'] = {'pk': hit_count.pk}
    hit_count_response = HitCountMixin.hit_count(request, hit_count)
    if hit_count_response.hit_counted:
        hits = hits + 1
        hitcontext['hit_counted'] = hit_count_response.hit_counted
        hitcontext['hit_message'] = hit_count_response.hit_message
        hitcontext['total_hits'] = hits

    # … extra logic …

    return render(request, 'my_template.html', context)
然而,这在某种程度上说明基于类的 View 更适合此类任务:人们可以轻松地在可重用组件中定义逻辑,从而将其混合到现有逻辑中。

关于django - 如何在基于函数的 View 而不是类中使用 Django Hitcount?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64278071/

相关文章:

python - Django Slug 生成的 URL 返回 : 'No Fund matches the given query.'

python - 图表未显示在我的 html-Django 中(在 html 中嵌入动态图表)

django - LinkedIn REST API 无法发送消息;无法解析邮箱项目文档 : error: Unexpected end of file after null

python - 原始查询和自定义 sql 查询最快的是什么?

python - 如何使用查询字符串过滤 Django 中的查询集?

mysql - django 查询中混合注释和聚合

python - 在 Django 中使用动态字段过滤器生成报告

database - 在 Django 中,如何在我的 models.py 中包含一些默认记录?

python - 值错误 : too many values to unpack (expected 2) in Django

python - Recaptcha 不显示 Django1.5 中的 Django 注册