Handling POST in a View
The standard pattern for processing a submitted form.
Syntax
if request.method == "POST": ...A form view usually handles two cases: a GET shows an empty form, and a POST processes the submission. If the data is valid, save and redirect; otherwise re-render the form with its errors.
Redirecting after a successful POST prevents duplicate submissions on refresh.
Example
from django.shortcuts import render, redirect
from .forms import PostForm
def create_post(request):
if request.method == "POST":
form = PostForm(request.POST)
if form.is_valid():
form.save()
return redirect("index")
else:
form = PostForm()
return render(request, "blog/create.html", {"form": form})When to use it
- A developer processes a login form by reading POST data, authenticating the user, and redirecting on success.
- A developer uses request.FILES to handle file uploads submitted alongside a POST form.
- A developer follows the Post/Redirect/Get pattern to prevent duplicate form submissions on browser refresh.
More examples
Standard POST handling pattern
Implements the Post/Redirect/Get pattern: on valid POST save and redirect, on GET show an empty form.
def post_create(request):
if request.method == "POST":
form = PostForm(request.POST)
if form.is_valid():
form.save()
return redirect("post-list") # PRG pattern
else:
form = PostForm()
return render(request, "blog/post_form.html", {"form": form})Handle file upload in POST
Passes request.FILES as the second argument to ModelForm to handle uploaded file data.
def upload_avatar(request):
if request.method == "POST":
form = AvatarForm(request.POST, request.FILES)
if form.is_valid():
request.user.profile.avatar = form.cleaned_data["avatar"]
request.user.profile.save()
return redirect("profile")
else:
form = AvatarForm()
return render(request, "profile/avatar.html", {"form": form})Read raw POST data
Reads raw JSON from request.body for API endpoints that accept application/json POST bodies.
import json
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def api_receive(request):
if request.method == "POST":
data = json.loads(request.body)
name = data.get("name", "")
return JsonResponse({"received": name})
Discussion