Home>

The question is only about working in the Django admin panel:

There are 2 models Departments (departments) and Employees (employees)

class Departments(models.Model):
    title= models.CharField()
class Employees(models.Model):
    name= models.CharField()
    fk_departments= models.ForeignKey(Departments)

For example, there are several departments: "Department No. 1" and "Department No. 2", Ivanov works in the first, Petrov works in the second. If you create a user using the Django admin panel and give him all rights to the Employees model (employees), then by default the user will see the full list of employees from all departments:

  1. name: "Ivanov", department: "Department No. 1"
  2. name: "Petrov", department: "Department No. 2"

Is it possible to change the user's permissions at the department level in the Django admin panel? (i.e. different users should only see employees from certain departments).

For example, in the list of employees, User #1 will only see "Ivanov" from "Department #1"

  • Answer # 1

    Possibly a hacky solution, but I solved the problem by adding the following in the application's admin.py module:

    class EmployeesAdmin(admin.ModelAdmin):
        .... lists of display fields....
        def get_queryset(self, request):
            qs= super(EmployeesAdmin, self).get_queryset(request)
            # If the current user is a superuser, return everything:
            if request.user.is_superuser:
                return qs
            # If the current user belongs to the "Department No. 1" group, return Employees only from "Department No. 1":
            if request.user.groups.filter(name='Department #1').exists():
                return qs.filter(fk_departments=1)
            # If the current user belongs to the "Department No. 2" group, return Employees only from "Department No. 2":
            if request.user.groups.filter(name='Department #2').exists():
                return qs.filter(fk_departments=1)
    
  • Answer # 2

    Possibly a hacky solution, but I solved the problem by adding the following in the application's admin.py module:

    class EmployeesAdmin(admin.ModelAdmin):
        .... lists of display fields....
        def get_queryset(self, request):
            qs= super(EmployeesAdmin, self).get_queryset(request)
            # If the current user is a superuser, return everything:
            if request.user.is_superuser:
                return qs
            # If the current user belongs to the "Department No. 1" group, return Employees only from "Department No. 1":
            if request.user.groups.filter(name='Department #1').exists():
                return qs.filter(fk_departments=1)
            # If the current user belongs to the "Department No. 2" group, return Employees only from "Department No. 2":
            if request.user.groups.filter(name='Department #2').exists():
                return qs.filter(fk_departments=1)