在Djang中的类基础泛型视图中插入 request.session

2024-03-28 11:56:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着用请求.会话要创建一个'最近'会话密钥,并添加用户访问的产品页面,使其在模板中可访问,这是我的观点,你们会推荐什么,我似乎不能继续这样做

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

谢谢你的帮助!在


Tags: 用户self模板dataget产品context密钥
1条回答
网友
1楼 · 发布于 2024-03-28 11:56:38

感谢danielroseman解释了如何从基于类的泛型视图调用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)
        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

相关问题 更多 >