-1

I have two function in Django Templates.

def cart(request, template="shop/cart.html"):
 cart_formset = CartItemFormSet(instance=request.cart)

def checkout_steps(request):

How I use the cart_formset variable in my checkout_steps function..

2 Answers2

1

You can't. That's what local variables are: they're local to the function they're in. The variable cart_formset does not exist except when cart is executing.

You could return cart_formset from the function and then call cart from checkout_steps to get the value. Or you could store that variable somewhere else. I don't know enough about Django to know where the best place is. Given that what you're doing looks like a shopping cart setup, I would guess that you want to store that info with the session, so you could look at Django's session handling.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
1

How I use the cart_formset variable in my checkout_steps function..

  1. If the two functions are related, use a Class (like Shopping) and add cart and checkout_steps as member functions.

    class Shopping(object):
        def __init__(self):
            self.cart_formset = None
        def cart(self, request, template="shop/cart.html"):
            self.cart_formset = CartItemFormSet(instance=request.cart)
        def checkout_steps(self, request):
            #Use self.cart_formset
    
  2. You can also put the variable cart_formset, as global to make it available globally across the module

    def cart(request, template="shop/cart.html"):
         global cart_formset
         cart_formset = CartItemFormSet(instance=request.cart)
    def checkout_steps(self, request):
         #Use self.cart_formset
    
  3. If the order of function evaluation is deterministic then you can use a decorator

Abhijit
  • 62,056
  • 18
  • 131
  • 204
  • When I use this as a globally or in class.It shows error. class Shopping(object): def __init__(self): self.cart_formset = None def cart(self,request, template="shop/cart.html"): cart_formset = CartItemFormSet(instance=request.cart) - def checkout_steps(self,request): - qwert = self.cart_formset context = {"form": form, "CHECKOUT_STEP_FIRST": CHECKOUT_STEP_FIRST, "qwert":qwert} return render(request, template, context) ERROR IS: TypeError at /shop/cart/ cart() takes at least 2 arguments (1 given) – Rahul ghrix Dec 26 '12 at 09:46