Handling form submissions in Django is essential for collecting user input and interacting with backend logic. Django primarily uses the GET and POST HTTP methods to handle form data securely and efficiently.
The method attribute in HTML forms defines how data is transmitted. Django exposes this data using request.GET and request.POST dictionaries inside views.
# Django view handling GET request
from django.shortcuts import render
def search_view(request):
if request.method == "GET":
query = request.GET.get('q', '')
return render(request, 'search_results.html', {'query': query})
# Django view handling POST request
from django.shortcuts import render, redirect
from .forms import ContactForm
def contact_view(request):
if request.method == "POST":
form = ContactForm(request.POST)
if form.is_valid():
return redirect('thank_you')
else:
form = ContactForm()
return render(request, 'contact.html', {'form': form})
# Django template with CSRF protection
{% extends "base.html" %}
{% block content %}
{% endblock %} GET requests append data to the URL, making them visible and bookmarkable. POST requests keep data hidden and are safer for sensitive operations.
Simulator: See how data travels
Select a method and click "Send Request" to observe the difference.