Django CSRF Cookie 未设置

我有一些问题,现在,我遇到 CSRF 饼干没有设置。请看下面的代码:

视图:

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


模板档案:

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

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

206257 次浏览

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

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

在模板中,数据使用 csrf _ token 进行格式化:

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

在你看来,你使用的是 csrf 装饰? ?

from django.views.decorators.csrf import csrf_protect

@ csrf _ protected def view(request, params): ... .

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

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

稍后,用户填写表单并发送带有表单数据的 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))

如果设置了 CSRF_COOKIE_SECURE = True并且您正在不安全地访问站点,或者如果将 CSRF_COOKIE_HTTPONLY = True设置为规定的 给你给你,也会发生这种情况

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

方法一:

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

方法二:

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

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

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

Http://bugs.python.org/issue22931

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

Among the versions affected were 2.7.8 and 2.7.9. 如果其中一个值包含 [字符,则未正确读取 Cookie。

更新 Python (2.7.10)修复了这个问题。

我只见过一次,解决办法是清空饼干。 并且可能在调试 SECRET_KEY时发生更改。

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.

来自 < a href = “ https://stackoverflow. com/questions/19598993/csrf-cookie-not-set-django-證明失败”> 可以通过将 Sure _ csrf _ cookie 修饰符添加到视图中来解决这个问题

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

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

from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt


@csrf_exempt
def your_view(request):
if request.method == "POST":
# do something
return HttpResponse("Your response")

我之前用的是 Django 1.10,所以我遇到了这个问题。 现在我把它降级为 Django 1.9,它运行良好。

确保 django 会话后端在 setings.py 中配置正确,

class CustomMiddleware(object):
def process_request(self,request:HttpRequest):
get_token(request)

根据 django 版本,在 settings.py中的 MIDDLEWARE_CLASSESMIDDLEWARE下添加这个中间件

Get _ token-返回 POST 表单所需的 CSRF 标记。该标记是一个字母数字值。如果尚未设置新标记,则创建一个新标记。

如果您以登录用户的身份使用 HTML5获取 API发送 POST 请求并获得 Forbidden (CSRF cookie not set.),这可能是因为默认情况下 fetch不包含会话 cookie,导致 Django 认为您是与加载页面的用户不同的用户。

您可以通过传递选项 credentials: 'include'来获取会话标记:

var csrftoken = getCookie('csrftoken');
var headers = new Headers();
headers.append('X-CSRFToken', csrftoken);
fetch('/api/upload', {
method: 'POST',
body: payload,
headers: headers,
credentials: 'include'
})

我在使用 DRF 时遇到过类似的情况,解决方案是在 urls.py中的视图中附加 .as_view()方法。

I had the same error, in my case adding method_decorator helps:

from django.views.decorators.csrf import csrf_protect
from django.utils.decorators import method_decorator


method_decorator(csrf_protect)
def post(self, request):
...

当您没有设置表单操作时也会发生这种情况。
对我来说,当代码是:

<form class="navbar-form form-inline my-2 my-lg-0" role="search" method="post">

当我把我的代码改成这样的时候:

<form class="navbar-form form-inline my-2 my-lg-0" action="{% url 'someurl' %}" role="search" method="post">

my error disappeared.

如果您正在使用 DRF,请检查您的 urlpattern 是否正确,也许您忘记了 .as_view():

So that how mine code looked like:

urlpatterns += path('resource', ResourceView)

它应该是这样的:

urlpatterns += path('resource', ResourceView.as_view())

如果您在呈现的模板中没有使用 {% csrf_token %}标记,Django 将不会设置 csrftoken cookie。

若要强制 django 设置 csrftoken cookie,请在视图中添加 Sure _ csrf _ cookie装饰符。

from django.views.decorators.csrf import ensure_csrf_cookie


@ensure_csrf_cookie
def myview(request):

In my particular case, the problem is that I was using the Django rest_framework and forgot to add the following decorators to my function:

from rest_framework.decorators import api_view, renderer_classes


@api_view(('POST',))
@renderer_classes((JSONRenderer,))
def handle_web_request(request):
...

我只是想指出我的情况,因为有人可能会穿越相同的领域。

Forbidden (CSRF cookie not set.): /main/staff/products/validation/create
HTTP POST /main/staff/products/validation/create 403 [0.01, 127.0.0.1:55940]

这东西快把我逼疯了... 所以,通过评论 CSRF 中间件

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

它给了我

POST Method not allowed.

毕竟这是我的暗示。 我确信波斯特方法是存在的。 原来我的 url_patterns由于正则表达式错误导致了另一个视图。

因此,无论我在我的视图中做什么,@csrf_exempt @ensure_crsf_cookie,寻找 .as_view()... 我看到了错误的视图。

因此,如果没有工作,请确保您实际上被发送到正确的视图。

You can get this error while deploing Django application with NO SSL. If this is the case then putting an SSL reverse-proxy or SSL-configured Ingress in front of backend will solve the problem.

我得到这个错误并修改它:

<form method="post">

回到这里:

<form method="POST">

问题解决了! 只是大写后使问题! 在127.0.0.1中我没有任何问题,但是当我使用192.168.x.x 地址时,它破坏了我的表单。

In my case, setting CSRF_COOKIE_SECURE to False wasn't enough but setting it to Null/ not specifying the parameter worked.

在我的例子中,问题是 nginx 中静态文件的路径指定不正确。

sudo tail -F /var/log/nginx/error.log

检查文件路径中是否有错误。