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.
CodePudding user response:
The correct way is to use User.objects.create_user
.
See this answer: https://stackoverflow.com/a/23482284/117831
CodePudding user response:
2 errors:
- Password is not in
fields
so it's not invalidated_data
- 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()
CodePudding user response:
This works for me:
views.py
@api_view(['POST'])
@permission_classes([AllowAny])
def user_create(request):
if request.method == 'POST':
print(request.data)
serializer = CreateUserSerializer(data=request.data)
if serializer.is_valid(raise_exception=True):
serializer.save()
return JsonResponse(serializer.data, safe=False)
serializers.py
class CreateUserSerializer(serializers.ModelSerializer):
class Meta:
model = get_user_model()
fields = ('user', 'password')
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
print(validated_data)
password = validated_data.pop('password')
print(password)
user = User.objects.create_user(
validated_data['user'],
)
user.set_password(password)
user.save()
return user
If you remove the line:
extra_kwargs = {'password': {'write_only': True}}
It will also show you the hashed user password. Thanks at all for your good ideas