2

how would i go about creating a user inn the database with a api call? Im using the Model.serializer, ive tried to override the save method and create a user with the request.data but i cant seem to get it to work. Any tips? The error that i get is that when i try to asign the user to the request.data it comes back saying that the value needs to be a user instance. How do i make the requested data a user instance? This is my code.

@api_view(['POST'])
def createUser(request):

    serializer = userSerializer(data=request.data)
    print(request.data['username'])

    if serializer.is_valid():
        serializer.save()

        if request.data['password'] == request.data['password2']:
            userModel = UserModel.objects.create(
                user=request.data,
                username=request.data['username'],
                email=request.data['email'],
                firstname=request.data['firstname'],
                lastname=request.data['lastname'],
                password=request.data['password'],
                password2=request.data['password2']
            )
            userModel.save()
            return Response('User was created')
        else:
            return Response('Passwords must match')
2
  • try user=request.user. Commented Jul 15, 2020 at 19:22
  • What's UserModel? Is it the same as the builtin User model? Also why are you saving userModel again right after creating it? Commented Jul 16, 2020 at 2:50

1 Answer 1

2

Try and use a ModelViewSet like this

class RegisterUser(ModelViewSet):
  serializer_class = userSerializer()
  query_set = UserModel.objects.all()
  
 def perform_create(self, serializer):
    password = self.request.data['password']
    password2 = self.request.data['password2']
    if (password==password2):
       serializer.save()
       return Response('User was created')
   else:
      return Response('Password did not match')

Then call it in your urls as

path("register", views.RegisterUser.as_view()),
Sign up to request clarification or add additional context in comments.

2 Comments

thanks man, that looks clean. Il try that, ive sorted out the problem but i liked this code better :D Cheers
Welcome bro, feel free to let the community know if u come across other issues.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.