Python ';uuid';此函数的关键字参数无效
我正在扩展我的用户模型-Python ';uuid';此函数的关键字参数无效,python,django,django-rest-framework,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)
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框架,我有以下序列化程序-
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
如何让视图正确地为用户和用户配置文件模型写入值?问题是当您将
uuid
作为参数传递给函数时
您正在使用的默认User
模型中没有uuid
字段。create\u user()
函数接受在user
模型中定义的字段作为参数。因此,您不需要传递uuid
参数
创建用户()
签名:
创建用户(用户名、电子邮件=None、密码=None、**额外字段)extra_字段
关键字参数传递给用户的
\uuuu init\uuuu
方法,允许在自定义用户模型上设置任意字段
请发布您正在使用的扩展
用户
模型。@RahulGupta它在顶部。我的UserProfile模型有一个OneToOneField to User。在User
模型中定义的uuid
字段在哪里?它是在UserProfile模型中定义的,而不是在用户模型中定义的。保存时,我希望它同时更新用户模型和它链接到的UserProfile模型。接下来的问题是,我是否必须传递一个单独的UserProfile=UserProfile.objects.create(uuid=attrs.get('uuid'))
?即,如何将两个模型创建绑定在一起?您必须在create()中分别创建一个UserProfile
对象
函数使用以前创建的用户
。您也可以在视图中使用ModelViewSet
,因为您在视图中编写的所有代码都是由DRF内部完成的。我发现ModelViewSet
的问题是我不想返回所有字段。我有一个DynamicFieldsModelSerializer
serializer,但在ModelViewSet
中,我像serializer\u class=UserSerializer
一样调用序列化程序,而实际上我需要像serializer=UserSerializer(userlist,fields=('username','email','uuid')那样调用它。
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
...