I think the problem is in part due to the fact im not using the HTML template tag since, I'm creating a project using the JS generating the HTML from there. For addressing this in the HTML i added this script(before the js script I use):
<script> var csrfToken = '{{ csrf_token }}'; </script>
Im using the following script after the form code to send the information to my django project:
const apiSendDataUser = (event) => {
event.preventDefault();
const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]').value;
const formData = new FormData (event.target);
fetch('https://127.0.0.1:8000/myProject/post_user',{
method: 'POST',
body: formData,
headers: {
'X-CSRFToken': csrfToken
}
})
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error('Error: ' + response.status);
}
})
.then(data => {
// Handle the response data
console.log(data);
})
.catch(error => {
// Handle any errors
console.error(error);
});
};
And finally, the post_user function on the views.py is:
@require_POST
def post_user(request):
try:
email = request.POST['email']
if not User.objects.filter(email).exists() :
username = request.POST['username']
password = request.POST['password']
User.objects.create_user(username=username, password=password, email=email)
return JsonResponse(
{
"success":True,
"message": "Usuario añadido."
}
)
except Exception as e:
return JsonResponse({
"success": False,
"message": e.args[0]
}, status=404)
I've tried some options you have given me, for example I even gave up trying on JS and just placed the token in a form in the HTML, but it doesnt work, retrieves me 403: CSRF token missing. That is so weird since I've found the actual token and its value:
<input type="hidden" name="csrfmiddlewaretoken" value="VNHOnecTJVc61dUGpZaZ6X02yyGTayY6Bnnauqzv2NAmFi3XfhhU5Rj2El5kVtEl">
And this is it, if you got any idea what could be happening It would be nice to read you!