[Answered ]-Serialize the creation of user and profile django rest framework

2👍

Why do you need UserSerializer at first place? Change your ProfileCreateSerializer to following. It should work

class ProfileCreateSerializer(serializers.ModelSerializer):
   username = serializers.CharField(source='user.username')

   class Meta:
       model = Profile
       fields = [
       'username',
       'language',
       ]

   def create (self, validated_data):
    user = get_user_model().objects.create(username=validated_data['username'])
    user.set_password(User.objects.make_random_password())
    user.save()

    profile = Profile.objects.create(user = user)

    return profile

Since the create method is override at your serializer, you need to send the data as a format the serializer process. So, you need to override the POST request at the views and create data as follows :

from rest_framework import status
from rest_framework.response import Response

class ProfileCreateAPIView(CreateAPIView):
    model = Profile
    serializer_class = ProfileCreateSerializer

    def post(self, request, *args, **kwargs):
        data = {
            'username': request.data.get('username', None),
            'language': request.data.get('language', None),

        }

        serializer = ProfileCreateSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return Response(
                serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response( serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Leave a comment