Recommand · October 14, 2021 0

Django REST framework how to create new User?

I’m trying to get POST requests into my Django application using the Django REST framework, but for some reason I always fail getting a request trough. Either I get a permission error when creating a class based view. If I create a function based view I always run into validation error and Im kind of frustrated about the complexity of DRF.

Have a look at the following view to create a User object:

views.py

@api_view(['GET', 'POST'])
@permission_classes([AllowAny])
def user_create(request):
    if request.method == 'POST':
        print(request.data)
        serializer = CreateUserProfileSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({
            "user": UserSerializer(user, context=serializer.data)
        })

serializers.py

class CreateUserProfileSerializer(serializers.ModelSerializer):

    class Meta:
        model = get_user_model()
        fields = ('id', 'user',)
        extra_kwargs = {'password': {'write_only': True}}

    def create(self, validated_data):
        user = User.objects.create(
                validated_data['user'],
                validated_data['password'])
        user.save()
        return user

error when sending a POST to the endpoint:

   File "/App/App_API/serializers.py", line 36, in create
     validated_data['password'])
 KeyError: 'password'

Why that? If I do the following at my views code:

 print(request.data)

I see the following at the console:

<QueryDict: {'user': ['peter432'], 'password': ['OUBIfwiowef']}>

Can somebody please share his way of creating a user.

The correct way is to use User.objects.create_user.

See this answer: https://stackoverflow.com/a/23482284/117831

2 errors:

  1. Password is not in fields so it’s not in validated_data
  2. You’re saving the hashed password, you need to create the user instance in python level first and hash the password like:
password = validated_data.pop('password')
u1 = User(....)
u1.set_password(password)
u1.save()