简体   繁体   中英

Django context processor being called twice per request

I've found only one topic like this and not a single answer in there seems to work. I have two context processors:

def cart_view(request):
    try:
        cart_id = request.session['cart_id']
        cart = Cart.objects.get(id=cart_id)
        request.session['total'] = cart.items.count()
        print('OLD CART USED')
    except:
        cart = Cart()
        cart.save()
        cart_id = cart.id
        request.session['cart_id'] = cart_id
        cart = Cart.objects.get(id=cart_id)
        print('NEW CART CREATED')
    return {'cart':cart}

# dropdown menu categories to every page
def categories(request):
    print('CATEGORIES CONTEXT PROCCESOR')
    categories = Category.objects.all()
    return {'dropdown_categories':categories}

Settings:

            'context_processors': [
            'django.template.context_processors.debug',
            'django.template.context_processors.request',
            'django.contrib.auth.context_processors.auth',
            'django.contrib.messages.context_processors.messages',
            'django.template.context_processors.media',
            'shopping.views.cart_view',
            'shopping.views.categories',
             ]

Via those print statements I'm able to see that each one of those CP being executed twice per request, although I'm rendering just base.html . What may be the problem?

import traceback; traceback.print_stack() import traceback; traceback.print_stack() gives this two times:

PS I know that I'm querying the DB every time I use CP, I'll add caching later.

Cosole log(that's one page load):

OLD CART USED
CATEGORIES CONTEXT PROCCESOR
[30/Aug/2018 18:56:13] "GET / HTTP/1.1" 200 2651
OLD CART USED
CATEGORIES CONTEXT PROCCESOR
[30/Aug/2018 18:56:13] "GET / HTTP/1.1" 200 2651

View:

class HomePageView(TemplateView):
    template_name = 'base.html'

Project URLs:

urlpatterns = [re_path(r'^',include('shopping.urls',namespace='shop'))]

App's URLs:

urlpatterns = [re_path(r'^$',views.HomePageView.as_view(),name='home')]

Well, I don't what magic is this but the issue of getting two requests per page load had something to do with this line of code in my base.html :

<img src="#" width="30" height="30" class="d-inline-block align-top" alt="">

As soon as I deleted it, everything started to work normaly...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM