Correct way to let user register/sign up with DRF?

Hello,

I am building my first Django Rest Framework project as a backend for mobile app and just today I implemented user registration via API. I couldn’t find any definitive tutorial related to registration so I pieced the code together using different SO answers and just wanna ask, whether this is a good approach.

class UsersSerializer(serializers.ModelSerializer):
class Meta:
    model = core_models.CustomUser
    fields = ('email', 'username', 'password')

def create(self, validated_data):
    user = super(UsersSerializer, self).create(validated_data)
    user.set_password(validated_data['password'])
    user.save()
    return user

And the view is just this:

class UserCreate(generics.CreateAPIView):
queryset = CustomUser.objects.all()
serializer_class = UsersSerializer
permission_classes = (AllowAny, )

Seems to be working fine when testing with Postman and then trying to log in. As a next step I want to enable Token authentification.

Thanks for help and suggestions!

Your basic implementation seems fine to me, though I think you’re hitting the database twice unnecessarily. I would probably change create to:

def create(self, validated_data):
    password = validated_data.pop('password')
    user = core_models.CustomerUser(**validated_data)
    user.set_password(password)
    user.save()
    return user

Thanks for the tip! I will change it.

Is there anything else you would do differently or maybe add?

I just realized that password field in serializer is mistake right? It does not make sense to send hashed password back…

Yeah, in cases like that I normally override to_representation and return data from a different serializer, or manually delete the fields you don’t want.

e.g.

def to_representation(self, obj):
    data = super().to_representation(obj)
    del data['password']
    return data

Thanks. I dug into a documentation a bit and found another way:

extra_kwargs = {'password': {'write_only': True}}

In Meta, seems to work fine :slight_smile: