Django REST Framework UserSerializer中的keyerror

时间:2016-04-15 17:07:00

标签: django django-rest-framework

我正在尝试为新用户的create API处理程序添加一些功能。我有一个关联的UserProfile表,我想添加新创建的用户,添加一个URL参数的值。

POST api调用如下所示:

.../api/users/?username=fred&email=me@me.com&password=1234&data=whatever

标准Django用户表的序列化程序是:

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

    def create(self, validated_data):
        the_user = User.objects.create(
            username=validated_data['username'],
            email=validated_data['email']
        )

        the_user.set_password(validated_data['password'])
        the_user.save()

        # Create associated user profile
        user_profile = UserProfile.objects.create(
            data=validated_data['data'],
            user=the_user.id
        )
        user_profile.save()

        return the_user

用户资料的视图是:

class UserViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = User.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer

我的新UserProfile表模型是:

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

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    data = models.CharField(max_length=100)

我还没有为UserProfile创建一个视图或序列化程序,因为我想要做的就是在创建新用户时添加一行并将其放入POST URL中传递的data参数的值。 / p>

Django在创建新用户时报告以下错误:

KeyError: 'data'

1 个答案:

答案 0 :(得分:3)

# Create associated user profile
user_profile = UserProfile.objects.create(
    data=validated_data['data'],
    user=the_user.id
)

validated_datadata中没有UserSerializer.create个密钥。它只包含您在序列化程序的Meta.fields中定义的键

    fields = ('id', 'username', 'password', 'email')