Django class based post-only view

sudshekhar picture sudshekhar · Apr 26, 2016 · Viewed 18.6k times · Source

Sorry if this is a trivial question but I've been searching around for quite sometime and have been unable to find a good implementation.

Can someone provide an example of how to implement a post-only view (that can handle file uploads) in Django by subclassing any of the generic views?

I want to create an endpoint which handles all blog post comment creation logic. The comment form is embedded on my blog page and thus, this data will be sent to the url as POST.

Answer

Alasdair picture Alasdair · Apr 26, 2016

The View class has an http_method_names attribute that lists the HTTP methods that the view will accept.

Therefore, you could subclass any generic view you like (for example, CreateView), and set http_method_names so that only POST requests are allowed.

from django.views.generic.edit import CreateView


class CommentCreateView(CreateView):
    http_method_names = ['post']
    model = Comment
    ...

Alternatively, you could subclass View, and write your own post method.

class CommentView(View):

    def post(self, request):
        ...

In this case, GET requests will return a HttpResponseNotAllowed response, because you have not defined a get method to handle GET requests.