[英]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
. 通过这些打印语句,我可以看到每个请求中的每个CP都执行两次,尽管我只是渲染base.html
。 What may be the problem? 可能是什么问题?
import traceback; traceback.print_stack()
import traceback; traceback.print_stack()
gives this two times: import traceback; traceback.print_stack()
给出两次:
PS I know that I'm querying the DB every time I use CP, I'll add caching later. PS:我知道每次使用CP时都要查询数据库,以后再添加缓存。
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
: 好吧,我不是什么魔术,但是每页加载获取两个请求的问题与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... 我一删除它,一切便开始正常工作...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.