Reputation: 6723
I try to register user and return token and user id. Doing it like this
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.authtoken.models import Token
from rest_framework import status
from django.contrib.auth import get_user_model
User = get_user_model()
class CreateUser(CreateAPIView):
queryset = Profile.objects.all()
serializer_class = UserSerializer
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
token, created = Token.objects.get_or_create(user=serializer.instance)
user = User.objects.filter(user=serializer.instance)
return Response({'token': token.key, 'id':user.id}, status=status.HTTP_201_CREATED, headers=headers)
And I get an error
Cannot resolve keyword "user" into field. Choices are: auth_token, date_joined, email, first_name, groups, id, is_active, is_staff, is_superuser, last_login, last_name, logentry, password, user_permissions, username
What am I doing wrong ?
Upvotes: 11
Views: 5478
Reputation: 400
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", ...
Upvotes: 1
Reputation: 47856
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
.
Upvotes: 6