我遇到“未设置CSRF cookie”的问题。我只需要外部计费平台将更新发送到django服务器。在本地它可以与Postman一起使用,但在演示服务器中它不起作用......
# views.py
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
@csrf_exempt
def postback(request):
print(request.POST)
return JsonResponse({'ok': 'hoooh!'})
# urls.py
from django.conf.urls import url
from billing import views
urlpatterns = [
url(r'^postback/$', views.postback),
]
Forbidden (CSRF cookie not set.): /billing/postback/
[21/Jul/2016 10:49:21] "POST /billing/postback/ HTTP/1.1" 403 2682
https://requestb.in/p0rihap0?inspect#t67d6c
答案 0 :(得分:5)
如果您已在设置文件中将CSRF_COOKIE_SECURE
设置为True
,则Cookie将被标记为" secure"因此需要HTTPS连接。
这就是您收到该错误的原因。
了解更多信息here。
答案 1 :(得分:1)
我在这里找到了解决方案: Django Rest Framework remove csrf
我在系统的某些部分使用DRF,可能是在生成CSRF错误并忽略 csrf_exempt 装饰器。
感谢您的帮助!
答案 2 :(得分:0)
I modify urls.py
If you manage your routes in urls.py, you can wrap your desired routes with csrf_exempt() to exclude them from the CSRF verification middleware.
from django.conf.urls import patterns, url
from django.views.decorators.csrf import csrf_exempt
from . import views
urlpatterns = patterns('',
url(r'^object/$', csrf_exempt(views.ObjectView.as_view())),
...
)
在views.py
class ObjectView(CreateView):
def post(self, request):
if request.method == 'POST':
#enter you view