我试图通过django rest框架用他的个人资料创建一个用户注册端点,它告诉我我没有为我的序列化器创建一个明确的.create()方法。我错过了什么?
这是我的models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, blank=True, null=True)
language = models.CharField(max_length=4, default='es')
def __unicode__(self):
return "%s - %s" % (self.user, self.language)
我的serializers.py
class ProfileCreateSerializer(serializers.ModelSerializer):
class Meta:
model = Profile
fields = [
'language',
]
class UserSerializer(serializers.ModelSerializer):
profile = ProfileCreateSerializer()
class Meta:
model = User
fields = [
'username',
'profile',
]
def create (self, validated_data):
user = User.objects.create(username=validated_data['username'])
user.set_password(User.objects.make_random_password())
profile_data = validated_data.pop('profile')
Profile.objects.create(user=user, **profile_data)
user.save()
我的views.py
class ProfileCreateAPIView(CreateAPIView):
queryset = User.objects.all()
model = Profile
serializer_class = UserSerializer
答案 0 :(得分:0)
您的代码看起来没问题,但您的缩进看起来不对:.create()
方法需要是序列化程序的方法,因此它应缩进到与class Meta:
语句相同的级别。
它应该看起来像这样(注意create()
方法上的缩进):
class UserSerializer(serializers.ModelSerializer):
profile = ProfileCreateSerializer()
class Meta:
model = User
fields = [ 'username', 'profile', ]
def create (self, validated_data):
user = User.objects.create(username=validated_data['username'])
user.set_password(User.objects.make_random_password())
profile_data = validated_data.pop('profile')
Profile.objects.create(user=user, **profile_data)
user.save()
DRF Docs (Saving Instances)的更多示例,如果有帮助的话。