amit238
amit238

Reputation: 21

keys must be str, int, float, bool or None, not builtin_function_or_method

This is my cart views, im trying link my products/plans page to this view. Im trying to create an add to cart view so when i click add to cart it will go onto the cart page

from django.shortcuts import render, redirect, reverse

# Create your views here.

def view_cart(request):
    """ A view that renders the cart page """

    return render(request, 'cart/cart.html')

def add_to_cart(request, item_id):
    """ Add plan to shopping cart """
    
    cart = request.session.get('cart', {})
    cart[id] = cart.get(id, 1)

    request.session['cart'] = cart
    return redirect(reverse('plans'))
    

    

Upvotes: 2

Views: 973

Answers (3)

Michael Hawkins
Michael Hawkins

Reputation: 2873

The issue appears to be in this line of code:

cart[id] = cart.get(id, 1)

Where is the "id" variable coming from? Did you mean item_id?

You are using the builtin id instead of item_id, so change it to:

cart[item_id] = cart.get(item_id, 1)

Upvotes: 1

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477180

The key of the add_to_cart is a item_id, not id. This means that id is the builtin id(…) function [Django-doc]. You thus should use item_id instead:

def add_to_cart(request, item_id):
    """ Add plan to shopping cart """
    
    cart = request.session.get('cart', {})
    cart[item_id] = cart.get(item_id, 1)

    request.session['cart'] = cart
    return redirect('plans')

That being said, normally requests that have side effects should be POST/PUT/PATCH/DELETE/… requests, not GET requests. Furthermore here you can only add the item once to the cart. If you want to add the item multiple times, you should alter the logic to:

def add_to_cart(request, item_id):
    """ Add plan to shopping cart """
    
    cart = request.session.get('cart', {})
    cart[item_id] = cart.get(item_id, 0) + 1

    request.session['cart'] = cart
    return redirect('plans')

Upvotes: 1

AKX
AKX

Reputation: 169269

Your argument is item_id, but you're accidentally using the builtin id:

def add_to_cart(request, item_id):
    # ...
    cart[id] = cart.get(id, 1)
    # ...

should be

def add_to_cart(request, item_id):
    # ...
    cart[item_id] = cart.get(item_id, 1)
    # ...

or

def add_to_cart(request, id):
    # ...
    cart[id] = cart.get(id, 1)
    # ...

Upvotes: 2

Related Questions