Reputation: 475
I am using database-backed sessions for my project. I am trying to update the value of a session variable via an AJAX post request using AngularJS:
app.factory('SomeFactory', ['$http', 'djangoUrl',
function ($http, djangoUrl) {
return {
getSomeDataAndUpdateSessionVar: function () {
return $http({
method: 'POST',
url: djangoUrl.reverse('some_app:list'),
data: {
param1: "param1"
}
})
},
}
}
]);
Here is the simplified post method of my View:
class DocumentListView(JsonRequestResponseMixin, View):
def post(self, request, *args, **kwargs):
request_data = json.loads(request.body)
data_to_be_fetched = request.session.get("data_to_be_fetched", None)
if not data_to_be_fetched:
data_to_be_fetched = fetch_data(request_data)
request.session["data_to_be_fetched"] = data_to_be_fetched
print request.session.get("data_to_be_fetched") # This will return the updated value
return HttpResponse(json.dumps(data_to_be_fetched), content_type="application/json")
It seems like the session variable is not being saved because if I call the above method again, the value of data_to_be_fetched
will still be None
. The weird thing is that after calling the method for the second time, the new value of session variable will finally be saved (data_to_be_fetched
will not be None
anymore when fetched after saving it for the second time). Why is it behaving like that? It only happens when setting the session variable during AJAX requests.
I tried adding the following after updating the session variable, but the behavior is still the same:
request.session.modified = True
I also tried adding the following to the settings, but it is not helping either:
SESSION_SAVE_EVERY_REQUEST = True
Upvotes: 4
Views: 630
Reputation: 193
The problem is use localhost:8000 rather than 127.0.0.1:8000. Thefore always use 127.0.0.1:8000. This fix to me.
Upvotes: 1