在構建基於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 serializerVariableNameSerializer
. The serializer field might be named incorrectly and not match any attribute or key on thedict
instance. Original exception text was: 'name'."
據我瞭解,這我不知道是正確的,錯誤的意思是,它找不到名爲'name'的字段,該字段會引發KeyError。然而,一個'名字'字段當然存在,就像你在我的代碼中看到的那樣。請注意,在這兩個錯誤中,堆棧跟蹤都沒有包含我寫的任何函數,我發現這些函數很奇怪,並且是初學者,我從來沒有遇到過這樣的事情。
你是對的,這工作。但是,如果我想讓JSON擁有一個名爲「value」的屬性,而不是「name」,那麼這是不可能的? –
編輯回覆。 – Linovia