0

I'm trying to add a custom create method, and am using the Django REST FRAMEWORK. Once a user is created, I want to create an auth token and then return a JSON response with this user AND an auth token.

UPDATE: I was able to update the below to create the user, but now I am getting Cannot assign "<User: User object>": "Token.user" must be a "User" instance What am i doing wrong?

How can I modify the below so when POST to users/, I create a user, create an auth token, and return both?

class UserSerializer(serializers.ModelSerializer):
    class Meta:
      model = User
      fields = ('first_name', 'last_name', 'email', 's3_link', 'phone_confirmed', 'agreed_to_tos', 'phone_number', 'facebook_id', 'stripe_id', 'phone_verification_code')

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

    ##ISSUE WITH CODE STARTS HERE
    user = serializer.save()
    token = Token.objects.create(user=user)
DaynaJuliana
  • 1,144
  • 1
  • 14
  • 33

2 Answers2

1

You could use a custom Response to add the token to the user data:

class UserSerializer(serializers.ModelSerializer):
    class Meta:
      model = User
      fields = ('first_name', 'last_name', 'email', 's3_link', 'phone_confirmed', 'agreed_to_tos', 'phone_number', 'facebook_id', 'stripe_id', 'phone_verification_code')

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

    # Customized rest_framework.mixins.CreateModelMixin.create():
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        # Your code
        user = serializer.save()
        token = Token.objects.create(user=user)

        # Create custom response
        data = serializer.data
        # You may need to serialize your token:
        # token = token.your_token_string_field
        data.update({'token': token})
        headers = self.get_success_headers(serializer.data)
        return Response(data, status=status.HTTP_201_CREATED, headers=headers)
spiegelm
  • 65
  • 7
  • This looks more promising. Will this also satifiy the ValueError when trying to create the Token `token = Token.objects.create(user=user)` (see my other updated question): http://stackoverflow.com/questions/33683511/django-auth-token-valueerror-when-assigning-to-user – DaynaJuliana Nov 13 '15 at 00:46
  • 1
    I guess the problem in the other question is that there are two different User classes and that the Token class requires a specific one. Probably the User model from Django auth. I posted an answer, please verify. – spiegelm Nov 13 '15 at 01:11
0

If you want to create a user, I would recommend following this format:

serializers.py:

class AccountCreateSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        # You will need to check accuracy of fields, but this is for demo purposes
        fields = ['username', 'email', 'password']
        extra_kwargs = {'password': {'write_only': True}}

    def create(self, validated_data):
        user = User(
            username=validated_data['username'],
            email=validated_data['email']
        )
        user.set_password(validated_data['password'])
        user.save()
        return user

views.py:

from rest_framework import generics
from serializers.py import AccountCreateSerializer

class AccountCreateAPIView(generics.CreateAPIView):
    serializer_class = AccountCreateSerializer
jape
  • 2,861
  • 2
  • 26
  • 58
  • I'm not using an email or password. They are signing up via phone which I will verify by sending a text. I just want to return a Token upon the create method – DaynaJuliana Nov 12 '15 at 22:55