Check User Permission in Views

A snippet showing how to verify user permissions inside Django views.


# views.py

from django.http import HttpResponseForbidden
from django.shortcuts import render

def manage_users_view(request):
    if not request.user.has_perm('auth.view_user'):
        return HttpResponseForbidden("You do not have permission to view this page.")
    return render(request, 'manage_users.html')
  

# templates/manage_users.html

<h2>Manage Users</h2>
<p>You have permission to view this page.</p>
  
Explanation:
  • user.has_perm() is used to check if the logged-in user has a specific permission.
  • In this example, we check for the permission auth.view_user which controls user view access.
  • If the user lacks permission, a 403 Forbidden response is returned with a message.
  • This approach is useful for fine-grained access control inside your views.
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.