-1

I am sure this may have been addressed. I am having this issue for the past week and cannot get past it. I have tried all possible solutions in every site I could find.

Here is my error:

ValueError: The view cart.views.cart_add didn't return an HttpResponse object. It returned None instead. 

This is my code:

from django.shortcuts import render, get_object_or_404 from .cart import Cart from store.models import Product from django.http import HttpResponse, JsonResponse from django import template from django.http import HttpResponse, HttpResponseRedirect from django.urls import reverse def cart_summary(request): cart = Cart(request) return render(request, 'summary.html', {'cart': cart}) def cart_add(request): # Get the Cart cart = Cart(request) # test to POST if request.POST.get('action') == 'post': # get Stuff product_id = int(request.POST.get('product_id')) # lookup product in DB product = get_object_or_404(Product, id=product_id) # save to Session cart.add(product=product) # Return a reponse cart_quantity = cart.__len__() # Return Repesponse # response = JsonResponse({'Product Name ': product.name}) response = HttpResponse({'qty ': cart_quantity}) return response def cart_delete(request): return def cart_update(request): pass 

I have tried everything under the sun

1
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. Commented Jun 25, 2024 at 6:55

1 Answer 1

0

This can happen if the condition if request.POST.get('action') == 'post': is not met, causing the function to reach the end without returning a response.

The way you're creating the HttpResponse with a dictionary is incorrect. You should use JsonResponse if you want to return JSON data, or HttpResponse for plain text or HTML.

Make Sure your cart_quantity contain integer or string otherwise it will Show None.

 # Check if the request is POST and contains 'action' == 'post' if request.method == 'POST' and request.POST.get('action') == 'post': # remaining code here 1. return JsonResponse({'qty': cart_quantity}) 2. return Response(data={'qty': cart_quantity}) 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Tanveer. It worked. Much appreciated.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.