serve() is called twice everytime I reload a blog page in wagtail


This Content is from Stack Overflow. Question asked by elf

I am using wagtail to build a blog website. In order to count the visits of each blog, I override the get_context() and serve() to set cookie. The codes are as follows:

def get_context(self, request):
        data = count_visits(request, self)

        context = super().get_context(request)
        context['client_ip'] = data['client_ip']
        context['location'] = data['location']
        context['total_hits'] = data['total_hits']
        context['total_visitors'] =data['total_vistors']
        context['cookie'] = data['cookie']
        return context
    def serve(self, request):
        context = self.get_context(request)
        template = self.get_template(request)
        response = render(request, template, context)
        response.set_cookie(context['cookie'], 'true', max_age=3000)
        return response

And the function count_visits is as follows:

def count_visits(request, obj):       
    ct = ContentType.objects.get_for_model(obj)
    key = "%s_%s_read" % (ct.model,
    count_nums, created = VisitNumber.objects.get_or_create(id=1)
    if not request.COOKIES.get(key):      
        blog_visit_count, created =BlogVisitNumber.objects.get_or_create(content_type=ct,
        count_nums.count += 1
        blog_visit_count.count += 1

The problem I met is that when I reload the blog page, serve() was loaded twice. The first time request was with cookie info. But the second time the cookie of the request was {}, which caused the count of visit does not work correctly.
I do not understand why serve() is called twice everytime I reload page.


This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?