1

I have 3 connected models: User -> UserProfile -> BuyerProfile, and when a user makes an account, I want a User to be made, then a UserProfile, then a BuyerProfile. I'm using a ModelSerializer, but when I use the browsable api and make a post, I get:

{
    "userprofile": {
        "user": [
            "This field is required."
        ]
    }
}

Any ideas on how to do this?

class BuyerProfileViewSet(viewsets.ModelViewSet):
    queryset = BuyerProfile.objects.all()
    serializer_class = BuyerProfileSerializer

Serializers:

    class UserSerializer(serializers.HyperlinkedModelSerializer):
        class Meta:
            model = User
            fields = ('username',)

class UserProfileSerializer(serializers.HyperlinkedModelSerializer):

    user = UserSerializer()

    class Meta:
        model = UserProfile
        fields = ('user', 'bio','prof_type')

class BuyerProfileSerializer(serializers.HyperlinkedModelSerializer):
    userprofile = UserProfileSerializer()

    class Meta:
        model = BuyerProfile
        fields = ('userprofile', 'company','sitename')
2
  • 1. Please show what data serializer receives. 2. Please add restframework version to question. Commented Apr 22, 2015 at 8:33
  • What do you mean "what the data serializer recieves"? Do you mean a different serializer? I added the version too Commented Apr 22, 2015 at 16:22

1 Answer 1

1

Add parameter required=False into your instantiation of the UserProfileSerializer:

 userprofile = UserProfileSerializer(required=False)
Sign up to request clarification or add additional context in comments.

5 Comments

If I do that, then the user instance is never created and saved in the database. I want to first create the user, then the userprofile, and finally a BuyerProifle
Yeah, required=False just makes the field optional. What JSON post object are you sending?
I'm testing it with the brower api using the html form
Weird, so I submitted as json this time and it looks like the 'user' fields are now included. Any idea why the data would appear so different between the json vs html form representations?
Yeah, I've seen a few issues with the html form. It is doing some guessing , especially for nested fields. If you look at the request using your debugger (Chrome's debugger network tab?) then you can see what is actually getting sent to the server. I'm not sure the html form supports the nested interface.... I simply don't use it for nested work, myself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.