简体   繁体   中英

Django: Forbidden (CSRF cookie not set.)

I am having a problem with "CSRF cookie not set". All I need is that the external billing platform send the update to the django server. Locally it works with Postman but in the demo server its not working...

Code

# 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),
]

Error

Forbidden (CSRF cookie not set.): /billing/postback/
[21/Jul/2016 10:49:21] "POST /billing/postback/ HTTP/1.1" 403 2682

Result of the postback to the requestb server

https://requestb.in/p0rihap0?inspect#t67d6c

Env

  • Python 3.5.1+
  • Django 1.10rc1

If you have set the CSRF_COOKIE_SECURE to be True in your settings file, then the cookie will be marked as "secure" and therefore will need an HTTPS connection.

Which is why you receive that error.

For more information here .

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())),
    ...
)

In views.py

class ObjectView(CreateView):

    def post(self, request):
        if request.method == 'POST':
             #enter you view

I found the solution here: Django Rest Framework remove csrf

I use in some parts of the system the DRF and maybe it was generating the CSRF error and ignoring the csrf_exempt decorator.

Thank for your help!

CSRF_TRUSTED_ORIGINS = ['https://<my_domain>.com']

the code above work like margic

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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