Home > database >  Django - Serialized model of type User is not JSON serializable
Django - Serialized model of type User is not JSON serializable

Time:10-08

I'm currently trying to find out how setup a API for my app using the django rest framework. Currently I have the following two files:

serializers.py:

from rest_framework import serializers, permissions
from App_Accounts.models import User


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('user',)

views.py

from rest_framework import permissions
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response


@api_view(['GET'])
@permission_classes((permissions.AllowAny,))
def current_user(request):
    user = request.user
    return Response({
        'user': user,
    })

When I open: http://localhost/api/current_user/ it just get the following error returned at my console:

   File "/usr/local/lib/python3.9/json/encoder.py", line 179, in default
     raise TypeError(f'Object of type {o.__class__.__name__} '  TypeError: Object of type User is not JSON serializable

I don't know how important it is but I'm using a custom User model

models.py

class User(AbstractBaseUser):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.CharField(max_length=15, unique=True, verbose_name=_("Username"))
    avatar = models.ImageField(
        null=True,
        blank=True,
        upload_to=get_file_path_user_avatar,
        validators=[default_image_size, default_image_file_extension],
    )
    avatar_tn = models.ImageField(
        null=True,
        blank=True,
        upload_to=get_file_path_user_avatar,
    )

    ...

CodePudding user response:

Okay I got it working like this:

at my views.py I do:

@api_view(['GET',])
def current_user(request):
    if request.method == 'GET':
        users = User.objects.all()
        user_serializer = UserSerializer(users, many=True)
        return JsonResponse(user_serializer.data, safe=False)

at serializers.py I do:

class UserSerializer(serializers.ModelSerializer):
    id = serializers.PrimaryKeyRelatedField(queryset=User.objects.all())
    class Meta:
        model = User
        fields = ('user', 'id')

This returns my the following JSON:

[
  {
    "user": "admin",
    "id": "b910aa3e-7716-467e-8ec6-dd3a545663f0"
  }
]

CodePudding user response:

I see that you didn't use the built serializer UserSerializer in your view, try to update your view:


@api_view(['GET']) 
@permission_classes((permissions.AllowAny,))
def current_user(request):
    serializer = UserSerializer(request.user)
    Response(serializer.data)
  • Related