2016-11-23 50 views
0

這是我的看法,無法獲取POST數據Django的REST框架

@api_view(['GET','POST']) 
def login(request): 
    if request.method == 'GET': 
     posts = Posts.objects.all() 
     serializer = PostSerializer(posts, many=True) 
     return Response(serializer.data) 
    elif request.method == 'POST': 
     usr = request.data.get('username') 
     print(request.data) 
     pwd = request.data.get('password') 
     try: 
      user = Users.objects.get(username=usr) 
      if user.password == pwd: 
       return Response(UserSerializer(user).data) 
      else: 
       return Response({}) 
     except Users.DoesNotExist: 
      return Response({}) 

這是我在angularjs控制器通話

$http.post("api/v1/login/",{"username":$scope.username,"password":$scope.password}) 
      .then(
       function(response){ 
       console.log('r',response.data) 
       }, 
       function(response){ 
       console.log('e',response) 
       } 
      ); 

我在我的view.I得到一個空對象還角度配置添加

$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; 
     $httpProvider.defaults.xsrfCookieName = 'csrftoken'; 
     $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken'; 

在一些blog.the request.data建議仍然empty.Where我做錯了認罪我指導我正確。提前感謝。

,因爲有一些無關痛癢的code.The問題應該在於code.Please這兩個區塊幫助 .The獲得Ajax請求我已經更新了這個職位是working.Only在文章中,我能得到的任何數據。

回答

0
from rest_framework.decorators import api_view, parser_classes 
from rest_framework.parsers import FormParser, MultiPartParser 

@api_view(['GET','POST']) 
@parser_classes((FormParser, MultiPartParser)) 
def login(request): 
    ... 
+0

我已經按照您的建議添加了,但仍然在'print(response.data)'.getting 中獲得一個空對象 – saiyan

+0

請試用MultiPartParser嗎? –

+0

MultiPartParser在客戶端給我一個錯誤,說「不支持的媒體類型」 – saiyan

0

安裝ngCookies然後加入這行代碼:

.run(['$rootScope', '$log', '$http', '$cookies', 
function ($rootScope, $log, $http, $cookies) { 
    $http.defaults.headers.common['X-CSRFToken'] = $cookies['csrftoken']; 
}]); 

清潔您的瀏覽器,然後再試一次。

+0

謝謝,我已經解決了這個問題。這個問題在我身邊。我沒有檢查實際的數據是否存在。請繼續討論,並再次感謝。 – saiyan