I have a template cat1.html with a listing of products . When a customer selects an item, it builds an object with properties of the selected product. If the customer clicks 'add to cart' button, axios sends a request params stringified product object to /cart
ulElement.addEventListener('click', function(event) {
let targetClasses = Array.from(event.target.classList);
if(targetClasses.includes('dropdown-item')) {
/* code to build the item */
}
if(targetClasses.includes('btn-cart')) {
axios.get('/cart', { params: { item: JSON.stringify(item) } } );
}
});
so far this is working fine, I can print the object/json from the server so I know it makes it through.
def cart(request):
item_dict = json.loads(request.GET.get('item'))
user_cart.append(item_dict)
print(user_cart); # this seems to work fine
/* return redirect('cart') this results in error TypeError(f'the JSON object must be str, bytes or bytearray, ' */
The problem happens when I try to add a redirect to the /cart view. I get the error
the JSON object must be str, bytes or bytearray, not NoneType
I've tried to get around this using window.location.href and also wrapping the button in an but I get the same error, so I get the sense I'm using the wrong approach.
CodePudding user response:
you can not send redirect as ajax response. You can send back message or status, and you should work with that on front in success callback function.
CodePudding user response:
This is because you are redirecting to the 'cart' view without JSON in the parameters. So what happens is redirect is successful but then in the redirected instance, the 'item' parameter is None hence json.loads() throws the error.