I recently completed a tutorial at and now I'm attempting to add a POST functionality to it. Despite obtaining the csrf from cookies and including it in the "csrfmiddlewaretoken" variable alongside a test message in json format for the axios function, I am facing issues when trying to send the csrf value to the server using Axios ajax framework.
Even after adding the @ensure_csrf_cookie decorator to views.py, I continue to encounter a 403 error. While using the @csrf_exempt decorator resolves the issue, I prefer to stick to using csrf for security purposes.
I am currently working with Django Version 3.0.8 in a venv environment.
A snippet from csrftoken.js:
import React from "react";
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== "") {
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
if (cookie.substring(0, name.length + 1) === name + "=") {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie("csrftoken");
const CSRFToken = () => {
return <input type="hidden" name="csrfmiddlewaretoken" value={csrftoken} />;
};
export default CSRFToken;
Snippet from App.js:
...
import axios from "axios";
import CSRFToken from "./csrftoken";
...
sendPost() {
var jsonPost = {
csrfmiddlewaretoken: document.getElementsByTagName("input")[
"csrfmiddlewaretoken"
].value,
transmitter: "This is houston Do you hear me Copy ",
};
axios({
method: "post",
url: "/api/sendpost/",
data: jsonPost,
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
...
render() {
return (
<ul>
<CSRFToken />
{this.state.data.map((contact) => {
return (
<div>
<li key={contact.id}>
{contact.name} - {contact.email}
</li>
<button onClick={() => this.sendPost()}>
Send A Post Message
</button>
</div>
);
})}
</ul>
);
}
Snippet from leads app's views.py:
from django.views.decorators.csrf import csrf_exempt,ensure_csrf_cookie
from django.http import JsonResponse
#@csrf_exempt
@ensure_csrf_cookie
def receivePost(request):
print(request.POST)
data = {
"receiver":"Received Houston"
}
return JsonResponse(data)
Snippet from settings.py:
...
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
'rest_framework.authentication.TokenAuthentication',
),
}
...
Snippet from urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('api/lead/', views.LeadListCreate.as_view() ),
path('api/sendpost/', views.receivePost ),
]
Edit: Despite enabling @csrf_exempt on views.py, the print(request.POST) returns an empty Querydict {}