Prerequisites: Basic knowledge of Python and Django is required. Familiarity with HTTP methods and their roles in a web application will be helpful.
Step-by-Step Guide
Django views can be written as function-based views (FBVs) or class-based views (CBVs). While you can handle HTTP methods in both, CBVs provide more structure and are recommended for larger projects.
Code Examples
Here's how to handle GET and POST methods in a basic Django view:
```python
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':
# Handle the GET request
return HttpResponse('Hello, GET!')
elif request.method == 'POST':
# Handle the POST request
return HttpResponse('Hello, POST!')
``
- In this code snippet, we first import the required modules. The
require_http_methods` decorator restricts the HTTP methods that this view will accept. If a request comes in with a different method, Django will automatically return a 405 ‘Method Not Allowed’ response.
- Inside the view, we check the method of the request. Depending on whether it's a GET or POST request, we return a different HTTP response.
Summary
For more information, you can refer to Django’s official documentation.
Practice Exercises
Solutions and explanations:
require_http_methods
decorator like this:python
@require_http_methods(["PUT"])
def my_view(request):
# Handle the PUT request
return HttpResponse('Hello, PUT!')
request.GET
:python
@require_http_methods(["GET"])
def my_view(request):
param = request.GET.get('param', 'default')
if param == 'special':
return HttpResponse('Hello, special!')
else:
return HttpResponse('Hello, default!')
For further practice, consider creating views that interact with a database model, such as creating a new instance or updating an existing one.