1

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.

Community
  • 1
  • 1
Arnold Laishram
  • 1,801
  • 2
  • 18
  • 25
  • I am using the exact same code since over a year and it does work. Check on debugger what is happening before and after the add and the save – Daniele Bernardini Mar 06 '16 at 20:54
  • Anyway you might consider using a trigger at the model level instead then updating it at every request. We are using something similar with a m2m relation named role and we are using a function to update the users whenever users or roles are updated: `m2m_changed.connect(update_groups, sender=MISUser.role.through)` `@receiver(m2m_changed, sender=Role.groups.through)` `def update_all_users(sender, **kwargs):` – Daniele Bernardini Mar 06 '16 at 20:57
  • I have tried debugging. When i give the employee_category value to 2. it comes to the Tescher Management group condition check. and the request.user.save() is also getting called. But still doesnt effect. – Arnold Laishram Mar 07 '16 at 05:34
  • did you print request.user.groups at each step? what are their value? Right after the save() put a breakpoint and check the database directly. Is the new group there? Are groups changed in any other part of your application? (search for user.groups in your code) – Daniele Bernardini Mar 07 '16 at 10:02

1 Answers1

0

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()
Arnold Laishram
  • 1,801
  • 2
  • 18
  • 25