问题
Here are my models :
User - I am using the default User provided by django admin
class UserProfile(models.Model):
user = models.ForeignKey(User,on_delete=CASCADE,related_name='user')
phonenumber=models.IntegerField()
picture=models.CharField(max_length=20,null=True)
#dp=models.ImageField(upload_to='profile_pics',blank=True)
points=models.IntegerField(default=0)
def __str__(self):
return self.user.name
def __repr__(self):
return str(self.user.name)
Here is my View where I am trying to post the data
class UserCreate(generics.CreateAPIView):
queryset=User.objects.all()
serializer_class=None
def get_serializer_class(self, *args, **kwargs):
if(self.request.method=='GET'):
return UserSerializer
return CreateUserSerializer
def post(self,request,format=None):
user=CreateUserSerializer(data=request.data)
if(user.is_valid()):
user.save()
Here is my serializer
class CreateUserSerializer(serializers.ModelSerializer):
email = serializers.EmailField()
username = serializers.CharField(max_length=100)
password = serializers.CharField(max_length=255)
userprofile = UserProfileSerializer(required=True)
class Meta:
fields=('username','password','email','userprofile')
model=models.User
def create(self, validated_data):
"""
Create and return a new `User` instance, given the validated data.
"""
userprofile = validated_data.pop('userprofile')
instance = super(CreateUserSerializer, self).create(validated_data)
instance.save()
return instance
profile=UserProfileSerializer(data=request.data)
if profile.is_valid():
profile.save()
return Response(user.data, status=201)
return Response(user.errors, status=400)
class UserProfileSerializer(serializers.ModelSerializer):
class Meta:
fields=('phonenumber','picture')
model=models.UserProfile
def create(self, validated_data):
profile = super(UserProfileSerializer,self).create(validated_data)
profile.save()
return profile
User gets saved properly. Problem arises with UserProfile only. It says :
Got AttributeError when attempting to get a value for field userprofile
on serializer CreateUserSerializer
.
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 'userprofile'.
I understand that it expects 'userprofile' inside 'user', but I had to remove it inside CreateUserSerializer for the user to get saved properly. What has to be done now? I am a newbie to django.
回答1:
Your related_name
on UserProfile
<-> User
relation doesn't match field in serializer. You have 'user'
set as a related name in ForeignKey
, but you are using userprofile
in your serializer. Change either of those to match the other and problem should be fixed.
来源:https://stackoverflow.com/questions/54964528/unable-to-post-data-with-foreign-key-relationship-django-rest