0
0
Djangoframework~30 mins

Handling different HTTP methods in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
Handling different HTTP methods in Django views
📖 Scenario: You are building a simple Django web app that responds differently to GET and POST requests on the same URL.This is like a restaurant where the waiter listens to different requests: one to show the menu (GET) and one to take your order (POST).
🎯 Goal: Create a Django view function called handle_request that returns a different HTTP response depending on whether the request method is GET or POST.For GET requests, respond with the text 'This is a GET request'. For POST requests, respond with the text 'This is a POST request'.
📋 What You'll Learn
Create a Django view function named handle_request
Use the request.method attribute to check the HTTP method
Return an HttpResponse with the exact text 'This is a GET request' for GET requests
Return an HttpResponse with the exact text 'This is a POST request' for POST requests
💡 Why This Matters
🌍 Real World
Web servers often need to respond differently to GET and POST requests on the same URL, such as showing a form on GET and processing it on POST.
💼 Career
Understanding how to handle different HTTP methods is essential for backend web development and building RESTful APIs.
Progress0 / 4 steps
1
Import HttpResponse and create the view function
Import HttpResponse from django.http and create a function called handle_request that takes request as a parameter.
Django
Need a hint?

Start by importing HttpResponse and define the function handle_request with request as its argument.

2
Check if the request method is GET
Inside the handle_request function, add an if statement to check if request.method is equal to 'GET'.
Django
Need a hint?

Use if request.method == 'GET': to check the HTTP method.

3
Return HttpResponse for GET and POST methods
Inside the if block for GET, return HttpResponse('This is a GET request'). Add an elif block to check if request.method is 'POST' and return HttpResponse('This is a POST request').
Django
Need a hint?

Use return HttpResponse('This is a GET request') inside the GET block and similarly for POST.

4
Add a fallback response for other HTTP methods
Add an else block at the end of the handle_request function that returns HttpResponse('Unsupported HTTP method') for any other HTTP methods.
Django
Need a hint?

Use an else block to handle any HTTP methods other than GET and POST.