Skip to main content
 首页 » 编程设计

python之html中的csrf token ,但无法设置cookie

2025年05月04日10飞鱼

首先,我转到 localhost:8000 查看以下页面:

</div>         
 
< form id="SignUpForm"  name="form_signupform"  method="post" action="hello/" >  
 
{% csrf_token %}   
< fieldset class="roundedCorners"  style = "display: table;"  > 
< legend align="center"><em>Sign Up</em></legend> 
< p></p> 
< p style="display: block;"> 
 
etc. 

在 localhost:8000 上面的页面 View 是使用 views.py 中的函数提供的:

def login(request):   
    c = {}   
    c = {'query': 'abcd.com'}   
    response = render_to_response('index.html', c,context_instance=RequestContext(request))   
    return response    

在这里,在提供的页面源代码中,我可以看到如下所示的 csrf 值:

< form  id="SignUpForm"  name="form_signupform"  method="post" action="hello/" > 
< input type='hidden' name='csrfmiddlewaretoken'       
value='rjbU4k8DY3EEBWVhlsgIYU3gEu4x3ctM' / >    
< fieldset class="roundedCorners"  style = "display: table;" > 
< legend align="center"><em>Sign Up</em></legend> 
< p >< /p > 
< p style="display: block;">  
 
etc. 

在按下提交按钮时调用另一个 View 。在 views.py 中:

def hello(request):   
    if request.method == "POST":   
        return HttpResponseRedirect("genResp1.html")   
    else:   
        return HttpResponseRedirect("genResp2.html")   

但是,在按下提交按钮时,出现以下错误:

Forbidden (403) 
    CSRF verification failed. Request aborted. 
... 
... 
Help 
Reason given for failure: 
    CSRF cookie not set. 

::我已经咨询了 a) django 文档,b) stackoverflow.com,c) google 等。我已经尝试了所有可能的代码排列组合......但错误从未改变......(我可以设置cookie 调用 set_cookie 函数...工作正常...但无法设置 csrf cookie...为什么?)请不要搜索网络并编写解决方案。我已经搜索了过去 6 天。我已经尝试了所有形式的 View 功能。其中之一已在上面给出。如果你自己完成了那个 CSRF 工作并且让它运行那么请写下你是如何做到的......(我使用 python 3.4 和 django 1.7)

请您参考如下方法:

通过将 CSRF_COOKIE_SECURE 设置为 False 解决了这个问题,因为我没有在我的开发机器上使用 HTTPS:

  1. 修改了包含以下行的文件 settings.py:

    CSRF_COOKIE_SECURE = True 
    SESSION_COOKIE_SECURE = True 
    
  2. 修改为:

    CSRF_COOKIE_SECURE = False 
    SESSION_COOKIE_SECURE = False