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):
    def get(self):
        #handle get requests

    def post(self):
        #handle post requests

This is what webapp2 does and I very much like the style, is it possible to do in Django? I also want the view in Class-method style. What kind of BaseHandler and router should I write.

HINT: Use django generic views.

5/21/2013 11:35:53 AM

Accepted Answer

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

class MyView(View):
    def get(self, request, *args, **kwargs):
        return HttpResponse('This is GET request')

    def post(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 -

from django.conf.urls import patterns, url

from myapp.views import MyView

urlpatterns = patterns('',
    url(r'^mine/$', MyView.as_view(), name='my-view'),
5/21/2013 11:35:55 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow