[Django]에러
AssertionError: The field 'place_id' was declared on serializer UserReviewedGetSerializer, but has not been included in the 'fields' option.
AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>`
두가지의 에러가 떴다
각각에 대해서 살펴보자
AssertionError: The field 'place_id' was declared on serializer UserReviewedGetSerializer, but has not been included in the 'fields' option.
첫번째 오류는 아래코드에서 발생되었다
class UserReviewedGetSerializer(serializers.ModelSerializer):
place_id = serializers.IntegerField()
class Meta:
model = PlaceVisitorReview
fields = ['place_name']
첫 번째 오류인 "AssertionError: The field 'place_id' was declared on serializer UserReviewedGetSerializer but has not been included in the 'fields' option"은 'place_id' 필드가 UserReviewedGetSerializer에서 정의되었지만, 해당 필드가 직렬화기(serializer)의 Meta 클래스의 'fields' 옵션에 포함되지 않아 발생합니다. 이 오류를 해결하기 위해 UserReviewedGetSerializer의 Meta 클래스의 'fields' 리스트에 'place_id'를 추가해야 합니다.
class UserReviewedGetSerializer(serializers.ModelSerializer):
place_id = serializers.IntegerField()
class Meta:
model = PlaceVisitorReview
fields = ['place_name', 'place_id'] # 'place_id'를 fields 리스트에 추가합니다.
AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>`
두번째 에러는 아래 코드에서 발생되었다.
def get(self,request):
try:
user = request.user
self.user=user
selector = UserReviewedSelector(user)
places = selector.list()
serializer = self.UserReviewedGetSerializer(places,many=True)
return Response({
'sataus':'success',
'data':serializer.data,
},status=status.HTTP_200_OK)
except Exception as e:
print("오류가 발생했습니다.")
print(traceback.format_exc())
두 번째 오류인 "AssertionError: Expected a Response, HttpResponse or HttpStreamingResponse to be returned from the view, but received a <class 'NoneType'>"는 뷰(view)에서 모든 코드 경로에서 응답을 반환하지 않아 발생합니다. get 메서드의 except 블록에서는 print 문이 있지만 반환(return) 문이 없습니다. 이 오류를 해결하기 위해 except 블록에 오류 응답과 함께 반환 문을 추가하거나 예외를 처리하여 유효한 응답을 반환해야 합니다.
다음은 except 블록에 오류 응답과 함께 반환 문을 추가하는 예입니다:
def get(self, request):
try:
# ...
except Exception as e:
print("오류가 발생했습니다.")
print(traceback.format_exc())
return Response({'status': 'error', 'message': '오류가 발생했습니다.'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
장고 입문 한달만에 결과 띄우기 성공!