Django:修改基于 Class 的视图上下文(使用 **kwargs)

Django: Modify Class Based View Context (with **kwargs)

我有一个完美的函数定义,但我需要更新到基于 Class 的视图。

函数定义:

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})

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

所以,我这样做了:

Class 基于视图:

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 传递给此 CBV 的 get_context_data 定义以用作函数定义?

class 基于视图,.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=<b>self.kwargs['c_slug']</b>,
            slug =<b>self.kwargs['product_slug']</b>
        )
        return context