0
0
Djangoframework~5 mins

Handling different HTTP methods in Django

Choose your learning style9 modes available
Introduction

Handling different HTTP methods lets your web app respond correctly to actions like viewing, sending, or updating data.

When you want to show a form on a page and also process the form submission.
When your app needs to respond differently to a page visit (GET) versus a form submission (POST).
When building APIs that accept data updates (PUT) or deletions (DELETE).
Syntax
Django
from django.http import HttpResponse
from django.views.decorators.http import require_http_methods

@require_http_methods(["GET", "POST"])
def my_view(request):
    if request.method == "GET":
        return HttpResponse("This is a GET request")
    elif request.method == "POST":
        return HttpResponse("This is a POST request")

Use request.method to check which HTTP method was used.

The decorator @require_http_methods limits allowed methods and returns 405 error if others are used.

Examples
Basic example checking GET and POST inside one view function.
Django
from django.http import HttpResponse

def example_view(request):
    if request.method == "GET":
        return HttpResponse("Show data")
    elif request.method == "POST":
        return HttpResponse("Save data")
Using a decorator to allow only GET requests.
Django
from django.http import HttpResponse
from django.views.decorators.http import require_GET

@require_GET
def only_get_view(request):
    return HttpResponse("Only GET allowed")
Using a decorator to allow only POST requests.
Django
from django.http import HttpResponse
from django.views.decorators.http import require_POST

@require_POST
def only_post_view(request):
    return HttpResponse("Only POST allowed")
Sample Program

This Django view responds differently based on whether the user sends a GET or POST request.

Django
from django.http import HttpResponse
from django.views.decorators.http import require_http_methods

@require_http_methods(["GET", "POST"])
def greet(request):
    if request.method == "GET":
        return HttpResponse("Hello! You sent a GET request.")
    elif request.method == "POST":
        return HttpResponse("Hello! You sent a POST request.")
OutputSuccess
Important Notes

Always handle unexpected methods to avoid errors.

Use decorators to keep your code clean and restrict methods easily.

GET requests should not change data; POST is for sending data.

Summary

Check request.method to handle different HTTP methods in one view.

Use decorators like @require_http_methods to restrict allowed methods.

Respond differently to GET and POST to support forms and data updates.