I am new to django and I am trying to understand class views.
In urls.py (main) I have:
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('webapp.urls')),
]
in webapp folder I have:
urls.py (webapp):
from django.conf.urls import url
from webapp.views import Firstapp
urlpatterns = [
url(r'^whatever$', Firstapp.as_view()),
]
views.py (webapp):
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!')
As I have said, I am trying to use class views and I would appreciate if you could help me understand why class returns 405 error. Thank you. CMD returns 0 problems.
Because you are subclassing View
and the only method you define is called something
.
View
expects you to define a method for each valid http verb. (GET, POST, HEAD etc). Since Firstapp
has no such method, View.dispatch
will return a response with http status 405 (Method not allowed).
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.
To fix this, change your something
method:
def get(self, request):
return HttpResponse('Yes it works!')