Enabling CSRF for Django

I have the following python code in my Django views.py, the code takes in a JSON body and send the extracted DATA to another API endpoint, I have simplified the code here.

How do I enable csrf such that it will send the token back to the caller for this method? I am calling this from postman.

@csrf_protect
def validate_booking(request):
  if request.method != "POST":
    return HttpResponseServerError("Invalid HTTP method")
  body = json.loads(request.body)
  booking_details = body["booking_details"]

    DATA = {
      "name": booking_details["name"],
      "nric": booking_details["nric"],
      "booking_id": booking_details["booking_id"]
    }

  return HttpResponse(status="200")

This site directs to put this piece of code in my method. But what is "a_template.html"? https://docs.djangoproject.com/en/4.1/ref/csrf/

@csrf_protect
def my_view(request):
    c = {}
    # ...
    return render(request, "a_template.html", c)

This isn't an easy thing to do as CSRF is 2 steps thing

  1. There is a value that is passed to the client and it is saved to the session on the server.
  2. When a POST request is received, the client shall send this as csrfmiddlewaretoken in the body and the server will check the value against the stored one in the server's session.

So this isn't feasible to be done in APIs as you require session Management which is not of REST API implementations.

Thanks for your reply. I managed to find a solution by doing the following:

  1. Create a new GET method that will generate the session CSRF token using python
  2. Instead of using render which expects a HTML template file, I used JsonResponse(data) to return in JSON format directly
  3. In my postman app which I am making the POST request with the X-CSRFToken in the header, I will first make a GET request to the new method I created in step 1 to retrieve the token and store it as an environment variable

The following is the GET method sample:

from django.http import JsonResponse

def get_csrf_token(request):
    csrf_token = csrf(request)['csrf_token']
    data = {'csrf_token': csrf_token}
    return JsonResponse(data)
Back to Top