[Fixed]-Django distinguish between get / post in view's methods

13👍

There’s no need to create functions for each one, you can “ask” the request:

You can:

def login(request):
    if request.method == 'POST':
        # Your code for POST
    else:
        # Your code for GET
    return render(request, 'login.html')

Or, you can assume GET as the default:

def login(request):
    if request.method == 'POST':
        # Your code for POST
        # make sure to put a "return redirect" statement here
    # Your code for GET
    return render(request, 'login.html')

Both are okay. Also, take a look at Class-based Views as an alternative, they are very helpful.

👤César

12👍

As mentioned in the Django documentation, another approach would be to used class-based views.

Class-based views provide an alternative way to implement views as Python objects instead of functions. They do not replace function-based views, but have certain differences and advantages when compared to function-based views:

  • Organization of code related to specific HTTP methods (GET, POST, etc) can be addressed by separate methods instead of conditional branching.
  • Object oriented techniques such as mixins (multiple inheritance) can be used to factor code into reusable components.

So instead of using function-based view (as mentioned in other answers):

from django.shortcuts import render

def login(request):
    if request.method == 'POST':
        # handle the post request
     else:
         # handle the get request
     return render(request, 'login.html')

You could use a class-based view like so:

from django.shortcuts import render
from django.views.generic import View

class LoginView(View):
    def post(self, request):
        # handle the post request
        return render(request, 'login.html')

    def get(self, request):
        # handle the get request
        return render(request, 'template-path.html')

When using class-based views, your urls.py would look like this:

# urls.py
from django.conf.urls import url
from myapp.views import LoginView

urlpatterns = [
    url(r'^login/', LoginView.as_view()),
]
👤strix

Leave a comment