I would like to ask for a little help regarding a code since when I start it tells me this following error:
Here are the views and code
def add(request):
cart = get_or_create_cart(request)
producto = Producto.objects.get(pk=request.POST.get('product_id'))
cart.productos.add(producto)
return render(request, 'carts/add.html', {
'producto': producto
})
CodePudding user response:
Add primary_key=True
to cart_id
column.
Since you have not added it django added a pk field id
which is what it's expecting when you query.
After the change make the template code to use cart_id
instead of id
CodePudding user response:
You are supplying product_id in the add views as post data but by default django views handles GET request. So, either change views to include product_id as argument and this function will works or change function to handle post request.
Using GET method
def add(request, product_id):
cart = get_or_create_cart(request)
producto = Producto.objects.get(pk=product_id)
cart.productos.add(producto)
return render(request, 'carts/add.html', {
'producto': producto
})
and your url patterns look like following
path('<int:product_id>/', add, name='add')
Using POST request
def add(request):
if request.method == "POST":
cart = get_or_create_cart(request)
producto = Producto.objects.get(pk=request.POST.get('product_id'))
cart.productos.add(producto)
return render(request, 'carts/add.html', {
'producto': producto
})
else:
# something you would like (GET method)