在Django中基于类的通用视图中插入request.session

时间:2014-02-20 09:23:05

标签: python django session detailview

我正在尝试使用request.session创建一个“最近的”会话密钥并添加用户访问的产品页面以使其可以在模板中访问,这是我的观点,你们会推荐什么,我可以好像这样做

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

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

感谢Daniel Roseman关于如何从基于类的通用视图调用会话的说明

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