我正在尝试使用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


谢谢你的帮助!

最佳答案

感谢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

09-17 22:46