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

When a user creates a user record for a client, the new client should should have the current logged in user's User.user_company value.

In the problem here, I want to assign the value of the logged in user's User.user_company into the new user's clientuser.user_company when save() is called in the view.

here is the serializer below with the clientuser object.


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 

I've tried using

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

print statement prints usr_comp is None in the terminal

I've also tried using

curr_User_Company = User.user_company
user.user_company = curr_User_Company 

it returns the following line in the terminal

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

Here is my user model

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

Here is my view

@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)

I'm not sure if this is necessary, but if it is, here is a sample of the data i tried to pass through Postman

{
        "email":"[email protected]", 
        "username":"Maximillian", 
        "password":"AmgRacingBetterThanRedBull", 
        "password2":"AmgRacingBetterThanRedBull", 
        "client_name" : "MaximillianRacing" 
    }



Solution 1:[1]

Finally figured it out. I added current_user parameter to the save() function and assigned the user_company to the value of current_user.user_company

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

In the ClientApi view, here's what I did

serializer.save(current_user = request.user)

Solution 2:[2]

Maybe you should used this:

from django.contrib.auth import get_user

and this:

 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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 BaseKodu
Solution 2 KamilBaranowskiCZ