django how to use a variable globally

2020-07-16 02:46发布

I have a variable in one of my view

def ViewName(request):
      simple_variable = request.session['value']

in the same views.py file,i have another view

def AnotherViewName(request):
    --------------------
    --------------------

now i want to use the variable simple_variable in my AnotherViewName view ,i have tried

def AnotherViewName(request):
     global simple_variable

but,its not worked,now my question is,how can i use a variable from one view to another view in Django or how can i use a variable globally?

in mention the simple_variable is storing value from the session and initially i have to call it within my above given ViewName view.

i am using django 1.5

标签: python django
3条回答
做个烂人
2楼-- · 2020-07-16 03:11

Or you can use a session.

def ViewName(request):
      #retrieve your value
      if 'value' in request.session:
          simple_variable = request.session['value']

def AnotherViewName(request):
    #set your varaible
    request.session['value'] = simple_variable
查看更多
forever°为你锁心
3楼-- · 2020-07-16 03:21

I think you can do this way:

simple_variable = initial_value 

def ViewName(request):
    global simple_variable
    simple_variable = value
    ...

def AnotherViewName(request):
    global simple_variable
查看更多
仙女界的扛把子
4楼-- · 2020-07-16 03:30

There is no state shared between views as they probably runs in another thread. So if you want to share data between views you have to use a database, files, message-queues or sessions.

Here is another stackoverflow about this. How do you pass or share variables between django views?

Update after rego edited the question:

Can't you do it like this?

def ViewName(request):
     simple_variable = request.session['value']

def AnotherViewName(request):
     simple_variable = request.session['value']
查看更多
登录 后发表回答