不允许的方法(GET):/在django中

shi*_*dul 4 python django

from django.views.generic import View
from django.http import HttpResponse

class home(View):
  def post(self,request):
    return HttpResponse('Class based view')
Run Code Online (Sandbox Code Playgroud)

当我尝试定义上述方法时,它说不允许方法(GET):/

任何人都可以帮我解决这个问题吗?

rud*_*dra 6

在您的代码中,您定义了post方法,但没有get处理GET请求的方法。您可以像这样进行修复,例如:

class home(View):
    def get(self, request):
       return HttpResponse('Class based view')

    def post(self,request):
      return HttpResponse('Class based view')
Run Code Online (Sandbox Code Playgroud)

在此处查看基于类的视图的使用:https : //docs.djangoproject.com/en/2.1/topics/class-based-views/intro/#using-class-based-views


Rit*_*sht 5

根据 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)
Run Code Online (Sandbox Code Playgroud)

如果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())
Run Code Online (Sandbox Code Playgroud)

这里,

if request.method.lower() in self.http_method_names:
    handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
Run Code Online (Sandbox Code Playgroud)

在这段代码中,if条件会通过,但是当它尝试对self执行getattr时,request.method.lower()有get作为值,所以getattr不会找到get方法,因为我们还没有定义它,所以getattr 将返回 http_method_not_allowed