R – Http verb decorator for Django

asp.net-mvcdjangodjango-viewshttpverbs

In ASP.NET MVC, you can use the AcceptVerbs attribute to correlate a view function with a verb:

public ActionResult Create()
{
    // do get stuff
} 

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(FormCollection collection)
{
    // do post stuff
}

The Django Book suggests something like this:

def method_splitter(request, *args, **kwargs):
    get_view = kwargs.pop('GET', None)
    post_view = kwargs.pop('POST', None)
    if request.method == 'GET' and get_view is not None:
        return get_view(request, *args, **kwargs)
    elif request.method == 'POST' and post_view is not None:
        return post_view(request, *args, **kwargs)
    raise Http404

urls.py:

urlpatterns = patterns('',
    # ...
    (r'^somepage/$', views.method_splitter, {'GET': views.some_page_get, 
        'POST': views.some_page_post}),
    # ...
)

That seems a little ugly to me – is there a decorator that can associate an HTTP verb with a view, ASP.NET MVC-style, or another accepted way to do this?

Best Solution

There are standard built-in decorators for requiring particular HTTP method or list of allowed methods.

See the code: http://code.djangoproject.com/browser/django/trunk/django/views/decorators/http.py.