我有一个完美的功能定义,但是我需要更新为基于类的视图。
功能定义:
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_slug
,product_slug
传递给get_context_data定义,以使此CBV用作功能定义?
答案 0 :(得分:1)
.as_view
基本上将基于类的视图用作基于函数的视图。位置和命名参数分别存储在self.args
和self.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