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.
PROJECT 2 · LESSON 4 OF 16
Learn GET, POST, bound forms, CSRF and Post/Redirect/Get before database writes.
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.
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.
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 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.
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.
Read this sequence before the source. Identify the input, the component or function that handles it, and the result the learner sees.
GET /contact/ creates an empty form and renders it.
The browser sends form fields and csrfmiddlewaretoken in a POST body.
Django validates the CSRF token, then the view binds ContactForm.
Invalid input returns the bound form with errors.
Valid input produces a message and a redirect; the next GET displays the result.
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.
Describe accepted enquiry fields and their validation rules.
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)
Bind a form only for POST and choose the response based on validation.
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})
Expose the form at /contact/.
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"),
]
Provide the shared HTML document, navigation and content slots.
{% 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>
Render the bound form and include CSRF protection for POST.
{% 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 %}
Remove csrf_token temporarily and submit from a fresh page.
The POST is rejected with 403 when CSRF checking is active.
Middleware rejects the unsafe request before the view can accept it. Restore the token; disabling middleware would remove protection for every form.
Use request.method to distinguish an empty POST from a GET; request.POST or None incorrectly treats an empty submission as unbound.
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.
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.
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.
cleaned_data contains validated and converted values. request.POST is raw user input and may contain fields your form never accepts.
No. CSRF addresses forged cross-site submissions. Ownership verification would require a separate email confirmation process.