🎓 A1Learner
🔍
0 of 50 lessons completed

Handling a POST in Django

Handling a POST means reading the values a form sends. The view checks the request method first.

Make the form

This form has one field for a name. The form class comes from an earlier lesson.

from django import forms

class NameForm(forms.Form):
    name = forms.CharField(max_length=50)

Read a POST

The view builds the form from the posted values. A valid form gives back the checked name.

def echo(request):
    if request.method == "POST":
        form = NameForm(request.POST)
        if form.is_valid():
            return HttpResponse("Posted: " + form.cleaned_data["name"])
        return HttpResponse("Please type a name")

Show the form on a GET

The csrf_token tag adds a hidden token to the form. The token proves the form came from this site.

template = Template('<form method="post">{% csrf_token %}<input name="name"></form>')
return HttpResponse(template.render(RequestContext(request)))

Post a word and an empty form

The first post sends hello. The second post sends an empty name.

client = Client()
print(client.post("/echo", {"name": "hello"}).content.decode())
print(client.post("/echo", {"name": ""}).content.decode())

Example

import django
from django.conf import settings

settings.configure(
    DEBUG=True,
    SECRET_KEY="key",
    ROOT_URLCONF=__name__,
    ALLOWED_HOSTS=["*"],
    TEMPLATES=[{"BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "APP_DIRS": True}],
)
django.setup()

from django import forms
from django.http import HttpResponse
from django.template import RequestContext, Template
from django.urls import path
from django.test import Client


class NameForm(forms.Form):
    name = forms.CharField(max_length=50)


def echo(request):
    if request.method == "POST":
        form = NameForm(request.POST)
        if form.is_valid():
            return HttpResponse("Posted: " + form.cleaned_data["name"])
        return HttpResponse("Please type a name")
    template = Template('<form method="post">{% csrf_token %}<input name="name"></form>')
    return HttpResponse(template.render(RequestContext(request)))


urlpatterns = [path("echo", echo)]

client = Client()
print(client.get("/echo").status_code)
print(client.post("/echo", {"name": "hello"}).content.decode())
print(client.post("/echo", {"name": ""}).content.decode())

Key points

  • request.method holds the method of the request.
  • A POST carries the sent form values.
  • A GET shows the form instead.
  • One view handles both halves of a form.
  • cleaned_data holds the checked values from a valid form.
  • Handling a POST means reading sent values in the view.

In this example, the setup lines configure Django. The NameForm class has one field for a name. The echo view checks the request method. A POST builds the form from the posted values and echoes the checked name. An empty name fails the check and gets a message. A GET renders the form with a CSRF token. The test client opens with GET, then posts hello, then posts an empty name. The prints show the 200 status, the echo, and the message.

Note

The test client skips CSRF checks by default.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

How does a view know a POST from a GET?