根据您可以在此处找到的 View 的调度方法:-
https://ccbv.co.uk/projects/Django/2.0/django.views.generic.base/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)
如果你没有在View中定义get方法,那么dispatch会调用self.http_method_not_allowed
def http_method_not_allowed(self, request, *args, **kwargs):
logger.warning(
'Method Not Allowed (%s): %s', request.method, request.path,
extra={'status_code': 405, 'request': request}
)
return HttpResponseNotAllowed(self._allowed_methods())
这里,
if request.method.lower() in self.http_method_names:
handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
在这段代码中,if条件会通过,但是当它尝试对self做getattr时,request.method.lower()有get作为值,所以getattr找不到get方法,因为我们没有定义它,所以 getattr 将返回 http_method_not_allowed