Django视图没有从Angularjs $ http请求接收数据

时间:2014-12-04 10:08:19

标签: javascript python django angularjs

我使用Angular $ http将数据发布到django,但django并未接收它。我必须要么误用$ http(因为这适用于ajax)或者我的django视图是错误的。

<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>

views.py中的请求处理程序看起来像

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")

我从Django获得的错误是ValueError at /rest/ Cannot use None as a query value

我打电话来获得&#34; artiste&#34;一定不要回来了达芬奇&#39;来自$http data对象。我确定它已成功发送,因为数据artiste: da vinci显示在devtools的标头中。 Django并没有获得这个价值。 request.POST.get("artiste")电话有问题吗?

1 个答案:

答案 0 :(得分:4)

由于来自$http请求的数据是原始json数据,因此必须更改我的Django请求处理程序以处理它。现在函数(在views.py中)看起来像

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")