Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 77 ยท Forms

Handling Forms in Views

Handle Django forms in views with the GET/POST pattern, redirect after POST, CSRF protection, the messages framework, file uploads and FormView.

A form class describes fields and rules, but it does nothing until a view connects it to the request. The view decides what happens on a first visit (show an empty form), on a submission with mistakes (show the form again with errors) and on a good submission (do the work, then send the user somewhere else). Getting this flow right protects users from double submissions and keeps your code easy to read.

This lesson shows the standard view pattern with forms and validation, why you must redirect after a successful POST, how CSRF protection works, how to show one-time notices with the messages framework, how file uploads differ, and how FormView packages the pattern. Every example drives real views with Django's test client, so you can see status codes, redirects and cookies.

The examples use a stand-in formsite_urls module instead of a urls.py file, an in-memory template loader instead of template files, and signed cookies for the session. A real project has the same pieces as files on disk.

The GET/POST pattern

Almost every form view has the same three branches:

flowchart TB
    R["Request arrives"] --> M{"request.method"}
    M -->|"GET"| E["Create an empty form"]
    M -->|"POST"| B["Bind form to request.POST"]
    B --> V{"is_valid()?"}
    V -->|"no"| S["Render page again<br/>(form shows errors)"]
    V -->|"yes"| W["Do the work, then redirect"]
    E --> S

GET shows a blank form; POST validates; a valid POST ends with a redirect, an invalid one shows the same page again with errors.

In code the pattern looks like this (you will see it in nearly every Django project):

Python
def contact(request):
    if request.method == "POST":
        form = ContactForm(request.POST)
        if form.is_valid():
            ...                      # save, send e-mail, call an API
            return redirect("contact")
    else:
        form = ContactForm()
    return render(request, "form.html", {"form": form})

Two details matter. When validation fails, the view falls through to the final render() call with the bound form, so the page shows the user's input and the errors. And on success it redirects instead of rendering a page. That is the Post/Redirect/Get pattern. If a successful POST rendered a page directly, pressing the browser's reload button would submit the form again, creating a second order or a duplicate comment. With a redirect, reload simply repeats the harmless GET.

Redirect after POST and flash messages

After the redirect, the user should know what happened. The messages framework stores a short notice in the session (or a cookie) during the POST and delivers it on the next request, after which it disappears. Messages have levels (debug, info, success, warning, error) that become CSS classes in your template.

Python A contact view, the Post/Redirect/Get flow and messages

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Follow the flow in the output. The first GET returns an empty form containing a hidden CSRF field. The invalid POST returns status 200, because the page is rendered again, and the response shows the error and the typed e-mail address. The valid POST returns 302 with a Location header: the browser will fetch /contact/ with a GET. That page shows the success message once, and the next visit shows nothing, because messages are consumed when they are read.

Use redirect("contact") with a URL name (see URL routing) rather than a hard-coded path, so a changed URL does not break the view. After creating an object, redirect to its detail page.

CSRF protection

A cross-site request forgery attack tricks a logged-in user's browser into sending a request to your site from another page: a hidden form that posts to /transfer/, for example. The browser attaches the user's cookies automatically, so the request looks legitimate.

Django defends against this with a token. CsrfViewMiddleware sets a csrftoken cookie, and every POST must also carry the same secret in a form field (csrfmiddlewaretoken) or the X-CSRFToken header. A page on another site can make the browser send the cookie but cannot read it, so it cannot supply the matching token. Without the token, Django answers with 403 Forbidden.

In templates, add {% csrf_token %} inside every <form method="post"> that targets your own site. That tag renders the hidden field. Never put the tag in a form that posts to an external URL, since it would leak your token.

Django's test client skips CSRF checks by default so that tests stay simple. You can switch the checks on to see the behavior:

