Malcom Swarez
Malcom Swarez

Reputation: 53

how to use Django Hitcount in a function based view rather than a class?

The documentation covered only the usage of Django-Hitcount in a class-based 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

Is there any way to use it in a function?

Upvotes: 5

Views: 1327

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476557

It is possible, you only need to implement the logic that the HitCountDetailView implements [GitHub].

So for a function-based view that "hits" an object of MyModel this looks like:

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)

This however to some extent illustrates that a class-based view is more suited for such tasks: one can easily define the logic in reusable components, and thus mix it in the existing logic.

Upvotes: 4

Related Questions