Django:修改基于类的视图上下文(带有** kwargs)

时间:2018-12-11 21:29:39

标签: python django

我有一个完美的功能定义,但是我需要更新为基于类的视图。

功能定义:

def ProdCatDetail(request, c_slug, product_slug):
    try:
        product = Product.objects.get(category__slug=c_slug, slug = product_slug)
    except Exception as e:
        raise e
    return render(request, 'shop/product.html', {'product':product})

到目前为止,我已经读过要修改基于类的视图(CBV)的上下文,我需要覆盖CBV中的def get_context_data(self, **kwargs)

所以,我这样做了:

基于类的视图:

class ProdCatDetailView(FormView):
    form_class = ProdCatDetailForm
    template_name = 'shop/product.html'
    success_url = 'shop/subir-arte'


    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['product'] = Product.objects.get(category__slug=c_slug, slug = product_slug)
        return context

我应该如何将参数c_slugproduct_slug传递给get_context_data定义,以使此CBV用作功能定义?

1 个答案:

答案 0 :(得分:1)

.as_view基本上将基于类的视图用作基于函数的视图。位置和命名参数分别存储在self.argsself.kwargs中,因此我们可以使用:

class ProdCatDetailView(FormView):

    # ...

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['product'] = Product.objects.get(
            category__slug=self.kwargs['c_slug'],
            slug =self.kwargs['product_slug']
        )
        return context