简体   繁体   中英

Django add custom permission

I am facing the problem of adding custom permission in Django. My idea is that when authorizing a user, if it belongs to group1, only the rows of group1 are displayed, and otherwise the rows of group2. There is a group field in the database table, it contains only two values group1 and group2. In the admin panel, I created 2 groups, respectively, and also included users in these groups. Also I created permissions and assigned them to each user.

My models.py

class Employee(models.Model):
   DEPT =(
    ('Group1', 'Group1'),
    ('Group2', 'Group2')
   )

   dept = models.CharField(max_length=100, choices=DEPT, default='')
   fio = models.CharField(max_length = 100)
   work_place = models.CharField(max_length = 150, default= '')

def __str__(self):
    return self.fio

class Meta:
    permissions = (
                   ("view_museum", "can view museum"),
                   ("view_ssoismi", "can view ssoismi"),
                  )

My views.py

def employee_list(request):
   context = {'employee_list': Employee.objects.all()}
   return render(request, "employee_register/employee_list.html", context)

If i change the context row to

context = {'employee_list': Employee.objects.filter(dept="Group1")}

I get the desired result, but how can do it automatically with django groups and etc. Maybe i do something wrong? Any idea what to do next? Thanks

In the admin panel, I created 2 groups, respectively, and also included users in these groups.

Query these group names by filtering request.user.groups with name__in . Then filter Employee.objects by those results with dept__in .

Note that this assumes the admin group names are named exactly like the Employee.dept field. If not, rename the admin groups to match the Employee.dept field (including capitalization, spaces, etc.).

def employee_list(request):
    groups = [g.name for g in request.user.groups.filter(name__in=['Group1', 'Group2')]
    context = {'employee_list': Employee.objects.filter(dept__in=groups)}

    return render(request, 'employee_register/employee_list.html', context)

Try this:

context = {'employee_list': Employee.objects.filter(dept=request.user.group)}

I'm not sure how you made the User belong in one of the groups but I'm guessing you also have a group field on your User model.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM