Skip to content Skip to sidebar Skip to footer

Django Get And Post Handling Methods

I want a way to automatically route GET and POST requests to subsequent methods in a centralized way. I want to create my handler in the following way. class MyHandler(BaseHandler)

Solution 1:

This is supported in Django as class based views. You can extend the generic class View and add methods like get(), post(), put() etc. E.g. -

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

classMyView(View):
    defget(self, request, *args, **kwargs):
        return HttpResponse('This is GET request')

    defpost(self, request, *args, **kwargs):
        return HttpResponse('This is POST request')

The dispatch() method from View class handles this-

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.

The default implementation also sets request, args and kwargs as instance variables, so any method on the view can know the full details of the request that was made to invoke the view.

Then you can use it in urls.py -

from django.conf.urls import patterns, url

from myapp.views import MyView

urlpatterns = patterns('',
    url(r'^mine/$', MyView.as_view(), name='my-view'),
)

Post a Comment for "Django Get And Post Handling Methods"