我想将登录用户的 user_company 的值分配给新创建用户的 user_company 字段

I want to assign value of logged in user's user_company to the user_company field of the newly created user

当用户为客户端创建用户记录时,新客户端应具有当前登录用户的 User.user_company 值。

这里的问题,我想在视图中调用save()时,将登录用户的User.user_company的值赋给新用户的clientuser.user_company

下面是带有 clientuser 对象的序列化程序。


class ClientSerializers(serializers.ModelSerializer):

    password2 = serializers.CharField(style={'input_type': 'password'}, write_only=True)
    client_name = serializers.CharField(style={'input_type' : 'text'}, required=True)


    class Meta:
        model = User
        fields = ['email', 'username', 'password', 'password2', 'user_type', 'client_name'] 
        extra_kwargs = {
                'password': {'write_only': True}, #dont want anyone to see the password
                'user_type': {'read_only': True},
        }

    
    def save(self):
        clientuser = User(
                    #creating a user record. it will record company fk
                    email=self.validated_data['email'],
                    username=self.validated_data['username'],
                    user_type = 3,
                    first_name = self.validated_data['client_name'])

        
        #validating the password
        password = self.validated_data['password']
        password2 = self.validated_data['password2']
        if password != password2:   #trying to match passwords.
            raise serializers.ValidationError({'password': 'Passwords must match.'})
        
        clientuser.set_password(password) #setting the password
        clientuser.save() #saving the user
        return clientuser 

我试过使用

cur_usr = User()
param = 'user_company'
usr_comp = getattr(u, param)
print(f'usr_comp is {usr_comp})

print 语句在终端中打印 usr_comp is None

我也试过使用

curr_User_Company = User.user_company
user.user_company = curr_User_Company 

它returns终端中的以下行

raise ValueError(
ValueError: Cannot assign "<django.db.models.fields.related_descriptors.ForwardManyToOneDescriptor object at 0x04B05F28>": "User.user_company" must be a "Company" instance.

这是我的用户模型

class User(AbstractUser):
    email = models.EmailField(verbose_name="email", max_length=60, unique=True)
    user_type_data = ((1,"sysAdmin"),(2,"CompanyAdmin"), (3,"Client"), (4,"Employee"))
    user_type = models.IntegerField(choices=user_type_data, default=2)
    user_company = models.ForeignKey('Company', on_delete=models.CASCADE, null=True, blank=True)
    #if user is CompAdmin then company is the company he belongs to
    #if user is Client then company is the company he is serviced by
    #if user is Employee then company is the company he works for
    #if user is sysAdmin then company is null

这是我的看法

@csrf_exempt
@permission_classes([IsAuthenticated])
def ClientApi(request):
    if request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = ClientSerializers(data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, status=201)
        return JsonResponse(serializer.errors, status=400)

我不确定这是否有必要,但如果有必要,这里是我尝试通过 Postman 传递的数据示例

{
        "email":"Maximillian@amgracing.com", 
        "username":"Maximillian", 
        "password":"AmgRacingBetterThanRedBull", 
        "password2":"AmgRacingBetterThanRedBull", 
        "client_name" : "MaximillianRacing" 
    }

也许你应该使用这个:

from django.contrib.auth import get_user

还有这个:

 clientuser = User(
      #creating a user record. it will record company fk
      email=self.validated_data['email'],
      username=self.validated_data['username'],
      ///

      user_company = get_user(self.request).user_company /// this line get you user_company from logged user

终于想通了。我将 current_user 参数添加到 save() 函数并将 user_company 分配给 current_user.user_company

的值
    def save(self, current_user):
        usr_comp = current_user.user_company
        clientUser = User(///
                          user_company = usr_comp)

ClientApi 视图中,这是我所做的

serializer.save(current_user = request.user)