Python What CSRF protection does

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notes on the result:

  • Step 1 returns 403: no token, no entry. This is exactly what an attacker's forged request experiences.
  • Steps 3 and 5 succeed with 302, the success redirect, so the token check passed.
  • Real tokens in the form are masked and differ on every page load. Django unmasks them when comparing, so you never write that logic.
  • For JavaScript fetch calls, read the csrftoken cookie and send it in the X-CSRFToken header.
  • Do not disable CSRF protection (@csrf_exempt) just to make an error go away. Use it only for endpoints that are called by other servers and authenticate in another way, such as webhooks that verify a signature.

File uploads

Forms with a FileField or ImageField differ in two places:

  1. The HTML <form> must have enctype="multipart/form-data"; otherwise the browser sends only the file name. You can test form.is_multipart() in a template to decide.
  2. The view passes both request.POST and request.FILES to the form: AvatarForm(request.POST, request.FILES).

Uploaded files arrive as UploadedFile objects with .name, .size, .content_type and .read(). Small files stay in memory; large ones stream to a temporary file. Where the file finally goes (disk, cloud storage) is decided by a model's FileField and the storage settings, covered in Static Files and Media. Here we only validate and read the upload.

Never trust content_type or the file name; both come from the client. Check the extension, limit the size, and for images use ImageField, which verifies that the bytes really decode as an image.

FormView: the pattern, packaged

The GET/POST/redirect skeleton is so common that Django offers it as a class-based view. FormView needs a form_class, a template_name and a success_url, and calls form_valid(form) when the data is good. You override that one method to do the work. (Class-based views are explained in Class-Based Views.)

Python A FormView with a file upload

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

FormView handled the three branches for us. Invalid uploads (too big, wrong type, missing) re-rendered the page with status 200 and errors, and the valid upload ended in a redirect to the same URL, where the success message appeared. The test client sends the file as multipart/form-data just like a browser, and request.FILES was passed to the form automatically by the class.

Related views fit the same mold. CreateView and UpdateView (Generic Display and Editing Views) are FormView variants built on a ModelForm: they also create or update the object in form_valid.

Common mistakes

  • Rendering a page after a successful POST instead of redirecting. Reload then resubmits the form.
  • Creating an unbound form on POST errors. Always render the bound form so users see their input and the errors.
  • Forgetting request.FILES or the enctype. The file field then fails with "This field is required", which confuses everyone.
  • Using request.POST["x"] directly instead of cleaned_data. The raw values are unvalidated strings.
  • Missing {% csrf_token %}, which results in a 403 page.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why should a view redirect after a successful POST?

    After a redirect the browser's last request is a GET, so reload is harmless. This is the Post/Redirect/Get pattern.
  2. 2. A POST with invalid data is handled by the view. What status code does the rendered error page normally have?

    Django view code simply renders the template again with the bound form, so the response is a normal 200 page that contains the error messages.
  3. 3. What happens to a POST request that has no valid CSRF token when CsrfViewMiddleware is active?

    The middleware refuses unsafe requests that lack the matching token, which stops forged cross-site requests.
  4. 4. Which two things are required for a form that uploads files?

    Without the multipart encoding the browser sends only the file name, and without request.FILES the form never sees the uploaded data.
  5. 5. In a FormView, where do you put the code that runs when the data is valid?

    FormView calls form_valid(form) for a valid POST. The default implementation redirects to success_url, and you extend it to do the real work.

Summary

  • A form view has three branches: GET shows an empty form, an invalid POST re-renders the bound form, a valid POST does the work and redirects.
  • Redirect after a successful POST (Post/Redirect/Get) so reloading does not repeat the action.
  • The messages framework carries one-time notices across a redirect.
  • CSRF protection needs {% csrf_token %} in your own POST forms (or the X-CSRFToken header for JavaScript); requests without a valid token get 403.
  • File uploads need enctype="multipart/form-data" and request.FILES; validate size and extension yourself.
  • FormView packages the pattern; override form_valid for the real work.

Next, meet the automatic admin interface in The Django Admin.