1

I am beginning to use the Django Rest Framework and making a user registration process. I have used this to create a rudimental version and it works fine, but I get the hashed password back in my response, which I don't want. Tried using write_only_fields, but that made no difference.

This is my current serializer:

class UserSerializer(serializers.ModelSerializer):
    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

    class Meta:
        model = User
        fields = ('id', 'username', 'email', 'password',)
        write_only_fields = ('password',)

How can I prevent DRF to return the created password in the response?

Community
  • 1
  • 1
Bart Friederichs
  • 33,050
  • 15
  • 95
  • 195
  • See if [this SO QA](http://stackoverflow.com/questions/18812732/dynamically-include-or-exclude-serializer-class-fields) can help you out – Pynchia Dec 07 '15 at 23:11

2 Answers2

0

Declare the password field explicitly like this and rest of the code will remain same:

password = serializers.CharField(write_only=True)

Other method can be to delete the password from the to_representation method:

def to_representation(self, instance):
    ret = super(MySerializer, self).to_representation(instance)
    del ret['password']
    return ret
zaphod100.10
  • 3,331
  • 24
  • 38
0

You may use different serializers for creating a user and for showing the user's data. For example, you may inherit from the basic UserSerializer class and thus create something like ReadOnlyUserSerializer, where you completely remove the password field from the Meta.fields property. The only thing you will need to do is to switch between these serializers properly in ViewSets or whatever you use to render the output.

abcdn
  • 1,397
  • 14
  • 15