简体   繁体   中英

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.

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?

A class based view is, by the .as_view basically used as a function-based view. The positional and named parameters, are stored in self.args , and self.kwargs respectively, so we can use:

class ProdCatDetailView(FormView):

    # ...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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