Search code examples
djangodjango-rest-frameworkdjango-users

how to add django groups to a request user dynamically


I have a model called Employee which has a foreign key field to employee category(like teacher,non-teaching or librarian). I have two groups called 'Library Management' and 'Teacher Management'.

This is my code for Employee model

class EmployeeAdmission(User):

    User.username = models.CharField(max_length=50)
    User.password = models.CharField(max_length=50)

    employee_number =models.CharField(max_length=10)
    joining_date = models.DateField()
    employee_first_name = models.CharField(max_length=20)
    employee_middle_name = models.CharField(max_length=20,blank=True)
    employee_last_name = models.CharField(max_length=20,blank=True)
    employee_email = models.EmailField(max_length=254)
    gender = models.CharField(choices=GENDER,max_length=20)
    date_of_birth = models.DateField()
    employee_category = models.ForeignKey(AddEmployeeCategory,on_delete=models.CASCADE,related_name='employee')
    job_title = models.CharField(max_length=35)
    qualification = models.CharField(max_length=30)
    Experience_info = models.TextField(max_length=200)
    total_experience = models.CharField(max_length=20,choices=YEAR)

I made some employee category like teacher and librarian

My logic is based on the category at the time of post request. say if employee_category is 1. then check for Library Management group and add the group to the request user or if employee_category is 2 then check for Library Management group and add the group to the request user.

this is my code for employee.views.py

@csrf_exempt
def post(self, request, format=None):
    json = JSONRenderer().render(request.data)
    stream = BytesIO(json)
    data = JSONParser().parse(stream)
    serializer = EmployeeDetailSerializer(data=data)
    if serializer.is_valid():

        category = serializer.fields.get('employee_category',default=None)

        if (category == 1 ):
            library_group = Group.objects.get(name='Library Management')
            request.user.groups.add(library_group)
            request.user.save()

        else :
            teacher_group = Group.objects.get(name='Teacher Management')
            request.user.groups.add(teacher_group)
            request.user.save()

        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

I have refered these links here . I am able to save the user but i am still not able to add the groups to the user (Not reflecting on the User model).

Anyone who knows the solution please help. Thank you in advance.


Solution

  • I have found the answer after a lot of research.

    When i was using this code.

    request.user.groups.add(library_group)
    request.user.save()
    

    the group was getting saved only on the user which has admin not the instance of the "EmployeeAdmission". So to get the instance of the "EmployeeAdmission" I did it like this.

    employee = serializer.save()
    

    after getting the instance of the that model i was able to save it. and it was reflecting in the database.

    The code i used was this

    employee.groups.add(library_group)
    employee.save()