Django cookies没有得到s

2024-06-25 07:08:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着在主页上设置django测试cookies,但是没有设置好,我尝试了从改变中间件类到sessionengines的所有方法 我的索引函数

定义索引(请求):

request.session.set_test_cookie()
if request.method == 'POST':
    # create a form instance and populate it with data from the request:
    form = NameForm(request.POST)
    # check whether it's valid:
    if form.is_valid():
        # process the data in form.cleaned_data as required
        # ...
        # redirect to a new URL:
        return HttpResponseRedirect('/thanks/')

# if a GET (or any other method) we'll create a blank form
else:
    form = NameForm()

return render(request, 'name.html', {'form': form})

这是我测试cookie的另一个函数

def寄存器(请求):

^{pr2}$

Tags: the函数formdatareturnifcookierequest
1条回答
网友
1楼 · 发布于 2024-06-25 07:08:50

您不需要对设置文件进行所有这些中间件更改。我刚试着设置一个简单的代码演示,它工作得很好。在

首先,试着把你的代码最小化到只有cookie设置“实验”。你可以试试这个演示。在

一个视图或者一个主视图的索引设置cookie。 在另一个视图中,可能是另一个应用程序的索引视图来测试cookie。在

  From the docs you can only test using another page request I quote
  *test_cookie_worked()* "Returns either True or False, depending on whether the user’s    
   browser accepted the test cookie. Due to the way cookies work, 
   you’ll have to call set_test_cookie() on a previous, 
   separate page request. See Setting test cookies below for more information."

    project/appxx/views ... request.session.set_test_cookie() #inside a view
    project/appyy/views ...  if request.session.test_cookie_worked():
                               request.session.delete_test_cookie()
                               return HttpResponse(">>>> TEST COOKIE WORKED!")

然后你可以在后面添加逻辑。我使用的是httreresponse方法,而不是您使用的print statement。在

相关问题 更多 >