Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在基于函数的视图而不是类中使用Django Hitcount?_Django_Django Models_Django Views_Django Templates - Fatal编程技术网

如何在基于函数的视图而不是类中使用Django Hitcount?

如何在基于函数的视图而不是类中使用Django Hitcount?,django,django-models,django-views,django-templates,Django,Django Models,Django Views,Django Templates,文档仅介绍了Django Hitcount在基于类的视图中的使用 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

文档仅介绍了Django Hitcount在基于类的视图中的使用

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

有没有办法在函数中使用它?

有可能的话,您只需要实现

因此,对于基于函数的视图,它“命中”了
MyModel
的对象,如下所示:

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)
从hitcount.utils导入get\u hitcount\u模型
从hitcount.views导入HitCountMixin
定义某些视图(请求、主键):
对象=获取对象或404(MyModel,pk=pk)
上下文={}
#命中逻辑
hit_count=get_hitcount_model().objects.get_for_object(object)
点击次数=点击次数
hitcontext=context['hitcount']={'pk':hit_count.pk}
hit\u count\u response=HitCountMixin.hit\u count(请求、hit\u count)
如果hit\u count\u response.hit\u counted:
点击次数=点击次数+1
hitcontext['hit_counted']=hit_count_response.hit_counted
hitcontext['hit_message']=hit_count_response.hit_message
hitcontext['total_hits']=点击次数
#…额外的逻辑…
返回渲染(请求'my_template.html',上下文)

然而,这在某种程度上说明了基于类的视图更适合此类任务:可以在可重用组件中轻松定义逻辑,从而将其与现有逻辑混合。

您可以实现HitCountDetailView实现的逻辑。是: