Django Rest Framework - Serializer没有填充额外的字段

时间:2015-10-23 03:19:02

标签: django django-rest-framework

我得到以下追溯 -

Traceback:
File "/opt/enterpass_app/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/opt/enterpass_app/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view
  58.         return view_func(*args, **kwargs)
File "/opt/enterpass_app/lib/python2.7/site-packages/django/views/generic/base.py" in view
  71.             return self.dispatch(request, *args, **kwargs)
File "/opt/enterpass_app/lib/python2.7/site-packages/rest_framework/views.py" in dispatch
  466.             response = self.handle_exception(exc)
File "/opt/enterpass_app/lib/python2.7/site-packages/rest_framework/views.py" in dispatch
  463.             response = handler(request, *args, **kwargs)
File "/opt/enterpass/core/views.py" in post
  35.             serializer.save()
File "/opt/enterpass_app/lib/python2.7/site-packages/rest_framework/serializers.py" in save
  180.             self.instance = self.create(validated_data)
File "/opt/enterpass/core/serializers.py" in create
  50.                                         uuid=attrs.get('userprofile.uuid'))
File "/opt/enterpass_app/lib/python2.7/site-packages/django/contrib/auth/models.py" in create_user
  187.                                  **extra_fields)
File "/opt/enterpass_app/lib/python2.7/site-packages/django/contrib/auth/models.py" in _create_user
  180.                           date_joined=now, **extra_fields)
File "/opt/enterpass_app/lib/python2.7/site-packages/django/db/models/base.py" in __init__
  480.                 raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])

Exception Type: TypeError at /api/users/
Exception Value: 'uuid' is an invalid keyword argument for this function

我的观点是填充数据。我可以通过打印功能看到它 -

class UserViewSet(APIView):
    """
    List all companies, or create a new company.
    """
    def get(self, request, format=None):
        userlist = User.objects.all()
        serializer = UserSerializer(userlist, fields=('username', 'email', 'company', 'last_modified'), many=True)
        return Response(serializer.data)

    def post(self, request, format=None):
        uuid = generate_uuid()
        data = {'username': request.data.get('username'),
                'first_name': request.data.get('first_name'),
                'last_name': request.data.get('last_name'),
                'email': request.data.get('email'),
                'uuid': generate_uuid()}
        serializer = UserSerializer(data=data)
        if serializer.is_valid():
            print serializer.data
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

但是当传入我的序列化程序时,该值显示为None -

class UserSerializer(DynamicFieldsModelSerializer):
    company = serializers.CharField(source='userprofile.company', required=False, allow_null=True)
    is_admin = serializers.CharField(source='userprofile.is_admin', required=False, allow_null=True)
    last_modified = serializers.DateTimeField(source='userprofile.last_modified', required=False, allow_null=True)
    uuid = serializers.CharField(source='userprofile.uuid')

    class Meta:
        model = User
        fields = ('username', 'first_name', 'last_name', 'email', 'company', 'is_admin', 'last_modified', 'uuid')

    def create(self, attrs, instance=None):
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            instance.email = attrs.get('user.email', instance.user.email)
            instance.password = attrs.get('user.password', instance.user.password)
            return instance

        user = User.objects.create_user(username=attrs.get('username'),
                                        email= attrs.get('email'),
                                        password=attrs.get('password'),
                                        uuid=attrs.get('userprofile.uuid'))
        return AppUser(user=user)

具体而言,我在与extra_fields

相关时看到了这一点
extra_fields    {'uuid': None}

1 个答案:

答案 0 :(得分:1)

在序列化程序中 - > User.objects.create_user()替换:

uuid=attrs.get('userprofile.uuid') 

uuid=attrs.get('uuid')