Serializer user "Invalid data. Expected a dictionary, but got User"

I am trying to display the fields of my user model but I always get that my serializer is not valid { "non_field_errors": [ "Invalid data. Expected a dictionary, but got User." ] }

this is my model

from django.db import models
from django.contrib.auth.models import BaseUserManager, AbstractBaseUser, PermissionsMixin


class UserManager(BaseUserManager):
    def _create_user(self, username, password, is_staff, is_superuser, **extra_fields):
        user = self.model(
        username=username,
        is_staff=is_staff,
        is_superuser=is_superuser,
        **extra_fields
    )
    user.set_password(password)
    user.save(using=self.db)
    return user

def create_user(self, username, password=None, **extra_fields):
    return self._create_user(username, password, False, False, **extra_fields)

def create_superuser(self, username, password=None, **extra_fields):
    return self._create_user(username, password, True, True, **extra_fields)


class User(AbstractBaseUser, PermissionsMixin):
    username = models.CharField(max_length=255, unique=True)
    email = models.EmailField( max_length=255, blank=True, null=True)
    name = models.CharField(max_length=255, blank=True, null=True)
    age = models.PositiveIntegerField()
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    objects = UserManager()

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = []

    def __str__(self):
       return f"{self.id} {self.name} {self.username} {self.age}"

this is my serializer

class UserUpdateSerializer(serializers.ModelSerializer):
class Meta:
    model = User
    fields = ['id', 'email', 'username', 'name', 'age']

this is my view

class UserUpdateApiView(APIView):
    def get(self, request, pk):
        try:
            queryset = User.objects.get(pk=pk)
            serializer = UserUpdateSerializer(data=queryset)
            if serializer.is_valid(raise_exception=True):
                return Response(data=serializer.data)
        except User.DoesNotExist:
            return Response(data={"error": "User no found"}, status=status.HTTP_404_NOT_FOUND)

You have used the data keyword argument, i think the problem is here. Pass the queryset without keyword argument:

class UserUpdateApiView(APIView):
    def get(self, request, pk):
        try:
            queryset = User.objects.get(pk=pk)
            serializer = UserUpdateSerializer(queryset)
            return Response(serializer.data)
        except User.DoesNotExist:
            return Response(data={"error": "User no found"}, status=status.HTTP_404_NOT_FOUND)

data is the serialized output in fact. the keyword argument for passing your input model data is named instance I believe

Back to Top