from django.views.generic import View
from django.http import HttpResponse
class home(View):
def post(self,request):
return HttpResponse('Class based view')
When I tried to define above method it says Method Not Allowed (GET): /
Can anyone please help me on this issue?
In your code, you have defined post
method, but no get
method to handle GET
request. You can put a fix like this, for example:
class home(View):
def get(self, request):
return HttpResponse('Class based view')
def post(self,request):
return HttpResponse('Class based view')
Check here for usage of class based view: https://docs.djangoproject.com/en/2.1/topics/class-based-views/intro/#using-class-based-views
According to View's dispatch method that you can find here:- 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)
If you don't define get method in View, then dispatch will call 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())
Here,
if request.method.lower() in self.http_method_names:
handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
In this piece of code the if condition will pass ,but when it will try to do getattr on self, request.method.lower() have get as value, so getattr will not find get method , because we have not defined it, so getattr will return http_method_not_allowed
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With