python - “uuid”是该函数的无效关键字参数

标签 python django django-rest-framework

我正在扩展我的用户模型 -

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)

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

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

如何让我的 View 正确写入 User 和 UserProfile 模型的值?

最佳答案

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

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

create_user() 签名:

create_user(username, email=None, password=None, **extra_fields)
The extra_fields keyword arguments are passed through to the User’s __init__ method to allow setting arbitrary fields on a custom User model.

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/

相关文章:

python - 计算 Pandas Dataframe 中两个日期之间的 GroupBy 内的行数

python - 我可以使用 bazaar 提交一个大文件,还是有更好的方法来对数据库转储进行版本控制?

python - Django : An established connection was aborted by the software in your host machine

django-rest-auth 自定义注册无法保存额外的字段

python - 从包含多行的 pandas Dataframe 更新 BigQuery 表的最佳方法是什么

python - 读取 HTML 文件并将其显示在 Tkinter 窗口中

django - 使用 post_save 信号处理程序访问新创建的模型实例的相关数据

python - 无法使用反向名称解析路径的 URL 字符串

Django Rest 创建后删除密码

django - Django REST框架请求数据