Home » Django & REST Api » Solved: Forbidden (CSRF cookie not set.)

Solved: Forbidden (CSRF cookie not set.)

When you have developed Django Views using function, and now tried to do http POST then you may sometimes see an error as below,

Forbidden (403)

CSRF verification failed. Request aborted.

You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties.

If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for “same-origin” requests.

Solution1 :

Open your views.py file and add “@csrf_exempt” above the functions..

For example : in our case for our API http://127.0.0.1:8000/users/, when we did http POST, we were getting error as,

So, we opened our views.py file, helloproject/helloapp/views.py and added “@csrf_exempt” , just above api function “users” as,

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def users(request):

Now, when you run the server again and do http POST, you will not see the error..

Solution 2 :

While we were trying to do “DELETE” on class based views implementation, our first solution to didn’t worked. So as an workaround to get it working without proper implementation of CSRF Cookies, we can just disable “django.middleware.csrf.CsrfViewMiddleware” from MIDDLEWARE in settings.py

MIDDLEWARE = [
#    'django.middleware.csrf.CsrfViewMiddleware',
]


Subscribe our Rurban Life YouTube Channel.. "Rural Life, Urban LifeStyle"

Leave a Comment