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.