我試圖做一個登錄應用程序,包括註冊,認證等.. 我得到這個錯誤: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()
工作就像一個魅力。謝謝。 – Addict