Django rest framework one to one relation Create serializer
<p>I'm a beginner to the Django Rest Frame work. I want to create a custom user but  I have a problem from a long period i try to find a solution through many forums but unfortunately i didn't succeed. hope you help me </p>

<p>models.py</p>

<pre><code>class Account(models.Model):

    user=models.OneToOneField(User,on_delete=models.CASCADE)
    image=models.ImageField(upload_to='Images/',default='Images/user.png')
    date=models.DateField(auto_now=True,auto_now_add=False)
</code></pre>

<p>Serializers.py</p>

<pre><code> class AccountCreateUpdateSerializer(serializers.ModelSerializer):


    user=UserListSerializers()
    image=serializers.ImageField()

    class Meta:
      model= Account
      fields=['id','user','image']
    def create(self,validated_data):
       user_data=validated_data.pop('user')
       account=Account.objects.create(**validated_data)
       User.objects.create(account=account,**user_data)

       return account
</code></pre>

<p>the error :
<a href="http://i.stack.imgur.com/Rgovf.png" rel="nofollow">enter image description here</a></p>

<p>Your problem is here:</p>

<pre><code>   user_data = validated_data.pop('user')
   account = Account.objects.create(**validated_data)
   User.objects.create(account=account, **user_data)
</code></pre>

<p>You're trying to create an Account before creating a User, which won't work because an Account requires a value for <code>user_id</code>. If your User model had a foreign key to Account, instead of the other way around, then creating the account first would be the right way to do it.</p>

<p>Switching to:</p>

<pre><code>   user_data = validated_data.pop('user')
   user = User.objects.create(**user_data)
   account = Account.objects.create(user=user, **validated_data)
</code></pre>

<p>should fix the problem as long as your <code>UserListSerializers()</code> is providing the correct data to create a User instance.</p>

<p>Hope that helps.</p>

python django rest django-rest-framework