简体   繁体   English

Django返回403错误-“未设置CSRF Coo​​kie”

[英]Django returning 403 Error — “CSRF cookie not set”

I'm getting a 405 error, specifically saying CSRF verification failed. Request aborted. CSRF cookie not set. 我收到405错误,特别是说CSRF verification failed. Request aborted. CSRF cookie not set. CSRF verification failed. Request aborted. CSRF cookie not set.

My urls.py is: 我的urls.py是:

from django.conf.urls import patterns, include, url
from django.contrib import admin
from users.views import HandlerView
admin.autodiscover()

urlpatterns = patterns('',
    url(r'^admin/', include(admin.site.urls)),
    url(r'^users/login$', HandlerView.as_view(), name='my-view'),
    url(r'^users/add$', HandlerView.as_view(), name='my-view'),
)

and my views.py is: 而我的views.py是:

from django.shortcuts import render
from django.http import HttpResponse
from django.views.generic import View

class HandlerView(View):
    def get(self, request, *args, **kwargs):
        return HttpResponse('Hello, World!')

    def post(self, request, *args, **kwargs):
        print "Hello world!"
        return HttpResponse('Hello, World!')

The curl execution that I'm inputting at my terminal is: 我在终端输入的curl执行为:

curl -v -H "Accept: application/json" -H "Content-type: application/json" -X POST -d ' {"user" : "jeff", "password" : "pass1"} ' http://localhost:8000/users/add

and the terminal running my server returns: 运行我的服务器的终端返回:

[13/Feb/2014 00:38:06] "POST /users/add HTTP/1.1" 403 2282

I understand what CSRF is, but what would this be flagging for a POST method through the terminal, when theres no cookies right? 我了解CSRF是什么,但是当没有cookie时,通过终端对POST方法进行标记是什么? What would be the remedy to this? 有什么补救办法呢?

It might be giving this error because you might be having the CSRF protection turned on in middelware settings. 可能出现此错误,因为您可能在中间软件设置中打开了CSRF保护。

If you don't need that protection, you can set the view as CSRF exempt . 如果您不需要这种保护,可以将视图设置为CSRF exempt You can simply use a decorator on the view or you can turn it disable it from middleware settings. 您可以只在视图上使用装饰器,也可以将其从中间件设置中禁用。

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

@csrf_exempt
def my_view(request):
    return HttpResponse('Hello world')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM