These decorators help make sure your web views only accept certain types of requests, like GET or POST. This keeps your app safe and organized.
0
0
View decorators (require_GET, require_POST) in Django
Introduction
When you want a page to only show data and not change anything, use require_GET.
When a form submits data to your server, use require_POST to accept only POST requests.
To prevent users from accidentally sending data with the wrong method.
To improve security by blocking unwanted request types.
When you want clear rules about how your views handle requests.
Syntax
Django
from django.views.decorators.http import require_GET, require_POST @require_GET def my_view_get(request): # handle GET request @require_POST def my_view_post(request): # handle POST request
Place the decorator right above your view function.
If a request uses the wrong method, Django returns a 405 error automatically.
Examples
This view only allows GET requests to show items.
Django
from django.http import HttpResponse from django.views.decorators.http import require_GET @require_GET def show_items(request): return HttpResponse('Showing items')
This view only accepts POST requests to submit a form.
Django
from django.http import HttpResponse from django.views.decorators.http import require_POST @require_POST def submit_form(request): return HttpResponse('Form submitted')
Sample Program
This example shows two views: one only accepts GET requests and returns a greeting, the other only accepts POST requests and returns a different greeting.
Django
from django.http import HttpResponse from django.views.decorators.http import require_GET, require_POST @require_GET def greet_get(request): return HttpResponse('Hello via GET') @require_POST def greet_post(request): return HttpResponse('Hello via POST')
OutputSuccess
Important Notes
These decorators help keep your views simple and secure by limiting request methods.
They automatically handle errors for wrong methods, so you don't need extra code.
Summary
Use @require_GET to allow only GET requests to a view.
Use @require_POST to allow only POST requests to a view.
They help keep your app safe and clear about how it handles requests.