11

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?

George Cummins
  • 28,485
  • 8
  • 71
  • 90
Philip007
  • 3,190
  • 7
  • 46
  • 71
  • You should `return view2(request)`. View2 returned it's result to the caller (which is `view1`), but the caller needs to return it as well. – J0HN May 29 '13 at 19:47

2 Answers2

11

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.

Community
  • 1
  • 1
J0HN
  • 26,063
  • 5
  • 54
  • 85
  • 1
    I really like this answer. It makes the code very clear and easy to maintain. – Dunatotatos Feb 13 '17 at 15:16
  • This is definitely the better way to handle views. You don't want to write two large complicated logic inside `if else` when you can call separate functions. – Qumber Aug 17 '20 at 06:21
7

You need to return the results of view2:

def view1 (request):
    if request.method == 'POST':
        return view2(request)
    else:
        # handle GET
        return render(request, template, context)
girasquid
  • 15,121
  • 2
  • 48
  • 58