0

I am following a tutorial where a Cart is made for Products handling. the is a function to add the items in the cart as

@require_POST
def cart_add(request, product_id):
    cart = Cart(request)
    product = get_object_or_404(Product, id=product_id)
    form = CartAddProductForm(request.POST)

    if form.is_valid():
        cd = form.cleaned_data
        cart.add(product=product, quantity=cd['quantity'], update_quantity=cd['update'])

    return redirect('cart:cart_detail')

and the second one is

def product_detail(request, id, slug):    
    product = get_object_or_404(Product, id=id, slug=slug, available=True)
    cart_product_form = CartAddProductForm()
    return render(request,'shop/product/detail.html' {'product':product,'cart_product_form': cart_product_form})

How can I change these two codes into ClassBasedViews? What will be better? using thesamefunction based views or the ClasBased?

from django import forms


PRODUCT_QUANTITY_CHOICES = [(i, str(i)) for i in range(1, 21)]


class CartAddProductForm(forms.Form):
    quantity = forms.TypedChoiceField(choices=PRODUCT_QUANTITY_CHOICES, coerce=int)
    update = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput)

this is forms.py in CartApp. The cart has a class called Cart which requires request,Product from the form. How can I pass that information to cart using CBV?

Higor Rossato
  • 1,996
  • 1
  • 10
  • 15
Deshwal
  • 3,436
  • 4
  • 35
  • 94

1 Answers1

0

It's a bit difficult to visualize all steps of the way but I think this gives you at least a starting point (if it doesn't solve your issue). Your 2 function based views can be replaced by a single class based view. The only thing you should be aware of is that on your template your form is now accessible by the name of form instead of cart_product_form.

class AddCartFormView(FormView):
    template_name = 'shop/product/detail.html'
    form_class = CartAddProductForm()

    def get_success_url(self):
        return reverse('cart:cart_detail')

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        # Your form is already inside context by the name of "form"
        context = ['product'] = get_object_or_404(Product, id=product_id, slug=slug, available=True)
        return context

    def post(self, request, *args, **kwargs):
        form = self.get_form()
        cart = Cart(request)
        product = get_object_or_404(Product, id=kwargs.get('product_id'))

        if form.is_valid():
            cd = form.cleaned_data
            cart.add(product=product, quantity=cd['quantity'], update_quantity=cd['update'])
            return self.form_valid(form)
        else:
            return self.form_invalid(form)
Higor Rossato
  • 1,996
  • 1
  • 10
  • 15