[Fixed]-Perform Create Always Fails Django REST Framework

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

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

Leave a comment