2014-12-04 94 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")