Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write separate views for GET and POST

Tags:

django

First of all I want both views use exact same URL because I don't want to make my URLConf more complicated. I want separate views for GET and POST to make my code cleaner. The code is something like this:

def view2 (request):
    # handle POST request, possibly a ajax one
    return HTTPRESPONSE(json_data, mimetype="Application/JSON")

def view1 (request):
    if method == POST:
        view2(request)
        # What should I return here???

    else:
        # handle GET
        return render(request, template, context)

My question is about the # What should I return here??? line. If I don't put a return there, error occurs:

not returning http response

But I already return an HTTP response in view2. How can I make this work?

like image 246
Philip007 Avatar asked May 29 '13 18:05

Philip007


1 Answers

Another, probably a bit cleaner way would be using class-based views

from django.views.generic import TemplateView

class View1(TemplateView):
    def get(self, request, *args, **kwargs):
        """handle get request here"""

    def post(self, request, *args, **kwargs):
        """handle post request here"""

    def head(self, request, *args, **kwargs):
        """handle head request here. Yes, you can handle any kind of requests, not just get and post"""

Of course you can add common methods, __init__ (which is useless unless you are sure what you are doing), apply login_required (see this SO question) and pretty much everything you can do with django views (e.g. apply middleware, permissions, etc.) and python classes (e.g. inheritance, metaclasses/decorators, etc.)

Also, there's a whole bunch of generic class based view coming with Django to address common situations like list page, details page, edit page, etc.

like image 135
J0HN Avatar answered Sep 27 '22 19:09

J0HN