Home > Mobile >  Django Redirect does not work at all within view
Django Redirect does not work at all within view

Time:05-06

I am trying to get my view to redirect to another page after clicking a button that triggers the POST request. I cannot seem to figure out why the redirect doesn't work or why it doesn't even seem to try to redirect.

Here is my view:

def cart1(request):
if request.user.is_authenticated:
    #POST
    if request.method == "POST":
        #JSON Data
        data = request.body
        new_data = ast.literal_eval(data.decode('utf-8'))

        customer = request.user
        user_order = Order(user=customer)
        user_order.save()

        x = 0
        while x < len(new_data.keys()):
            obj_title = new_data[x]["title"]
            obj_price = new_data[x]["price"]
            obj_quantity = new_data[x]["quantity"]
            obj_extra = new_data[x]["extra"]
            total = round(float(obj_price.replace("$", "")))
            m = OrderItem(order=user_order, title=obj_title, price=total, quantity=obj_quantity, extra=obj_extra)
            m.save()
            x  = 1 
        return redirect('checkout-page')

return render(request, 'cart.html')

Any help would be appreciated, thank you

CodePudding user response:

redirect(…) [Django-doc] produces a HttpRedirectResponse, you need to return it, so:

return redirect('checkout-page')

redirect(…) itself thus does not stop the code flow to redirect return a HTTP redirect response, it constructs such response, and your view should then return that response.

CodePudding user response:

you need to be sure the URL name =checkout-page is in the current app otherwise you need to make it redirect('app:checkout-page')

However,I suggest to use from django.http import HttpResponseRedirect

  • Related