Django: CSRF middleware token missing

Django is rejecting the Square SDK example card.html form submission because of a missing CSRF token. I’ve tried including it in the body of the POST but it’s still getting rejected.

Here’s what I’ve got:

      async function createPayment(token) {
        const body = JSON.stringify({
          locationId,
          sourceId: token,
          csrfmiddlewaretoken: '{{ csrf_token }}',
        });

        const paymentResponse = await fetch('/payment', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body,
        });

Any assistance much appreciated.

1 Like

:wave: With the Web Payments SDK a csrfmiddlewaretoken isn’t required. Is there a reason that your adding it to the request? :slightly_smiling_face:

Python’s Django framework requires CSRF middleware tokens on all POST requests as a security standard. It’s considered good practice to always require one even in js/jquery submits.

I added the @csrf_exempt decorator to the receiving View function to override the default behaviour. I mean, if you’re absolutely sure it’s not required/good practice then I’ll just leave it but it seems odd that the only POST in my project without a CSRF token is credit card submit of all things!

That said, you guys are the experts and there are tokens built into the process so I’ll go with what you recommend.

1 Like