About Django Views with Failing Authorization
401 Unauthorized
If an unknown visitor tries to access a protected view, return a view with status code "401 Unauthorized".
Use a response with a custom template and status 401:
from django.shortcuts import render
def protected_view(request):
if not request.user.is_authenticated:
return render(request, "401.html", {}, status=401)
...
Alternatively, redirect to the login page:
from django.contrib.auth.decorators import login_required
@login_required
def protected_view(request):
...
403 Forbidden
If a known user tries to access a protected view where they have no permission to do so, return a view with a status code "403 Forbidden".
Return a response with status 403 by raising an error:
from django.core.exceptions import PermissionDenied
def protected_view(request):
if not request.user.has_perm("posts.view_post"):
raise PermissionDenied()
...
Or use a response with custom template and status 403:
from django.shortcuts import render
def protected_view(request):
if not request.user.has_perm("posts.view_post"):
return render(request, "403.html", {}, status=403)
...
Tips and Tricks Programming Security Django 5.x Django 4.2 Django 3.2 HTTP
Also by me
Django Paddle Subscriptions app
For Django-based SaaS projects.
Django GDPR Cookie Consent app
For Django websites that use cookies.