I'm working on a Django project where I'm trying to create an auth token for a newly registered user using Django Rest Framework. However, when running the register function, I run into the following error:
ValueError: Cannot assign "<User: Test>": "Token.user" must be a "User" instance.
Here is the register function where the error occurs:
@api_view(['POST'])
def register(request):
serializer = UserSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
user = User.objects.get(username=request.data['username'])
user.hash_password(request.data['password'])
user.save()
token = Token.objects.create(user=user) # This is where the error occurs
return Response({
'token': token.key,
'User': serializer.data
}, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
How can I fix this error and successfully create the authentication token for the newly registered user?
I have tried to register a new user using the register function in my Django Rest Framework view. I was expecting the user to register successfully (register in the database) and for an auth token to be generated associated with that user.
The
ValueError: Cannot assign "<User: Test>": "Token.user" must be a "User" instance.error usually means that the "user" object is not an instance of the model that Token.user field expects.Your code seems correct, after
serializer.save(), the return value is an instance of User model. However,hash_passwordin lineuser.hash_password(request.data['password'])is not a standard Django method for User model. Please ensure this method exists in your User model and returns a User instance, not a string or something else. Also, this method probably does the same job asset_passwordwhich is already part of the Django User model.