Last modified: Jan 10, 2023 By Alexander Williams
Django HttpResponseNotAllowed: return Not Allowed Response
HttpResponseNotAllowed is a subclass of HttpResponse that returns a HTTP response with 405 status.
1. Django HttpResponseNotAllowed with examples
To understand how HttpResponseNotAllowed is working, let's write a simple view:
importing HttpResponseNotAllowed:
from django.http import HttpResponseNotAllowed
example:
def not_allowed(request): return HttpResponseNotAllowed(["GET"])
result:
response's status:
Why we need HttpResponseNotAllowed?
For example, we have a task view, and we want to reject the user request if he tries to get the view page.
Let's see the example:
def get_user_name(request): if request.method == "POST": user = request.POST.get('user', None) return HttpResponse(user) return HttpResponseNotAllowed(["GET"])
4. How to solve HttpResponseNotAllowed is not defined
issue's output:
To solve this issue, you need to import the subclass like:
from django.http import HttpResponseNotAllowed