Django Forms: The Easy Way to Handle User Input

3D visualization of a Django machine transforming messy user input into validated, organized forms.

HTML forms are painful. You have to write the <input> tags, handle the POST request, validate that the user didn’t leave fields blank, and show error messages if they did.

Django handles all of this for you with its Forms system.

Step 1: Create the Form Class

In your pages app, create a new file called forms.py. We’ll make a form to create new Blog Posts.

# pages/forms.py
from django import forms
from .models import Post

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ['title', 'text']

By using ModelForm, Django automatically knows it needs a text input for title and a large text area for text, because that’s what we defined in our Model.

Step 2: The View

We need a view that can handle two things:

  1. GET request: Show the empty form.
  2. POST request: Process the submitted data.
# pages/views.py
from django.shortcuts import render, redirect
from .forms import PostForm

def create_post_view(request):
    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            form.save()  # Saves directly to the database!
            return redirect('home')
    else:
        form = PostForm()  # An empty form for GET requests

    return render(request, 'pages/create_post.html', {'form': form})

Step 3: The Template

Django makes rendering the form incredibly easy.

<h1>Create a New Post</h1>
<form method="post">
    {% csrf_token %}  {{ form.as_p }}   <button type="submit">Save Post</button>
</form>

That {{ form.as_p }} line automatically generates all the necessary HTML <input> labels and tags.

Similar Posts

Leave a Reply