How to Create a Web Form in Python Django

Creating web forms is essential when you want to collect user input. I’ve found that building forms in Django is simple. In this article, I’ll walk you through how to create a web form in Django with practical examples that you can adapt for real-world applications.

We’ll cover both basic forms using Django’s Form class and model-based forms using ModelForm. By the end, you’ll have a solid understanding of how to create, display, and process forms in Django.

Let’s get started!

Methods to Use Django for Web Forms

Django’s form system handles a lot of the heavy lifting for you. It automatically generates HTML form elements, validates user input, and protects against common web security issues like Cross-Site Request Forgery (CSRF). This means you can focus more on your application logic rather than reinventing the wheel.

Read Register User with OTP Verification in Django

1: Create a Simple Form Using Django’s Form Class

This method is perfect when you want to build a form that isn’t directly tied to a database model, such as a newsletter signup or a feedback form.

Step 1: Set Up Your Django Project and App

If you haven’t already created a Django project, start one:

django-admin startproject myproject
cd myproject
python manage.py startapp webformapp

Add 'webformapp' to your INSTALLED_APPS in settings.py.

Step 2: Create the Form Class

In your app directory, create a file named forms.py and add the following:

from django import forms

class ContactForm(forms.Form):
    name = forms.CharField(max_length=100, label='Full Name')
    email = forms.EmailField(label='Email Address')
    message = forms.CharField(widget=forms.Textarea, label='Your Message')

Step 3: Create the View to Handle the Form

In views.py of your app:

from django.shortcuts import render
from .forms import ContactForm

def contact_view(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            # Process form data here (e.g., send email)
            name = form.cleaned_data['name']
            email = form.cleaned_data['email']
            message = form.cleaned_data['message']
            # For demo, just print to console
            print(f"Received message from {name} ({email}): {message}")
            return render(request, 'webformapp/thank_you.html', {'name': name})
    else:
        form = ContactForm()
    return render(request, 'webformapp/contact.html', {'form': form})

Step 4: Create Templates

Create templates/webformapp/contact.html:

<!DOCTYPE html>
<html>
<head>
    <title>Contact Us</title>
</head>
<body>
    <h1>Contact Form</h1>
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Send</button>
    </form>
</body>
</html>

Create templates/webformapp/thank_you.html:

<!DOCTYPE html>
<html>
<head>
    <title>Thank You</title>
</head>
<body>
    <h1>Thank you, {{ name }}!</h1>
    <p>Your message has been received. We will get back to you shortly.</p>
</body>
</html>

Step 5: Add URL Configuration

In webformapp/urls.py:

from django.urls import path
from .views import contact_view

urlpatterns = [
    path('contact/', contact_view, name='contact'),
]

Include this in your project’s main urls.py:

from django.urls import path, include

urlpatterns = [
    path('', include('webformapp.urls')),
]

Step 6: Run the Server and Test

python manage.py runserver

You can refer to the screenshot below to see the output:

python web form

Navigate to http://127.0.0.1:8000/contact/ and try submitting the form.

contact form python

Check out Python Django Convert Date Time to String

2: Create a Model-Based Form Using Django’s ModelForm

If you want to save form data directly to your database, ModelForm is the way to go. This method is ideal for applications like user registration, surveys, or any data collection that requires persistence.

Step 1: Define Your Model

In models.py:

from django.db import models

class Feedback(models.Model):
    full_name = models.CharField(max_length=100)
    email = models.EmailField()
    message = models.TextField()
    submitted_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.full_name} ({self.email})"

Run migrations:

python manage.py makemigrations
python manage.py migrate

Step 2: Create the ModelForm

In forms.py:

from django import forms
from .models import Feedback

class FeedbackForm(forms.ModelForm):
    class Meta:
        model = Feedback
        fields = ['full_name', 'email', 'message']

Step 3: Create the View

In views.py:

from django.shortcuts import render, redirect
from .forms import FeedbackForm

def feedback_view(request):
    if request.method == 'POST':
        form = FeedbackForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('thank_you')
    else:
        form = FeedbackForm()
    return render(request, 'webformapp/feedback.html', {'form': form})

def thank_you(request):
    return render(request, 'webformapp/thank_you.html')

Step 4: Templates

Create templates/webformapp/feedback.html:

<!DOCTYPE html>
<html>
<head>
    <title>Feedback Form</title>
</head>
<body>
    <h1>Feedback</h1>
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Submit</button>
    </form>
</body>
</html>

Reuse the thank_you.html template from the previous example.

Step 5: URL Configuration

In webformapp/urls.py:

from django.urls import path
from .views import feedback_view, thank_you

urlpatterns = [
    path('feedback/', feedback_view, name='feedback'),
    path('thank-you/', thank_you, name='thank_you'),
]

Include in the main urls.py as before.

Step 6: Test Your Form

Run the server and visit http://127.0.0.1:8000/feedback/ to see your model-backed form in action.

You can refer to the screenshot below to see the output:

python web forms
django simple contact form

Read Python Django Import Functions

Tips From My Experience

  • Always use Django’s built-in CSRF protection by including {% csrf_token %} in your forms.
  • Validate your forms server-side, even if you add client-side validation.
  • Use ModelForm when you want to save data directly to the database to reduce boilerplate code.
  • Customize form widgets and labels for a better user experience.
  • For complex forms, consider using Django Crispy Forms to handle styling and layout easily.

Building web forms in Django is intuitive and flexible. Whether you want a simple contact form or a complex data entry system, Django’s form framework has you covered. Start with these methods, and as your project grows, you can explore more advanced features like formsets, AJAX forms, and third-party form libraries.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.