在Django中基于类的通用视图中插入request.session [英] Insert request.session in class based Generic view in Django
本文介绍了在Django中基于类的通用视图中插入request.session的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用request.session创建一个最近的"会话密钥,并添加用户访问的产品页面以使其可在模板中使用,这是我的看法,你们会建议些什么,我可以似乎不打算这样做
I'm trying to use request.session to create a 'recent' session key and add the product pages visited by the user to make it accesible in the template, here is my view, what would you guys recommend, I can't seem to go about doing this
class ProductDetail(DetailView):
model = Producto
template_name = 'productos/product_detail.html'
def get_context_data(self, **kwargs):
# Call the base implementation first to get a context
context = super(ProductDetail, self).get_context_data(**kwargs)
# Add in a QuerySet of featured products
context['product_list'] = Producto.objects.filter(featured=True).exclude(pk=self.object.pk)
return context
感谢您的帮助!
推荐答案
感谢Daniel Roseman阐明了如何从基于类的通用视图调用会话
thanks to Daniel Roseman for the clarification on how to call session from the class based generic view
class ProductDetail(DetailView):
model = Producto
template_name = 'productos/product_detail.html'
def get_context_data(self, **kwargs):
# Call the base implementation first to get a context
context = super(ProductDetail, self).get_context_data(**kwargs)
if not 'recent' in self.request.session or not self.request.session['recent']:
self.request.session['recent'] = [self.object.pk]
else:
recentList = self.request.session['recent']
recentList.append(self.object.pk)
self.request.session['recent'] = recentList
# Add in a QuerySet of featured products
context['product_list'] = Producto.objects.filter(featured=True).exclude(pk=self.object.pk)
context['recent_list'] = Producto.objects.filter(pk__in=recentList)
return context
这篇关于在Django中基于类的通用视图中插入request.session的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文