2017-04-05 29 views
0

在構建基於django的Web應用程序的過程中,遇到了一個錯誤,我無法解決該如何解決。在應用中,我的Angular2前端發送POST請求,其傳遞給後端的以下形式的JSON對象:Django Rest-Framework序列化程序:肯定存在的字段上拋出的KeyError

{ 
    "variable": { 
     "name": "testVar" 
    } 
} 

在接收到該請求的節目的流程進到後功能,它在以下視圖中定義,它從django rest-framework的APIView繼承。

class VariableAPIView(APIView): 

    permission_classes = (AllowAny,) 
    renderer_classes = (VariableJSONRenderer,) 
    serializer_class = VariableNameSerializer 

    def post(self, request): 
     variable = request.data.get('variable', {}) 
     serializer = self.serializer_class(data=variable) 
     serializer.is_valid(raise_exception=True) 

     return Response(serializer.data, status=status.HTTP_200_OK) 

串行器的主要邏輯發生在這段代碼中。

class VariableNameSerializer(serializers.Serializer): 
    name = serializers.CharField(max_length=255) 

    def validate(self, data): 
     name = data.get('name', None) 

     if name is None: 
      raise serializers.ValidationError('A variable name is required.') 

     try: 
      value = server.ReadVariable(name) 
     except Exception: 
      raise serializers.ValidationError('A variable with this name could not be found') 

     return { 
      'value': value, 
     } 

當Django的服務器接收到一個請求,我得到以下異常:

KeyError: 'name'

During handling of the above exception, another exception occurred:

KeyError: "Got KeyError when attempting to get a value for field name on serializer VariableNameSerializer . The serializer field might be named incorrectly and not match any attribute or key on the dict instance. Original exception text was: 'name'."

據我瞭解,這我不知道是正確的,錯誤的意思是,它找不到名爲'name'的字段,該字段會引發KeyError。然而,一個'名字'字段當然存在,就像你在我的代碼中看到的那樣。請注意,在這兩個錯誤中,堆棧跟蹤都沒有包含我寫的任何函數,我發現這些函數很奇怪,並且是初學者,我從來沒有遇到過這樣的事情。

回答

1

不知何故,您從驗證返回{'value':value}而不是{'name':value},這會混淆DRF。

編輯: 如果你真的需要value,而不是name,你還需要將source參數添加到字段:

name = serializers.CharField(source='value', max_length=255) 

它可能已經在驗證的數據被轉換成價值,而不是死的肯定關於。

+0

你是對的,這工作。但是,如果我想讓JSON擁有一個名爲「value」的屬性,而不是「name」,那麼這是不可能的? –

+0

編輯回覆。 – Linovia

相關問題