问题
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