Reputation:
I don't use a django form, we only process it with API and respond to the result. I want to handle it without using @csrf_exempt. When using a form, I know that you are using a tag, but in this case, it is difficult to write a tag. I can't get rid of csrf so I need help. When receiving a request as a post, "CSRF token missing or incorrect." Appears. How can I solve this problem?
Upvotes: 0
Views: 501
Reputation: 483
If you need the csrf token check the csrf doc.
You can add the given code to a global js file and then reference it anywhere. I'm including the code here, but it is the same in the docs.
function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
And then to get the csrf token:
const csrftoken = getCookie('csrftoken');
Here is the an example of how I use it in my fetch:
fetch('some_url', {
method: 'POST',
headers:{
'Accept': 'application/json',
'X-Requested-With': 'XMLHttpRequest',
'X-CSRFToken': csrftoken,
},
body: JSON.stringify({
some_key: some_var,
...
})
})
.then(response => {
jsonResponse = response.json();
status_code = response.status;
if(status_code != 200) {
alert('error');
} else {
alert('success');
}
})
.catch(error => {
console.log(error)
})
But make sure the csrf token is available in your template by including the csrf template tag {% csrf_token %}
Upvotes: 0
Reputation: 2088
If this is a stateless API (i.e. you don't use cookies) you can safely disable CSRF as follows:
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def post(request):
return 'page'
Upvotes: 1