Reputation: 93
i am creating a web app and i'm using ajax to send the data from frontend to backend so i can process the forms and save them to the database. I send the data from ajax to a get-data method and from there i save it to the session, and when i access the /success page and try to get the same data from session, it tells me that the key doesn't exist. How is that possible? Here is the code down below.
$.ajax({
type: "POST",
url: "/get-data/",
data: JSON.stringify(obj),
dataType: "text",
headers: { "X-CSRFToken": getCookie("csrftoken") },
success: function (response) {
console.log("success"); // i get this, so i it means that the ajax works properly.
},
error: function (response, err, err2) {
console.log(err2);
},
});
def get_data(request):
if request.method == "POST":
if is_ajax(request):
rec_data = json.loads(request.body)
print("the request came")
request.session["data_check_form"] = rec_data
print("everything set")
print(request.session["data_check_form"]) # i print this and i get the json file properly
return JsonResponse({"success": "200"})
def success_view(request):
print("test")
data = request.session.get("data_check_form", False)
print(data) # i get false
...
Upvotes: 1
Views: 2367
Reputation: 2425
Use request.session.modified = True
after any changes in session
as
def get_data(request):
if request.method == "POST":
if is_ajax(request):
rec_data = json.loads(request.body)
print("the request came")
request.session["data_check_form"] = rec_data
request.session.modified = True
print("everything set")
print(request.session["data_check_form"]) # i print this and i get the json file properly
return JsonResponse({"success": "200"})
Or you can set SESSION_SAVE_EVERY_REQUEST
to True
in settings.py
which will save session to database on every single request as stated
To change this default behavior, set the SESSION_SAVE_EVERY_REQUEST setting to True. When set to True, Django will save the session to the database on every single request.
Upvotes: 3