6👍
✅
The mistake is in the line
user = User.objects.filter(user=serializer.instance)
Firstly, there is no field named user
on your User
model. Secondly, you don’t need to filter on the User
model to get the created user as you already have the user with you in serializer.instance
. So, there is no need for that line.
If you just want the id
, you can get that using serializer.instance.id
.
1👍
A neater solution is to depend on super()
‘s implementation:
def create(self, request, *args, **kwargs):
response = super().create(request, *args, **kwargs)
token, created = Token.objects.get_or_create(user_id=response.data["id"])
response.data["token"] = str(token)
return response
And ensure "id"
is included in your Serializer’s fields:
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ["id", ...
Source:stackexchange.com