Brian Barry
Brian Barry

Reputation: 559

CSRF verification failed on post request to Django Server

I'd like to post data to an endpoint hosted by Django. I am using cURL in my terminal to do this:

curl -X POST -H "Content-Type: application/json" http://127.0.0.1:8000/bucket/create/ --data '{"name":"test2", "description":"hey"}'

This returns the following error in an xml message:

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.

Help Reason given for failure:

CSRF cookie not set.
 In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django’s CSRF mechanism has not been used

correctly. For POST forms, you need to ensure:

Your browser is accepting cookies. The view function passes a request to the template’s render method. In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL. If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data. The form has a valid CSRF token. After logging in in another browser tab or hitting the back button after a login, you may need to reload the page with the form, because the token is rotated after a login.

I tried adding a @csrf_exempt decorator to the relevant backend view but this does not help. I'm not sure how to properly make API requests to my Django server.

Upvotes: 0

Views: 1841

Answers (1)

Jairus Matthias
Jairus Matthias

Reputation: 43

If you are using Django Version 4.0

https://docs.djangoproject.com/en/4.0/ref/settings/#csrf-trusted-origins

has to be included in the settings.

CSRF_TRUSTED_ORIGINS = ['https://*.example.com']

add this to the settings.py

Upvotes: 1

Related Questions