I'm building a web app with angularjs and django and I'm submitting form via Ajax request.
My problem is that when posting an Ajxa request with angular (ng-file-upload precisely) the csrfmiddlewaretoken expected by django is not set.
From my lectures on angular documentation and other forums I ended up with the following configuration.
In the config part of angular :
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
$httpProvider.defaults.withCredentials = true;
and in my controller the code for sending the request is :
Upload.upload({
url: 'http://localhost:8000/image',
headers: {
'X-CSRFToken': $cookies['csrftoken']
},
data: {file: file}
})
With that code the request send has the following headers :
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate
Accept-Language:fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4,de;q=0.2,fi;q=0.2
Connection:keep-alive
Content-Length:16582
Content-Type:multipart/form-data; boundary=----WebKitFormBoundarybWo821vSwcejTATP
Cookie:csrftoken=bC2UpXurGXAg3AUZgSqMVlUs8TKfussS
Host:localhost:8000
Origin:http://127.0.0.1:8000
Referer:http://127.0.0.1:8000/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36
X-CSRFToken:UeSt4LoqgU9L28JQBdVbS2IJJXOMQK6n
However for django to be able to handle csrf protection correctly the following header is missing
Cookie:_ga=GA1.1.1358238168.1447425523; XSRF-TOKEN=zWIM6q7O2Nz3PLm8TMUJSLFVRF8bKUbr; csrftoken=UeSt4LoqgU9L28JQBdVbS2IJJXOMQK6n
So far and despite having seen a lot of forums about this topic I didn't manage to set this header. if I try to set it programmatically via :
Upload.upload({
url: 'http://localhost:8000/image',
headers: {
'Cookie': 'csrftoken='+$cookies['csrftoken']
},
data: {file: file}
})
I end up with the following error in my console :
Refused to set unsafe header "Cookie"
My problem is really how to configure the cookie header from the client side. My django code is fine.
I have been struggling with this for quite a time now. Any help would be appreciated ! Thanks