我正在使用django-hitcount,但对我的应用在views.py
内的点击计数感到困惑。该文档建议使用此
from hitcount.models import HitCount
from hitcount.views import HitCountMixin
# first get the related HitCount object for your model object
hit_count = HitCount.objects.get_for_object(your_model_object)
# next, you can attempt to count a hit and get the response
# you need to pass it the request object as well
hit_count_response = HitCountMixin.hit_count(request, hit_count)
# your response could look like this:
# UpdateHitCountResponse(hit_counted=True, hit_message='Hit counted: session key')
# UpdateHitCountResponse(hit_counted=False, hit_message='Not counted: session key has active hit')
但是,我不是在寻找对HitCount对象的响应。我只想以类似于模板标签提供方式的方式来计算点击次数,就像这样
{% get_hit_count for [object] within ["days=1,minutes=30"] %}
在views.py
内的给定时间范围内,如何精确地获得对象的点击计数?
答案 0 :(得分:0)
我有同样的困境。因此,我研究了他们的观点,并在基于函数的观点中实现了您的要求。假设我们要计算用户个人资料中的所有观看次数。视图:
import hitcount # import entire package
from hitcount.models import HitCount
def profile(request):
my_profile = Profile.objects.get(user=request.user)
# mark it
hit_count = HitCount.objects.get_for_object(my_profile)
hit_count_response = hitcount.views.HitCountMixin.hit_count(request, hit_count)
# count the views
profile_views = my_profile.hit_count.hits
return render( request, 'profile.html', locals() )
我发现我必须导入整个点击计数包才能与hitcount.views.HitCountMixin
一起使用。我猜我的应用将hitcount.views.HitCountMixin
与hitcount.models.HitCountMixin
混淆了,可能是因为我已经从models.py
导入了所有内容。因此,如果您在views.py中拥有from .models import *
像我一样,明智的做法是导入整个程序包以指定要引用的HitCountMixin ...就像上面的代码中一样
无论如何,请确保您要计算点击数的模型是从hitcount.models.HitCountMixin
继承的,并确保您与hitcount.models.HitCount)
有通用关系,例如
from hitcount.models import HitCountMixin, HitCount
class Profile(models.Model, HitCountMixin):
user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
hit_count_generic = GenericRelation( HitCount, object_id_field='object_pk',
related_query_name='hit_count_generic_relation' )
就是这样。注销并再次登录到您的应用程序-我想刷新Django会话框架(我必须这样做)。然后,在模板中,像常规本地一样调用配置文件视图...
<p> Profile Views: {{profile_views}} </p>