Python/Django

[Django][Error] DRF 실행 관련 에러들

S0PH1A 2020. 1. 14. 20:24
반응형

[Django][Error] DRF 실행 관련 에러들


1. authenticators 에서 TypeError: 'type' object is not iterable

 

TypeError

... 생략 ...

File "/Users/jiyeon/.local/share/virtualenvs/backend-VwpUB2OP/lib/python3.7/site-packages/rest_framework/views.py", line 272, in get_authenticators
    return [auth() for auth in self.authentication_classes]
TypeError: 'type' object is not iterable

해결방법

settings.py의 REST_FRAMEWORK 튜플이 정상적으로 입력되었는지 확인한다.

()안 모든 요소 마지막에는 콤마(,)를 넣어줘야 한다.

comma


2. TypeError: Object of type AuthToken is not JSON serializable

 

TypeError

TypeError: Object of type AuthToken is not JSON serializable

해결방법

Response 시 결과물이 튜플이고 첫번째는 인스턴스 그리고 두번째가 토큰이 러턴값으로 나오기 때문에 두번째 것을 사용할 수 있도록 해야한다. (참고)

AuthToken

 


2. AttributeError

AttributeError at [URL경로]


Got AttributeError when attempting to get a value for field `[필드]` on serializer `[Serializerd이름]`.
The serializer field might be named incorrectly and not match any attribute or key on the `QuerySet` instance.
Original exception text was: 'QuerySet' object has no attribute '[필드]'.

해결방법

many=True옵션을 추가한다.

serializer는 한 개의 객체만 이해할 수 있고 리스트는 이해할 수 없다.

모델.objects.all()로 검색한 객체는 리스트이므로 many=True 함으로서 문제를 해결할 수 있다.

from rest_framework.views import APIView
from rest_framework.response import Response
from .serializers import PostSerializer
from .models import Post


class ListPostView(APIView):
	
    def get(self, request):
    	posts = Post.objects.all()
        serializer = PostSerializer(posts, many=True)
        return Response(serializer.data)

 


 

 

 

 

 

반응형