Reputation: 1665
I'm using Angular $http to post data to django, but django isn't receiving it. I must be either misusing $http (because this worked with ajax) or my django view is wrong.
<div ng-controller="mycontroller2">
<form ng-submit="submit()">
{% csrf_token %}
Search by name:<input ng-model="artiste" />
<input type="submit" value="submit" />
</form>
<table>
<tr ng-repeat="artist in artists">
<td> {({ artist.fields.link })} </td>
</tr>
</table>
</div>
<script>
artApp.controller('mycontroller2', ['$scope', '$http',
function($scope, $http){
$scope.submit = function(){
var postdata = {
method: 'POST',
url: '/rest/',
data: {
"artiste": $scope.artiste
},
headers: {
'X-CSRFTOKEN': "{{ csrf_token }}"
}
};
$http(postdata)
.success(function(data){
$scope.artists = data;
})
}
}]);
</script>
The request handler in views.py looks like
def rest(request):
artistname = request.POST.get("artiste") # should get 'da vinci'
response_data = {}
response_data = serializers.serialize("json", Art.objects.filter(artist__contains=artistname))
return HttpResponse(json.dumps(response_data), content_type="application/json")
The error I'm getting from Django is ValueError at /rest/ Cannot use None as a query value
.
My call to get the value of "artiste" must not be returning 'da vinci' from the $http
data
object. I'm sure it's sent successfully because the data artiste: da vinci
is shown in my headers in devtools. Django just isn't getting that value. Something wrong with the request.POST.get("artiste")
call?
Upvotes: 1
Views: 1058
Reputation: 1665
Since the data from my $http
request is raw json data, my Django request handler had to be changed to deal with that. Now the function (in views.py) looks like
def rest(request):
artistname = json.loads(request.body) # <- accepts raw json data
artistname = artistname['artiste'] # <- and now I can pull a value
response_data = {}
response_data = serializers.serialize(
"json", Art.objects.filter(artist__contains=artistname))
return HttpResponse(json.dumps(response_data), content_type="application/json")
Upvotes: 4