Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSRF verification failed. Request aborted. When I send POST request

Tags:

django

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.

like image 582
The Maestro Avatar asked Mar 21 '16 08:03

The Maestro


1 Answers

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.

like image 61
Kedar Avatar answered Sep 18 '22 11:09

Kedar