[英]how to use one function variable into another function?
I have two function in Django Templates. 我在Django模板中有两个功能。
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. 如何在checkout_steps函数中使用cart_formset变量。 .
。
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. 这就是局部变量是:他们是本地的他们所在的函数的变量。
cart_formset
并不时除外存在cart
正在执行。
You could return cart_formset
from the function and then call cart
from checkout_steps
to get the value. 您可以从函数返回
cart_formset
,然后从checkout_steps
调用cart
以获取值。 Or you could store that variable somewhere else. 或者,您可以将该变量存储在其他位置。 I don't know enough about Django to know where the best place is.
我对Django的了解不足,无法知道最好的地方在哪里。 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.
鉴于您正在做的事情看起来像是购物车的设置,我想您想在会话中存储该信息,因此可以查看Django的会话处理。
How I use the cart_formset variable in my checkout_steps function..
我如何在checkout_steps函数中使用cart_formset变量。
If the two functions are related, use a Class (like Shopping) and add cart and checkout_steps as member functions. 如果这两个功能相关联,请使用Class(例如Shopping),然后将cart和checkout_steps添加为成员功能。
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
You can also put the variable cart_formset, as global to make it available globally across the module 您还可以将变量cart_formset设置为全局变量,以使其在整个模块中全局可用
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
If the order of function evaluation is deterministic then you can use a decorator 如果功能评估的顺序是确定的,则可以使用装饰器
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.