简体   繁体   English

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

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

I've a Function definition that works perfect, but I need to update to a Class Based View.我有一个完美的函数定义,但我需要更新到基于类的视图。

function def:功能定义:

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

So far, I've read that to modify the context of a Class Based View (CBV) I need to overwrite the def get_context_data(self, **kwargs) in the CBV.到目前为止,我已经阅读了修改基于类的视图 (CBV) 的上下文,我需要覆盖 CBV 中的def get_context_data(self, **kwargs)

So, I've done this:所以,我已经这样做了:

Class Based View:基于类的视图:

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

How should I pass the arguments c_slug , product_slug to the get_context_data definition for this CBV to work as the Function definition?我应该如何将参数c_slugproduct_slug传递给这个 CBV 的 get_context_data 定义以用作函数定义?

A class based view is, by the .as_view basically used as a function-based view.基于类的视图,由.as_view基本上用作基于函数的视图。 The positional and named parameters, are stored in self.args , and self.kwargs respectively, so we can use:位置和命名参数分别存储在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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM