I\'m using django-rest-framework-simplejwt and was wondering if it\'s possible to return a token after registering a user?
This post has a solution for another jwt packa
I just solved my own question. Let me know if you have any comments. Thanks!
class RegisterUserSerializer(serializers.ModelSerializer):
"""Serializer for creating user objects."""
tokens = serializers.SerializerMethodField()
class Meta:
model = models.User
fields = ('id', 'password', 'email', 'tokens')
extra_kwargs = {'password': {'write_only': True}}
def get_tokens(self, user):
tokens = RefreshToken.for_user(user)
refresh = text_type(tokens)
access = text_type(tokens.access_token)
data = {
"refresh": refresh,
"access": access
}
return data
def create(self, validated_data):
user = models.User(
email=validated_data['email']
)
user.set_password(validated_data['password'])
user.save()
return user
views.py
class UserListView(generics.ListCreateAPIView):
"""Handles creating and listing Users."""
queryset = User.objects.all()
def create(self, request, *args, **kwargs):
serializer = RegisterUserSerializer(data=request.data)
if serializer.is_valid():
self.perform_create(serializer)
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)