class httpresponse 结果为 405 - django

class httpresponse results in 405 - django

我是 django 的新手,我正在尝试了解 class 视图。

在urls.py(主要)中我有:

from django.conf.urls import url, include
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^', include('webapp.urls')),
]

在我的 webapp 文件夹中:

urls.py(网络应用程序):

from django.conf.urls import url
from webapp.views import Firstapp

urlpatterns = [
    url(r'^whatever$', Firstapp.as_view()),

]

views.py(网络应用程序):

from django.shortcuts import render
from django.views import View
from django.http import HttpResponse

class Firstapp(View):

    def something(self):
        return HttpResponse('Yes it works!')

正如我所说,我正在尝试使用 class 视图,如果您能帮助我理解为什么 class returns 405 错误,我将不胜感激。谢谢你。 CMD returns 0 个问题。

因为您正在继承 View 并且您定义的唯一方法称为 something

View 希望您为每个有效的 http 动词定义一个方法。 (GET、POST、HEAD 等)。由于 Firstapp 没有这样的方法,View.dispatch 将 return 响应 http 状态为 405(方法不允许)。

dispatch(request, *args, **kwargs)

The view part of the view – the method that accepts a request argument plus arguments, and returns a HTTP response.

The default implementation will inspect the HTTP method and attempt to delegate to a method that matches the HTTP method; a GET will be delegated to get(), a POST to post(), and so on.

By default, a HEAD request will be delegated to get(). If you need to handle HEAD requests in a different way than GET, you can override the head() method. See Supporting other HTTP methods for an example.

要解决此问题,请更改您的 something 方法:

def get(self, request):
    return HttpResponse('Yes it works!')