Omar Gonzales
Omar Gonzales

Reputation: 4008

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?

Upvotes: 2

Views: 1191

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476594

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=self.kwargs['c_slug'],
            slug =self.kwargs['product_slug']
        )
        return context

Upvotes: 2

Related Questions