Skip to lesson content

PROJECT 2 · LESSON 4 OF 16

Build a validated enquiry form

Learn GET, POST, bound forms, CSRF and Post/Redirect/Get before database writes.

  • Forms
  • validation
  • CSRF
  • redirects

Your workspace: edushop

Continue from lesson 3: Build a reusable business website. Keep existing files; create or replace the complete files listed below.

Extract the ZIP and open the folder containing manage.py. Create a Python virtual environment, install requirements.txt and run migrate. Read README.md for checkpoint-specific commands and LESSON.md for offline explanations. Checkpoints contain no database records or private credentials.

1. Understand the problem and the concepts

Why we need this feature

An HTML form can collect text, but collecting is not the same as accepting valid input. A contact page teaches the complete submission cycle before we write database records: display, bind, validate, explain errors and acknowledge success.

This enquiry form intentionally validates and acknowledges input without sending an email. A success message says exactly that. Database persistence is the next project.

A GET displays the blank form. A POST binds submitted values. Invalid forms redisplay the values and errors; valid submissions redirect to avoid resubmitting on refresh.

Unbound and bound forms

On GET, construct an unbound ContactForm so the visitor sees empty inputs. On POST, construct it with request.POST so it becomes bound to submitted values. is_valid performs field conversion and validation. Only after it returns true should the view read cleaned_data. Invalid forms keep submitted values and errors, allowing the visitor to correct a specific problem.

A browser may validate an email field, but a script can send any HTTP request. Django’s server-side EmailField still checks the submitted value. Form validation is the authority; browser validation is a convenience. Required fields and length limits should be enforced on the server even when the HTML already describes them.

GET reads; POST submits

GET requests should not create records or trigger a contact action. Browsers, crawlers and link previews can issue GET automatically. POST signals an intended submission. The CSRF middleware checks that an unsafe request carries a valid token associated with the visitor’s context; place csrf_token inside the POST form.

After success, redirect to a GET page. This Post/Redirect/Get pattern prevents an ordinary refresh of the result page from resubmitting the form. It does not make all repeated POSTs impossible; checkout will need its own idempotency design later. Messages provide short-lived feedback across the redirect.

Be honest about what this application does

This project validates contact details and displays a confirmation. It does not send email or save messages. A successful validation message proves the form cycle works, not that someone received mail. Connecting an email service would require delivery configuration, failure handling and a decision about storing personal data.

Notice how the same form object controls HTML fields and server validation. If a form is invalid, render that bound object again rather than constructing a new blank one. Throwing away the bound object hides errors and forces the visitor to retype their work.

2. Follow the execution flow

Read this sequence before the source. Identify the input, the component or function that handles it, and the result the learner sees.

  1. GET /contact/ creates an empty form and renders it.

  2. The browser sends form fields and csrfmiddlewaretoken in a POST body.

  3. Django validates the CSRF token, then the view binds ContactForm.

  4. Invalid input returns the bound form with errors.

  5. Valid input produces a message and a redirect; the next GET displays the result.

Follow an invalid submission

  1. Enter an invalid email and submit; if the browser blocks it, inspect server validation using Django’s test client later.
  2. Observe that the form reports the email problem rather than treating raw text as accepted data.
  3. Correct the email and submit. Follow the redirect and confirm that no database record or outgoing email is claimed.

3. Build it, one file at a time

  1. Add ContactForm, the view and template. Replace the URL configuration and shared navigation.
  2. Submit a bad email and a short message. Read the field errors instead of expecting a redirect.
  3. Submit valid values and refresh the resulting page. It should remain a GET rather than repeating the POST.

The paths below are relative to your practice project. Each block is the complete file at this checkpoint. Read its responsibility first, type or copy the code, then use the walkthrough to explain the important statements.

shop/forms.py

Describe accepted enquiry fields and their validation rules.

shop/forms.py
from django import forms


class ContactForm(forms.Form):
    name = forms.CharField(max_length=80)
    email = forms.EmailField()
    message = forms.CharField(min_length=10, max_length=1000, widget=forms.Textarea)

Read the code

  1. EmailField validates syntax and CharField applies required/length checks. These checks run on the server even if a browser skips HTML validation.
  2. widget changes presentation; it does not bypass the field’s rules.

shop/views.py

Bind a form only for POST and choose the response based on validation.

