Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In Django I use request.POST and return JSONResponse but the url shows HttpResponse object error. I don't want to use render()

I’m using Ajax to submit a POST. In views.py I have the following:

def color(request):
    if(request.POST.get('mydata',False)):
        mylist= request.POST['mydata']
        mylist= mylist.split(",")
        request.session['var1'] = mylist[0]
        request.session['var2'] = mylist[1]
        return JsonResponse({'success':True})

In urls.py I defined color, so when I go to localhost:8000/color it shows error: "didn't return an HttpResponse object". I should use instead return render(request,'app/color.html',{}) but I do not have a color.html file. I actually don’t want to have one. All I want is to post a variable and use it as a session, so how can I avoid using render() and creating the html file? Thanks

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Is that all the code of your view? If so then the error is because you aren’t returning anything if your request.POST.get('mydata',False) if-statement returns False. You need a final return, like this:

def color(request):
    if(request.POST.get('mydata',False)):
        mylist= request.POST['mydata']
        mylist= mylist.split(",")
        request.session['var1'] = mylist[0]
        request.session['var2'] = mylist[1]
        return JsonResponse({'success':True})
    return JsonResponse({'success':False}) # a response is now always returned
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading