代码之家  ›  专栏  ›  技术社区  ›  javiercf

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

  •  1
  • javiercf  · 技术社区  · 10 年前

    我正在尝试使用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 回复  |  直到 10 年前
        1
  •  1
  •   javiercf    10 年前

    感谢DanielRoseman对如何从基于类的通用视图调用会话的说明

    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