Heroku Django request.POST giving wrong values

Advertisements

I have deployed an app in heroku build using django.In my django views.py iam getting some value using request.POST and storing in a global variable so that i can access that value in another function which is then rendered into the template.
Eveything worked fine on devolopment server but when i deployed it on heruko,request.POST is not retriving the correct value.

views.py:

serv='--'
def home(request):
global serv
if request.method=='POST':
    dayCheck.clear()
    serv=request.POST['service']
    return HttpResponseRedirect('func')

def func(request):
    global serv
    #Doing something,does not involve serv
    return render(request,'index.html',{'service':serv})

When i try to log serv in home() it gives correct value but different value in func
and the same is rendered,mostly it will be value which i previously clicked or sometimes it would be just -- as declared.
Please help me!
Thanks in Advance

>Solution :

Please don’t. Using global state in a webserver is a very very severe antipattern. Often later several Django processes will run to handle the requests concurrently: this means that the next request can be processed by a different Django process. Furthermore it is also possible that in between the request of a different user is processed.

Usually you pass data through the URL parameter, the querystring, the database, POST parameters, session variables and cookies (where session variables and cookies are usually not a good idea either, since these can easily collide with other views that store some state into the sessions or cookies).

You thus can thus for example make use of a URL parameter, where you map func to:

urlpatterns = [
    # …,
    path('func/<path:param>/', views.func, name='func')
]

then you thus make a request with:

from django.shortcuts import redirect

def home(request):
    if request.method == 'POST':
        dayCheck.clear()
        serv = request.POST['service']
        return redirect('func', param=serv)

def func(request, param):
    # here param has the value for serv in the previous request
    return render(request,'index.html',{'service':serv})

since it will make a GET request to func, func is furthermore not allowed to make any changes to the entities either, since this is specified by the HTTP specifications on safe methods [w3.org]:

In particular, the convention has been established that the GET and HEAD methods SHOULD NOT have the significance of taking an action other than retrieval. These methods ought to be considered "safe".

Leave a ReplyCancel reply