Python Django CSRF Coo​​kie 未设置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17716624/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:59:44  来源:igfitidea点击:

Django CSRF Cookie Not Set

pythondjango

提问by

I have some problem for a while now, I'm experiencing CSRF Cookie not set. Please look at the codes below

我现在遇到了一些问题,我遇到了 CSRF Coo​​kie not set。请看下面的代码

Python

Python

def deposit(request,account_num):
if request.method == 'POST':
    account = get_object_or_404(account_info,acct_number=account_num)
    form_=AccountForm(request.POST or None, instance=account)
    form = BalanceForm(request.POST)
    info = str(account_info.objects.filter(acct_number=account_num))
    inf=info.split()
    if form.is_valid():
    #cd=form.cleaned_data
        now = datetime.datetime.now()
        cmodel = form.save()
        cmodel.acct_number=account_num
        #RepresentsInt(cmodel.acct_number)
        cmodel.bal_change="%0.2f" % float(cmodel.bal_change)
        cmodel.total_balance="%0.2f" %(float(inf[1]) + float(cmodel.bal_change))
        account.balance="%0.2f" % float(cmodel.total_balance)
        cmodel.total_balance="%0.2f" % float(cmodel.total_balance)
        #cmodel.bal_change=cmodel.bal_change
        cmodel.issued=now.strftime("%m/%d/%y %I:%M:%S %p")
        account.recent_change=cmodel.issued
        cmodel.save()
        account.save()
        return HttpResponseRedirect("/history/" + account_num + "/")
    else:
        return render_to_response('history.html',
                          {'account_form': form},
                          context_instance=RequestContext(request))

In the HTML here is the code

在 HTML 中,这里是代码

HTML

HTML

<form action="/deposit/{{ account_num }}/" method="post">

<table>
<tr>
{{ account_form.bal_change }}
&nbsp;
<input type="submit" value="Deposit" />
</tr>
{% csrf_token %}
</table>
</form>

Im stuck, I already cleared the cookie, used other browser but still csrf cookie not set.

我卡住了,我已经清除了 cookie,使用了其他浏览器但仍然没有设置 csrf cookie。

采纳答案by Druska

This can also occur if CSRF_COOKIE_SECURE = Trueis set and you are accessing the site non-securely or if CSRF_COOKIE_HTTPONLY = Trueis set as stated hereand here

如果CSRF_COOKIE_SECURE = True已设置并且您以非安全方式访问该站点,或者如果CSRF_COOKIE_HTTPONLY = True按照此处此处所述进行设置,也会发生这种情况

回答by drabo2005

try to check if your have installed in the settings.py

尝试检查您是否已安装在 settings.py 中

 MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',)

In the template the data are formatted with the csrf_token:

在模板中,数据使用 csrf_token 进行格式化:

<form>{% csrf_token %}
</form>

回答by abhishekgarg

In your view are you using the csrf decorator??

在您看来,您使用的是 csrf 装饰器吗?

from django.views.decorators.csrf import csrf_protect

from django.views.decorators.csrf import csrf_protect

@csrf_protect def view(request, params): ....

@csrf_protect def view(request, params): ....

回答by Rohan

Problem seems that you are not handling GETrequests appropriately or directly posting the data without first getting the form.

问题似乎是您没有正确处理GET请求或没有先获取表单就直接发布数据。

When you first access the page, client will send GETrequest, in that case you should send html with appropriate form.

当您第一次访问该页面时,客户端将发送GET请求,在这种情况下,您应该以适当的形式发送 html。

Later, user fills up the form and sends POSTrequest with form data.

稍后,用户填写表单并发送POST带有表单数据的请求。

Your view should be:

你的观点应该是:

def deposit(request,account_num):
   if request.method == 'POST':
      form_=AccountForm(request.POST or None, instance=account)
      if form.is_valid(): 
          #handle form data
          return HttpResponseRedirect("/history/" + account_num + "/")
      else:
         #handle when form not valid
    else:
       #handle when request is GET (or not POST)
       form_=AccountForm(instance=account)

    return render_to_response('history.html',
                          {'account_form': form},
                          context_instance=RequestContext(request))

回答by IWS

Check that chrome's cookies are set with default option for websites. Allow local data to be set (recommended).

检查 chrome 的 cookie 是否设置为网站的默认选项。允许设置本地数据(推荐)。

回答by shenqi0920

Method 1:

方法一:

from django.shortcuts import render_to_response
return render_to_response(
    'history.html',
    RequestContext(request, {
        'account_form': form,
    })

Method 2 :

方法二:

from django.shortcuts import render
return render(request, 'history.html', {
    'account_form': form,
})

Because render_to_response method may case some problem of response cookies.

因为 render_to_response 方法可能会导致响应 cookie 的一些问题。

回答by sbaechler

This problem arose again recently due to a bug in Python itself.

由于 Python 本身的错误,这个问题最近再次出现。

http://bugs.python.org/issue22931

http://bugs.python.org/issue22931

https://code.djangoproject.com/ticket/24280

https://code.djangoproject.com/ticket/24280

Among the versions affected were 2.7.8 and 2.7.9. The cookie was not read correctly if one of the values contained a [character.

受影响的版本包括 2.7.8 和 2.7.9。如果其中一个值包含[字符,则无法正确读取 cookie 。

Updating Python (2.7.10) fixes the problem.

更新 Python (2.7.10) 解决了这个问题。

回答by JunLe Meng

I have just met once, the solution is to empty the cookies. And may be changed while debugging SECRET_KEY related.

刚遇到过一次,解决办法是清空cookies。并且在调试时可能会更改 SECRET_KEY 相关。

回答by infosmith

Clearing my browser's cache fixed this issue for me. I had been switching between local development environments to do the django-blog-zinnia tutorial after working on another project when it happened. At first, I thought changing the order of INSTALLED_APPS to match the tutorial had caused it, but I set these back and was unable to correct it until clearing the cache.

清除浏览器的缓存为我解决了这个问题。在完成另一个项目后,我一直在本地开发环境之间切换,以完成 django-blog-zinnia 教程。起初,我认为更改 INSTALLED_APPS 的顺序以匹配教程导致了它,但是我将这些设置回原位并且在清除缓存之前无法更正它。

回答by dscanon

From ThisYou can solve it by adding the ensure_csrf_cookie decoratorto your view

这里您可以通过将ensure_csrf_cookie 装饰器添加到您的视图来解决它

from django.views.decorators.csrf import ensure_csrf_cookie
@ensure_csrf_cookie
def yourView(request):
 #...

if this method doesn't work. you will try to comment csrf in middleware. and test again.

如果这个方法不起作用。您将尝试在中间件中注释 csrf。并再次测试。