Home > Software engineering >  how do I turn a function into a class and pass the form to a Django?
how do I turn a function into a class and pass the form to a Django?

Time:11-04

in my Django project i have a function:


def retail_product_detail(request, slug):
    context = {
        'product_retail': get_object_or_404(Product, slug=slug),
        'cart_product_form': CartAddProductRetailForm(),
        'related_products': Product.objects.filter(category__slug=self.kwargs['slug'])
        }
    return render(request, 'retail/single_product_retail.html', context)

how can i turn it into class RetailProductDetail and pass the form to be displayed?

i tried:


class RetailProductDetail(FormView):

    template_name = 'retail/single_product_retail.html'
    context_object_name = 'product_retail'
    form_class = CartAddProductRetailForm

    def get_queryset(self):
        return Product.objects.filter(category__slug=self.kwargs['slug'])

    def get_context_data(self, *, object_list=None, **kwargs):
        context = super().get_context_data(**kwargs)
        context['product_retail'] = Product.objects.get(slug=self.kwargs['slug'])
        context['related_products_1'] = Product.objects.select_related('tag').all()
        return context

But form doesn't works.

In template:

<form action="{% url 'cart_add_retail' slug=product_retail.slug %}" method="post">
    {{ cart_product_form }}
    {% csrf_token %}
    <br>
    <input class="btn btn-outline-dark flex-shrink-0" type="submit" value="Add to cart>
</form>

How can I fix it?

CodePudding user response:

I was able to solve the problem in the following way:

Instead of:

form_class = CartAddProductRetailForm

I used:

    def get_context_data(self, *, object_list=None, **kwargs):
        context['cart_product_form'] = CartAddProductRetailForm

CodePudding user response:

its because default context name for form is form in FormView CBV try in template {{ form }}

  • Related