Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django how to use a variable globally

Tags:

python

django

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

like image 929
Md. Tanvir Raihan Avatar asked Mar 01 '15 09:03

Md. Tanvir Raihan


2 Answers

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
like image 147
MarshalSHI Avatar answered Sep 20 '22 17:09

MarshalSHI


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']
like image 28
Mikael Svensson Avatar answered Sep 19 '22 17:09

Mikael Svensson