我正在扩展用户模型-

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    company = models.ForeignKey(Company, null=True)
    is_admin = models.BooleanField(default=False)
    last_modified = models.DateTimeField(blank=True, null=True)
    uuid = models.CharField(max_length=256)


使用Django Rest Framework,我有以下序列化器-

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)


尝试使用以下视图创建新用户时-

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):
        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': str(uuid.uuid4())}
        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)


我在回溯中遇到以下错误-

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
  36.             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


如何获得我的视图以正确地为User和UserProfile模型写入值?

最佳答案

问题是当您将uuid作为参数传递给create_user()函数时。

您使用的默认User模型中没有uuid字段。 create_user()函数接受在User模型中定义的字段作为参数。因此,您无需传递uuid参数。

create_user()签名:


  create_user(用户名,电子邮件=无,密码=无,** extra_fields)
  extra_fields关键字参数将传递给用户的
  __init__方法允许在自定义用户模型上设置任意字段。


def create(self, attrs, instance=None):
    ...
    # Remove the `uuid` argument from `create_user()` call.
    user = User.objects.create_user(username=attrs.get('username'),
                                email= attrs.get('email'),
                                password=attrs.get('password'))
    user_profile = UserProfile.objects.create(user=user, **attrs) # create user profile object
    ...

关于python - 'uuid'是此函数的无效关键字参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33320443/

10-11 06:34
查看更多