Home > Enterprise >  Django i want create a function which can be run from any page from the website and do its process a
Django i want create a function which can be run from any page from the website and do its process a

Time:11-20

Django i want create a function which can be run from any page from the website and do its process and return on the same page

What i want to is to create a button to add to cart i have writted function but the time come from returning from the function i use redirect to cart page but i want that there are lots of types of product pages and i want they must redirect to the same page from where they come and use the same function to do that any idea

@login_required(login_url='login_signup')
def add_cart(request,id):
    prod = Product.objects.get(id = id)
    try:
        cart = Cart.objects.get(cart_id = _cart_id(request))

    except Cart.DoesNotExist:
        cart = Cart.objects.create(
            cart_id = _cart_id(request)

        )
       
    cart.save()

    try:
        cart_item = CartItem.objects.get(product = prod,cart = cart)
        cart_item.quantity = cart_item.quantity   1
        cart_item.save()
        # print("I was tries")
        customer = request.user
        cust = Customer.objects.get(user = customer)
        # print(f"The customer is {cust}")
    except CartItem.DoesNotExist:
        customer = request.user
        cust = Customer.objects.get(user = customer)
        # print("Cart except is also being hit")
        cart_item = CartItem.objects.create(
            product = prod,
            quantity = 1,
            cart = cart,
            user = cust, 
            
            
        )
        cart_item.save()

    return redirect('/cart/cart_page') 

Here is the function i use to add to cart i want it to redirect to the same page from where it comes not always to the cart page because i will trigger same function from many places

CodePudding user response:

Use request.META.get('HTTP_REFERER') to the previous url the user come from.

@login_required(login_url='login_signup')
def add_cart(request,id):
    # Lot of code
    #Redirect to previous url if exist else '/cart/cart_page'
    previous_url = request.META.get('HTTP_REFERER', '/cart/cart_page')
    return HttpResponseRedirect(previous_url)

Note : i strongly recommend you to use named ur like 'cart_page' defined in the urls.py file (path('cart/cart_page',views.cart_page,name='cart_page')) instead of hard coded url like '/cart/cart_page'

  • Related