4

Is there a way to limit access to url pattern only for certain group of django users? for example, everything that starts with /settings/ shuld be accessible only for the administration group.

or maybe it is possible to create a new decorator such as @group("administration") and add it to each view that is limited to the group?

personally I prefer the second way, if possible.

user2216190
  • 784
  • 5
  • 10
  • 25

2 Answers2

5

django provides a user_passes_test decorator to do exactly this. You can pass it any function and if the function returns a false value, the view is not shown.

The example explains it better:

from django.contrib.auth.decorators import user_passes_test

def email_check(user):
    return '@example.com' in user.email

@user_passes_test(email_check)
def my_view(request):
    ...

In your case, you want to see if the user is in a particular group:

def in_admin_group(user):
   return 'administration' in user.groups
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
1

You probably want to either

or

rje
  • 6,388
  • 1
  • 21
  • 40