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.
- Proper declaration of an empty Django PostgreSQL JSONField default value in migration file
- How can I test if my redis cache is working?
- In django, is there a way to directly annotate a query with a related object in single query?
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.
- Could not import 'oauth2_provider.ext.rest_framework.OAuth2Authentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'
- What is query.clone(), queryset.clone() for in django?
- How to create custom groups in django from group