[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.

๐Ÿ‘คBurhan Khalid

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.

๐Ÿ‘คVinh Trieu

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.

๐Ÿ‘คAshok Joshi

Leave a comment