[Fixed]-Django global variable

31👍

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.

9👍

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.

3👍

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.

1👍

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.

Leave a comment