Django request.session无法正常工作



我正在创建一个web应用程序,并使用ajax将数据从前端发送到后端,这样我就可以处理表单并将其保存到数据库中。我将数据从ajax发送到get-data方法,然后从那里将其保存到会话,当我访问/success页面并尝试从会话中获取相同的数据时,它会告诉我密钥不存在。这怎么可能?下面是代码。

$.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
...

session发生任何更改后使用request.session.modified = True作为

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"})

或者您可以在settings.py中将SESSION_SAVE_EVERY_REQUEST设置为True,这将在每个请求中将会话保存到数据库中,如所述

若要更改此默认行为,请将SESSION_SAVE_EVERY_REQUEST设置设置为True。当设置为True时,Django将在每个请求中将会话保存到数据库中。

最新更新