[Solved]-How to write separate views for GET and POST

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)

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.

👤J0HN

Leave a comment