In views.py
When I try this one to access a global variable from other def
:
def start(request):
global num
num=5
return HttpResponse("num= %d" %num) # returns 5 no problem....
def other(request):
num=num+1
return HttpResponse("num= %d" %num)
def other
does not return 6, but it should be 6 right ? How can I access a variable globally in my view ?
Django-globals is a very simple application, that allow you to define thread specific global variables. It includes a middleware Global, which can be used to access to the current request and user, which is useful outside of a view when the “request” variable is not defined.
Global variables, as the name implies, are variables that are accessible globally, or everywhere throughout the program. Once declared, they remain in memory throughout the runtime of the program. This means that they can be changed by any function at any point and may affect the program as a whole.
A global variable in Python is often declared as the top of the program. In other words, variables that are declared outside of a function are known as global variables. You can access global variables in Python both inside and outside the function.
Use sessions. This is exactly what they are designed for.
def foo(request):
num = request.session.get('num')
if num is None:
num = 1
request.session['num'] = num
return render(request,'foo.html')
def anotherfoo(request):
num = request.session.get('num')
# and so on, and so on
If the session has expired, or num
did not exist in the session (was not set) then request.session.get('num')
will return None
. If you want to give num
a default value, then you can do this request.session.get('num',5)
- now if num
wasn't set in the session, it will default to 5
. Of course when you do that, you don't need the if num is None
check.
You could declare num outside one of the functions.
num = 0
GLOBAL_Entry = None
def start(request):
global num, GLOBAL_Entry
num = 5
GLOBAL_Entry = Entry.objects.filter(id = 3)
return HttpResponse("num= %d" %num) # returns 5 no problem....
def other(request):
global num
num = num + 1
// do something with GLOBAL_Entry
return HttpResponse("num= %d" %num)
You only need to use the global keyword if you are assigning to a variable, which is why you don't need global GLOBAL_Entry
in the second function.
You can open settings.py and add your variable and value. In your source code, just add these line
from django.conf import settings
print settings.mysetting_here
Now you can access your variable globally for all project. Try this, it works for me.
You can also do this by using global keyword in other() method like this:
def other(request):
global num
num = num+1
return HttpResponse("num= %d" %num)
now It will return 6. It means wherever you want to use global variable, you should use global keyword to use that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With