Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
291 views
in Technique[技术] by (71.8m points)

python - AssertionError: `create()` did not return an object instance

I am getting the error below while sending a request to a UserRegisterView:

  File "/Users/MichaelAjanaku/Desktop/test/afrocode/lib/python3.6/site-packages/rest_framework/views.py", line 506, in dispatch
    response = handler(request, *args, **kwargs)
  File "/Users/MichaelAjanaku/Desktop/test/leave/views.py", line 22, in post
    serializer.save()
  File "/Users/MichaelAjanaku/Desktop/test/afrocode/lib/python3.6/site-packages/rest_framework/serializers.py", line 207, in save
    '`create()` did not return an object instance.'
AssertionError: `create()` did not return an object instance.

I don't know why such occurs. Here is my views.py:

class UserRegistrationView(CreateAPIView):
    serializer_class = UserRegistrationSerializer
    permission_classes = (AllowAny,)

    def post(self, request):
        serializer = self.serializer_class(data= request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        status_code = status.HTTP_201_CREATED
        response = {
            'success' : 'True',
            'status code' : status_code,
            'message' : 'User registered successfully'
        }

and the serializers:

class UserRegistrationSerializer(serializers.ModelSerializer):

    profile = UserSerializer(required=False)
    class Meta:
        model = User
        fields = ('email', 'password','profile' )
        extra_kwargs = {'password': {'write_only' : True}}

    
    def create(self, validated_data):
        profile_data = validated_data.pop('profile')
        user = User.objects.create_user(**validated_data)
        UserProfile.objects.create(
            user = user,
            first_name = profile_data['first_name'],
            last_name= profile_data['last_name'],
                     )

Please what is causing the error? Thanks

question from:https://stackoverflow.com/questions/65864900/assertionerror-create-did-not-return-an-object-instance

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your create method is not returning an object instance. You should return the result of the User.objects.create(...) call.

def create(self, validated_data):
    profile_data = validated_data.pop('profile')
    user = User.objects.create_user(**validated_data)
    UserProfile.objects.create(
        user = user,
        first_name = profile_data['first_name'],
        last_name= profile_data['last_name'],
                 )
    return user

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...