Skip to content

Instantly share code, notes, and snippets.

@bradmontgomery
Last active March 8, 2019 02:31
Show Gist options
  • Save bradmontgomery/5657267 to your computer and use it in GitHub Desktop.
Save bradmontgomery/5657267 to your computer and use it in GitHub Desktop.
def not_in_student_group(user):
"""Use with a ``user_passes_test`` decorator to restrict access to
authenticated users who are not in the "Student" group."""
return user.is_authenticated() and not user.groups.filter(name='Student').exists()
# Use the above with:
@user_passes_test(not_in_student_group, login_url='/elsewhere/')
def some_view(request):
# ...
# Another, less verbose, option:
def not_student(function=None):
actual_decorator = user_passes_test(
lambda u: u.is_authenticated() and not user.groups.filter(name='Student').exists()
)
return actual_decorator(function)
# Use the above with:
@not_student
def some_view(request):
# ...
@rom1dep
Copy link

rom1dep commented Oct 24, 2015

    […]
    return user.is_authenticated() and 'Student' not in user.groups.iterator()

is probably more pythonic©

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment