2014-12-04 88 views
0

我使用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

我的电话获得“artiste”的值不能从$httpdata对象返回“da vinci”。我确定它已成功发送,因为数据artiste: da vinci显示在我的devtools头文件中。 Django没有得到那个价值。拨打request.POST.get("artiste")有什么问题?

+1

如果数据(艺术家)真的发送到服务器,您是否检查过(控制台上的“网络”选项卡)? – pleasedontbelong 2014-12-04 10:21:13

+0

是的,我相信。在网络标签中显示500错误,我点击它并转到“标题”,在“请求有效载荷”下显示“artiste:”da vinci“'。那是你在说什么? – 2014-12-04 11:19:39

+1

是的..所以这真是一个Django的问题。您需要使用[pdb](https://docs.python.org/2/library/pdb.html)或[runserver_plus](http://django-extensions.readthedocs.org/en)来查看请求对象/latest/runserver_plus.html) – pleasedontbelong 2014-12-04 11:27:47

回答

3

因为从我$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")