'Django: key error after setting the key with AJAX from JAVASCRIPT

I am using django to manage my site.

I have a JAVASCRIPT event that update's the server with this an AJAX call:

**script_x.js**

        $.ajax({
              type: "POST",
              url: "my_url_to_server",
              headers: {'X-CSRFToken': csrftoken},
              data: {},
              success:  function(response){alert(response);}
                 });

On the server in the views, I set the "SESSION variable" once the JQUERY function fires:

**views.py**

def set_session_now(request):
    if not request.is_ajax() or not request.method=='POST':
        return HttpResponseNotAllowed(['POST'])

    request.session['my_key'] = 0
    return HttpResponse('ok')

and in the urls.py:

path('set_session_now', views.set_session_now, name='set_session_now'),

But once the process finishes; I only get "ok" sent from the server; but the session is not set; the server returns "Key Error: 'my_key'".

Any help would be appreciated.

==================================== UPDATE:

The view raising the error:

@csrf_protect
def added_view(request):

    if request.is_ajax and request.session['my_key'] == 0:
    print("IN RESPONSE")
    #compose response
    .
    .(confidential task)
    .
   #my_key toggled
   request.session['my_key'] = -1 
   return response

The confidential task does not raise any errors and was tested.

The error arises from the if statement: the session doesn't get initialized from javascript or so I think.



Solution 1:[1]

Ah, the code actually worked, everything was working perfectly, but the requests I was making were all lacking www, conflicting with my own configuration -_-

Once I added www, everything worked like charm.

It's a server redirecting issue, not a code issue. Sorry for wasting your time,

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mohammed Baashar