Skip to main content
 首页 » 编程设计

python之“uuid”是此函数的无效关键字参数

2024年10月24日35bluestorm

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

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