8

I am sending a POST request to my server from an android application, but I am getting this error:

enter image description here

The POST looks like: http://example/my_page_url/1000 Where the 1000 is an ID.

This is my views method:

def inventory(request, cross_id):

    text_file = open("test.txt", "w")
    text_file.write('POST Received')

    text_file.write(cross_id.__str__())
    text_file.close()

    return render(request, 'Inventory.html', {})

my template code:

<form action='' method="POST">

     <button type="submit" id="btn_save" name="btn_save">Save</button>

    {% csrf_token %}

</form>

Actually, I don't really need to call a template, because I want to perform something on the server only. But I am calling the template just to prevent any errors for now.

I have read the other answers for the same problem but all of them have missed the CSRF token in the template or something else in the views method, but I believe the case is different here.

Sayse
  • 42,633
  • 14
  • 77
  • 146
The Maestro
  • 659
  • 1
  • 5
  • 21

1 Answers1

13

You need to add the X-CSRFToken header to all your POST requests.

You can get the appropriate value for this header from the cookie named csrftoken.

To test this in Postman, you need to enable the Interceptor plugin (top right corner).

Once you have it installed, make a GET request to /admin/login/ (make sure you are logged out from the site in the browser). In the cookies section you should see a cookie named csrftoken, copy its value.

Now, set the request type to POST for the same URL (/admin/login), add a header named X-CSRFToken with the value you copied earlier. Set the username and password fields in the Body section and hit send.

X-CSRFToken

If your POST do not require authentication, you can use the csrftoken from an earlier GET request.

Kedar
  • 1,648
  • 10
  • 20
  • Hi @Kedar do I need to provide `username` and `password` and **login** to the page while making a `GET` request to `/admin/login` or just visit the page without logging in to get the **csrftoken** value? – aspiring1 Mar 14 '22 at 02:28
  • @aspiring1 Just visiting the page (GET request without login details) is sufficient – Kedar Mar 14 '22 at 11:19
  • What if I have only `POST ` request enabled for my application? How can I get the csrf token in this scenario – aspiring1 Mar 15 '22 at 03:39
  • You can remove CSRF checks in that case https://stackoverflow.com/a/16458216/1268926 – Kedar Mar 15 '22 at 09:33