Search code examples
pythondjangogenericsdetailview

Pass context data from generic.DetailView


How can i pass the context data which is coming from a forms.py to my views class which is using generic detailView, i need to pass forms.py to my product detail page.

Here is the code for my view class

class ProductView(generic.DetailView):
model = Product
cart_product_form = CartAddProductForm()
context = {'cart_product_form': cart_product_form}
template_name = 'shopping/product.html'
query_pk_and_slug = True

Please let me know if this is incorrect


Solution

  • Override get_context_data, and add the form to the context before returning it.

    class ProductView(generic.DetailView):
        model = Product
        template_name = 'shopping/product.html'
        query_pk_and_slug = True
    
        def get_context_data(self, **kwargs):
            context = super(ProductView, self).get_context_data(**kwargs)
            cart_product_form = CartAddProductForm()
            context['cart_product_form'] = cart_product_form
            return context