I am using Django 2.0 . I have created user groups now I want to restrict views using User Groups. Which is the best way to solve this problem ?

2 Answers

0
Alpaslan Aykovan On
from django.contrib.auth.decorators import login_required, permission_required    
@method_decorator([
login_required,
permission_required('staff.tools_can_access', reverse_lazy('staff:login'), True)], name='dispatch')
class ToolsView(FormView):
    pass

first assign permissions to groups that you made and then change the permission_required args.

it's will be perfect to use generic views

0
Tajinder Singh On

If you want that only users that belongs to a specific group can access the view then you can use UserPassesTextMixin. In the example below, a certain user can access to the view only if he belongs to the YourGroupName group (I named it in this way because I don't know how you have named it by yourself)

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

class ToolsView(LoginRequiredMixin, UserPassesTestMixin, FormView):
    # ...

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

In the case you want to use function based view instead of class based then you can do this:

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

@login_required
@user_passes_test(lambda u: u.groups.filter(name='YourGroupName').exists())
def my_view(request, pk):
    # ....