我收到405错误,特别是说CSRF verification failed. Request aborted. CSRF cookie not set.
我的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'),
)
我的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!')
我在终端输入的卷曲执行是:
curl -v -H "Accept: application/json" -H "Content-type: application/json" -X POST -d ' {"user" : "jeff", "password" : "pass1"} ' http://localhost:8000/users/add
并且运行我的服务器的终端返回:
[13/Feb/2014 00:38:06] "POST /users/add HTTP/1.1" 403 2282
我理解CSRF是什么,但是当没有cookie时,这将通过终端标记POST方法是什么?对此有什么补救措施?
答案 0 :(得分:2)
它可能会出现此错误,因为您可能在midware设置中启用了CSRF保护。
如果您不需要这种保护,可以将视图设置为CSRF exempt。 您可以在视图上使用装饰器,也可以将其从中间件设置中禁用。
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
@csrf_exempt
def my_view(request):
return HttpResponse('Hello world')