Insert request.session in class based Generic view in Django

别说谁变了你拦得住时间么 提交于 2021-02-10 18:30:07

问题


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

Thanks for your help!


回答1:


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


来源:https://stackoverflow.com/questions/21903365/insert-request-session-in-class-based-generic-view-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!