Search code examples
djangodjango-rest-frameworkdjango-serializerdjango-users

Set default serializer for user in django


I created a rest-framework API in django for signup and its serializer is like this:

class SignupSerializer(ModelSerializer):

class Meta:
    model = User
    fields = ('email', 'password', 'first_name', 'last_name')
    read_only_fields = ()

def create(self, validated_data):
    with transaction.atomic():
       new_user = User.objects.create_user(....)
       return new_user

Now its working perfectly fine, but problem is that it also returns password hash in response object. Or if i include user in any other serializer and set depth=1 it still returns every field including password

How can I set default serializer for user? so that it only returns those fields which I set by myself?


Solution

  • Django Rest Framework fields can be configured to be "write only". The documentation even has an example that pretty much covers your usecase:

    class CreateUserSerializer(serializers.ModelSerializer):
        class Meta:
            model = User
            fields = ['email', 'username', 'password']
            extra_kwargs = {'password': {'write_only': True}}
    
        def create(self, validated_data):
            user = User(
                email=validated_data['email'],
                username=validated_data['username']
            )
            user.set_password(validated_data['password'])
            user.save()
            return user
    

    https://www.django-rest-framework.org/api-guide/serializers/#additional-keyword-arguments