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.
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.