[Django]-Django : when client request http methods that are not defined in the view class

3👍

You can take a look at the source on Github. The dispatch method checks which HTTP verb was used, and calls the appropriate function, or returns 405 - Method not allowed status code when the verb is not valid/expected (http_method_not_allowed is a django built-in method in the base View class that just returns the 405 status code).

The relevant portion is pasted below:

# Get the appropriate handler method
if request.method.lower() in self.http_method_names:
    handler = getattr(self, request.method.lower(),
                      self.http_method_not_allowed)
else:
    handler = self.http_method_not_allowed

response = handler(request, *args, **kwargs)

Essentially the same thing is done in django’s own views (dispatch in django.views.generic.View):

def dispatch(self, request, *args, **kwargs):
    # Try to dispatch to the right method; if a method doesn't exist,
    # defer to the error handler. Also defer to the error handler if the
    # request method isn't on the approved list.
    if request.method.lower() in self.http_method_names:
        handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
    else:
        handler = self.http_method_not_allowed
  return handler(request, *args, **kwargs)

If you’re ever developing with django’s own view classes, “Classy Class-Based Views” is a very helpful resource.

Leave a comment