shop/views.py
from django.http import HttpResponse
from django.shortcuts import render


def home(request):
    return render(request, "shop/home.html", {"features": ["Learn", "Build", "Share"]})


def about(request):
    return render(request, "shop/about.html")


def greeting(request, name):
    return HttpResponse(f"Hello, {name}!", content_type="text/plain")

from django.contrib import messages
from django.shortcuts import redirect
from .forms import ContactForm


def contact(request):
    form = ContactForm(request.POST if request.method == "POST" else None)
    if request.method == "POST" and form.is_valid():
        # Learning preview only: no email or storage is performed at this stage.
        messages.success(request, "Your enquiry passed validation. This practice form does not send email yet.")
        return redirect("shop:contact")
    return render(request, "shop/contact.html", {"form": form})

Read the code

  1. request.POST is a multi-value collection of submitted fields. is_valid populates cleaned_data or errors.
  2. On success redirect returns an HTTP redirect and messages survives into the next request through middleware. This view does not claim to send mail.

shop/urls.py

Expose the form at /contact/.

shop/urls.py
from django.urls import path
from . import views

app_name = "shop"
urlpatterns = [
    path("", views.home, name="home"),
    path("about/", views.about, name="about"),
    path("hello/<str:name>/", views.greeting, name="greeting"),
    path("contact/", views.contact, name="contact"),
]

Read the code

  1. Named routes let redirect and url use shop:contact without duplicating the URL string.

templates/base.html

Provide the shared HTML document, navigation and content slots.

templates/base.html
{% load static %}
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>{% block title %}EduShop{% endblock %}</title>
  <link rel="stylesheet" href="{% static 'shop/site.css' %}">
</head>
<body>
<nav aria-label="Main navigation">
  <a href="{% url 'shop:home' %}">Home</a>
  <a href="{% url 'shop:about' %}">About</a>
  <a href="{% url 'shop:contact' %}">Contact</a>
</nav>
{% for message in messages %}<p role="status">{{ message }}</p>{% endfor %}
<main>{% block content %}{% endblock %}</main>
<footer>EduShop · Built while learning Django</footer>
</body>
</html>

Read the code

  1. extends in a child template reuses this document; block content is where that child supplies its page.
  2. url resolves named routes and static builds the asset URL. These are server-side template tags, not browser JavaScript.
  3. Messages report the outcome after a redirect. Once authentication is added, logout uses a CSRF-protected POST form.

templates/shop/contact.html

Render the bound form and include CSRF protection for POST.

templates/shop/contact.html
{% extends "base.html" %}
{% block content %}<h1>Contact us</h1><p>Practice form: validates input but does not send email.</p>
<form method="post">{% csrf_token %}{{ form.as_p }}<button>Check enquiry</button></form>{% endblock %}

Read the code

  1. form.as_p includes labels, widgets and validation errors. csrf_token generates a hidden token tied to the request context.
  2. Never remove CSRF middleware to make a failing form submit; investigate token and origin configuration instead.

4. Run it and check your result

  • Invalid input retains its values and displays errors.
  • Valid input redirects and shows the honest validation-only message.

5. Predict, change and observe

Remove csrf_token temporarily and submit from a fresh page.

Compare your prediction with the expected result

What you should observe

The POST is rejected with 403 when CSRF checking is active.

Why it happens

Middleware rejects the unsafe request before the view can accept it. Restore the token; disabling middleware would remove protection for every form.

6. Troubleshoot with evidence

A common mistake

Use request.method to distinguish an empty POST from a GET; request.POST or None incorrectly treats an empty submission as unbound.

Errors disappear after submission

Likely cause: The view replaces an invalid bound form with a new unbound form.

Check and correct: Render the same form instance when is_valid returns false.

Success appears but no email arrives

Likely cause: This checkpoint does not include an email backend workflow.

Check and correct: Read the success wording: it confirms validation only. Email delivery is a separate feature.

7. Practice and explain it back

Your independent task

Add an optional subject field and render it through the existing form.

Attempt these questions before opening the explanations. Use the source above to justify your answer.

Why use cleaned_data instead of request.POST?

cleaned_data contains validated and converted values. request.POST is raw user input and may contain fields your form never accepts.

Does CSRF verify the email belongs to the sender?

No. CSRF addresses forged cross-site submissions. Ownership verification would require a separate email confirmation process.