2017-07-13 82 views
0

我試圖做一個登錄應用程序,包括註冊,認證等.. 我得到這個錯誤:OneToOne關係和NestedSerializer問題有關用戶模型

AttributeError: Got AttributeError when attempting to get a value for field 'user' on serializer 'PictureUserSerializer'. The serializer field might be named incorrectly and not match any attribute or key on the 'User' instance. Original exception text was: 'User' object has no attribute 'user'.

但是,當我檢查我的管理頁面。用戶已經註冊了正確的信息。我不覺得這個錯誤來自任何地方,我必須做一些錯誤的事情。這裏是我的代碼:

logginapp/models.py

from django.db import models 
from django.contrib.auth.models import User 

class PictureUser(models.Model): 
    user = models.OneToOneField(User) #OneToOne link to the Django's User Model    
    avatar = models.ImageField(null=True, blank=True, upload_to="avatars/") 

    def username(self, user): 
     return user.username 

    def password(self, user): 
     return user.password 

    def email(self, user): 
     return user.email 

loginapp/serializer.py

from django.core.validators import validate_email 
from django import forms 
from rest_framework import serializers 
from loginapp.models import PictureUser 

class UserSerializer(serializers.ModelSerializer): 
    class Meta: 
     model = User 
     fields = ('username', 'password', 'email') 
     write_only_fields = ('password',) 


class PictureUserSerializer(serializers.ModelSerializer): 
    """                      
    Serializer to put the PictureUser model into JSON           
    """ 
    user = UserSerializer() 

    class Meta: 
     model = PictureUser 
     fields = ('user', 'avatar') 
     read_only_fields = ('created',) 

    def create(self, validated_data): 
     print (validated_data) 
     return User.objects.create_user(validated_data['user']['username'], validated_data['user']['email'], 
      validated_data['user']['password'] 
    ) 

loginapp/view.py

from django.shortcuts import render 
from rest_framework import generics 
from .serializer import PictureUserSerializer 
from .models import PictureUser 

class PictureUserCreateView(generics.ListCreateAPIView): 
    """                      
    This class define the Create behaviour of a PictureUser         
    """ 
    queryset = PictureUser.objects.all() 
    serializer_class = PictureUserSerializer 

    def perform_create(self, serializer): 
     serializer.save() 

回答

2

如果您需要從PictureUserSerializer創建用戶,那麼,

def create(self, validated_data): 
    user_data = validated_data.pop('user') 
    user = User.objects.create_user(**user_data) 
    return PictureUser.objects.create(user = user, **validated_data) 
+0

工作就像一個魅力。謝謝。 – Addict

0

PictureUserSerializer create method需要返回一個PictureUser實例,而不是User實例。