0

Hej!

I'm looking for a possibility to add entries by different users and groups. In my app there are different users and different groups where one user can belong to multiple groups. The goal is that some of the groups have sensitive data so I only want members of this group to be able to read the entries but some data should be available in multiple groups. It should also be possible to only see some information. (e.g. See the name but not the address)

For now I have the decorator @login_required for all my views and @permission_required for a persons_view. Therefore you have to be a registered user to see anything, which is great but not quite enough. I also created groups (via the admin area) but can't filter the data for each model/view. The group either sees the data or they don't.

The registration of users is connceted to an already existing ldap system (where those groups are pre-defined. Would be great to use those!)

Is there a possibility to add entries only for a special group and view only some of the given information?

Thanks for the help!

piah
  • 95
  • 1
  • 12

2 Answers2

1

If you want to restrict or specify a view for a group, you should use two mixins: UserPassesTestMixin and LoginRequiredMixin.

  1. LoginRequiredMixin will just make sure the user in the request is logged in
  2. UserPassesTestMixin will check the request from a boolean expression we define and if it returns True it will let the user in

We can set this up using a test_func method that will return either True or False Here is an example that you can use in your view

from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin

class Index(LoginRequiredMixin, UserPassesTestMixin,View):
def get(self, request):
    return render(request, 'nioulboy/index.html')

def test_func(self):
    return self.request.user.groups.filter(name='Admin')

In the test_func method, we are returning true if the request.user has a group with the name Admin.
If it returns True, it will allow the user to view the index page if it returns False it will send back a 403 error.

  • Hej! thanks for the solution. @Mahmadou I do not work with classbased views, therefore it does not work for me, but I found a solution with the passes_test :) Do you know how I could give permission to a part of a view? I get a result table and I don't want to show names and contact details, but the institution and an comment. Do you know if this is possible? – piah Sep 06 '21 at 08:11
0

for NOT class based views works this function to give permission to a whole view.

# views.py

from django.contrib.auth.decorators import login_required, user_passes_test

def user_check(user):
    return user.groups.filter(name="Admin")

@user_passes_test(user_check)
@login_required
def view(request):
    ....

piah
  • 95
  • 1
  • 12