2
respostas

Erro ao Reescrever o Méthodo Create

File "/home/vinicius/Documents/Python/Django Rest/ESCOLA_API/escola/views.py", line 38, in create serializer = self.serializer_class(data=request.data) TypeError: 'NoneType' object is not callable [06/Jan/2023 13:15:45] "POST /alunos/ HTTP/1.1" 500 97500

Meu código

class AlunosViewSet(viewsets.ModelViewSet):
    """ Exibindo todos os alunos """

    queryset = Aluno.objects.all() # Trazendo todos os alunos
    # em todas as classes, por default estão:
    authentication_classes = [BasicAuthentication]
    permission_classes = [IsAuthenticated, DjangoModelPermissions]
    # Filtros e Pesquisa
    filter_backends = [DjangoFilterBackend, filters.OrderingFilter, filters.SearchFilter]
    ordering_fields = ['nome', 'id']
    search_fields = ['nome', 'id']



    def get_serializer_class(self):
        if self.request.version == 'v2':
            return AlunoSerializerV2
        else:
            return AlunoSerializerV1

    def create(self, request):
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            serializer.save()
            response = Response(serializer.data, status=status.HTTP_201_CREATED)
            id = str(serializer.data['id'])
            response['Location'] = request.build_absolute_uri() + id
            return response
2 respostas

Eu consegui resolver usando:

def create(self, request, *args, **kwargs):
    serializer = self.get_serializer(data=request.data)
    if serializer.is_valid(raise_exception=True):
        serializer.save()
        headers = self.get_success_headers(serializer.data)
        id = str(serializer.data['id'])
        response = Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
        response['Location'] = request.build_absolute_uri() + id

        return response

Para resolver esse problema eu tive que importar o status do rest_framework dessa maneira ficou assim:

from rest_framework import viewsets, generics, status

E o build_absolute_uri() foi necessário pegar através do self.request.build_absolute_uri(), então ficou assim:

response['Location'] = self.request.build_absolute_uri() + id

O código final do create do viewSet de cursos ficou assim:

 class CursosViewSet(viewsets.ModelViewSet):
    '''Exibindo todos os cursos'''
    queryset = Curso.objects.all()
    serializer_class = CursoSerializer

    def create(self, request):
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            serializer.save()
            response = Response(
                serializer.data, status=status.HTTP_201_CREATED)
            id = str(serializer.data['id'])
            response['Location'] = self.request.build_absolute_uri() + id
            return response