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

Advertisements

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

>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

Leave a ReplyCancel reply