In my cenario I am using a form in my react frontend (http://localhost:3000/submit) to post to my url http://localhost:8000/api/submit/
However, I have received this response:
"detail": "CSRF Failed: CSRF token missing or incorrect."
My class view is something like that:
from rest_framework.views import APIView
from rest_framework.parsers import MultiPartParser, FormParser
class Submit(APIView):
parser_classes = (MultiPartParser, FormParser)
def post(self, request, *args, **kwargs):
#custom post
I have two questions:
**
**
import cookie from "react-cookies";
...
<input
type="hidden"
value={cookie.load("csrftoken")}
name="csrfmiddlewaretoken"
/>
You need to set both the cookie and the header to the CSRF token as transmitted during the initial call wich loads the react page.
Basically you need to read the value of the cookie "csrftoken" as transmitted from the Django server and set that as the value of the header "X-CSRFTOKEN" for all the post AJAX requests in your react app. Best done generally (index.js for example).
Example using axios (we are using graphql) client in React:
import axios from "axios";
import cookie from "react-cookies";
axios.defaults.xsrfCookieName = "csrftoken";
axios.defaults.xsrfHeaderName = "X-CSRFTOKEN";
your_client.setHeaders({"X-CSRFTOKEN": cookie.load("csrftoken")});
Without ajax, add the cookie's value to the form like this - if you cannot use the template tag {% csrf_token %}
(in a react form):
<input type="hidden" name="csrfmiddlewaretoken" value="{value-of-the-cookie}" />
The documentation: https://docs.djangoproject.com/en/3.1/ref/csrf/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With