Reputation: 211
How to pass a variable between web pages/functions?
For example, let's say when I visit webpage "test3.html", I'd like to get the sum of variables a_test1 and a_test2, which are "global" variables which increased as visiting test1.html and test2.html. test1.html, test2.html and test3.html could be visited multiple times and independently. The following code doesn't work as it is, but it would if I can somehow make a_test1 and a_test2 global variables? Can that be done?
Another option maybe passing these variables by the "request" parameter? Can it be done that way?
urlpatterns = [
url(r'^test1/$', views.test1),
url(r'^test2/$', views.test2),
url(r'^test3/$', views.test3),
]
in views.py:
def test1(request):
a_test1=1+a_test1
return render(request,'test1.html',{'a_test1': a_test1})
#other stuffs
def test2(request):
a_test2=1+a_test2
return render(request,'test2.html',{'a_test2': a_test2})
#other stuffs
def test3(request):
a_test3=a_test1+a_test2
return render(request,'test3.html',{'a_test3': a_test3})
#other stuffs
Upvotes: 1
Views: 3988
Reputation: 571
You could use session variables in order to share variables across multiple templates and views! for example:
def test1(request):
a_test1=1+a_test1
request.session['my_variable'] = a_test1
return render(request,'test1.html',{'a_test1': a_test1})
With that you can access request.session['my_variable'] everywhere on your site!
https://docs.djangoproject.com/en/1.11/topics/http/sessions/
Upvotes: 4