'WSGIRequest' object has no attribute 'get' django 5.1.4

hey guys im new to django and in my first project i trying to save the cart of a visitor in session when i try to add some product in cart of session i have this error says < WSGIRequest object has no attribute 'get'

i use a class for cart in my project and in init i check if 'cart' exists in session or no then create a key for 'cart' like this :

in class Cart:

class Cart:
    def __init__(self, request):
        """
        Initialize The Cart
        """
        self.request = request
        self.session = request.session
        cart = self.session.get('cart')
        if not cart:
            cart = self.session['cart'] = {}
        self.cart = cart
        
    # add a product to session cart:
    def add(self, product, quantity=1):
        """
        Add The Specified Product To The Cart If Exists
        """
        product_id = str(product.id)
        if product_id not in self.cart:
            self.cart[product_id] = {'quantity': quantity}
        else:
            self.cart[product_id]['quantity'] += quantity
            self.save()

i also use another way for check if 'cart' exists in session:

        if 'cart' not in request.session:
            self.cart = self.session['cart'] = {}

and still have the same issue...

form for using the cart:

class AddToCartProductForm(forms.Form):
    QUANTITY_CHOICES = [(i, str(i)) for i in range(1, 30)]
    quantity = forms.TypedChoiceField(choices=QUANTITY_CHOICES, coerce=int, label=_('Quantity'))

view:

def add_to_cart_view(request, product_id):
    cart = Cart(request)
    product = get_object_or_404(Product, id=product_id)
    form = AddToCartProductForm(request)

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

    return redirect('cart:cart-detail')

urls file:

urlpatterns = [
    path('', views.cart_detail_view, name='cart-detail'),
    path('add/<int:product_id>', views.add_to_cart_view, name='add-to-cart')
]

in html file:

 <form action="{% url 'cart:add-to-cart' product.id %}" method="post">
         {% csrf_token %}
         {{ add_to_cart_form|crispy }}
         <button type="submit" class="btn btn-small btn-bg-red btn-color-white btn-hover-2">
                                        {% trans 'Add To Card' %}
                                    </button>
 </form>

and when i click on the add to cart button this error shows up: 'WSGIRequest' object has no attribute 'get' i think the error is because of the init method in Cart where i check the existing of 'cart' in the session how can i fix this?

The problem was because of this line:form = AddToCartProductForm(request) I should have written this instead : form = AddToCartProductForm(request.**POST**)

I had to take the POST from the request and give it to the AddToCartProductForm class.

Anyway, thank you.

Вернуться на верх