Restrict View by Group Membership
A snippet showing how to restrict view access depending on user groups.
# views.py
from django.http import HttpResponseForbidden
from django.shortcuts import render
def staff_dashboard_view(request):
if not request.user.groups.filter(name='Staff').exists():
return HttpResponseForbidden("Access denied: Staff only.")
return render(request, 'staff_dashboard.html')
# templates/staff_dashboard.html
<h2>Staff Dashboard</h2>
<p>Only users in the 'Staff' group can view this.</p>
Explanation:
-
We check if the logged-in user is part of a specific group using
user.groups.filter(name='GroupName').exists(). - If the user isn't in the group, a 403 Forbidden response is returned.
- This method is useful for implementing role-based access control.
- Groups can be created and assigned via the Django admin.
- Category Authentication & Authorization
- Total Views 572
- Last Modified 06 November, 2025
- Tags #groups #authorization #auth #permissions
Previous snippet
Check User Permission in Views
Next snippet