Basic Django Form Example

A snippet showing how to build and render a basic Django form.


# forms.py

from django import forms

class ContactForm(forms.Form):
    name = forms.CharField(max_length=100, label="Your name")
    email = forms.EmailField(label="Email address")
    message = forms.CharField(widget=forms.Textarea(attrs={"rows": 4}), label="Message")

    # Optional: example extra validation
    def clean_email(self):
        email = self.cleaned_data["email"]
        if not email or "@" not in email:
            raise forms.ValidationError("Please provide a valid email.")
        return email
      

# views.py

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

def contact_view(request):
    if request.method == "POST":
        form = ContactForm(request.POST)
        if form.is_valid():
            # Do something with form.cleaned_data (send email, save to DB, etc.)
            messages.success(request, "Thanks! We received your message.")
            return redirect("contact")  # replace with your URL name
    else:
        form = ContactForm()

    return render(request, "contact.html", {"form": form})
  

# templates/contact.html

{% load static %}
<div class="row justify-content-center">
  <div class="col-md-8 col-lg-6">
    <form method="post" novalidate class="bg-white border rounded p-3">
      {% csrf_token %}
      <h5 class="mb-3">Contact us</h5>

      <div class="mb-3">
        <label class="form-label">Name</label>
        {{ form.name|as_widget:attrs }}
      </div>

      <div class="mb-3">
        <label class="form-label">Email</label>
        {{ form.email|as_widget:attrs }}
      </div>

      <div class="mb-3">
        <label class="form-label">Message</label>
        {{ form.message|as_widget:attrs }}
      </div>

      {% if form.errors %}
        <div class="alert alert-danger" role="alert">
          Please fix the errors below and try again.
        </div>
      {% endif %}

      <button type="submit" class="btn btn-primary w-100">Send</button>
    </form>
  </div>
</div>

  

# urls.py 

from django.urls import path
from .views import contact_view

urlpatterns = [
    path("contact/", contact_view, name="contact"),
]
  
Explanation:
  • Use forms.Form for simple, non-model-backed forms.
  • Validate inputs with built-in field types and clean_FIELD methods.
  • Use Django messages framework to give user feedback after POST.
  • Category Forms & Validation
  • Total Views 514
  • Last Modified 21 September, 2025
  • Tags #forms #basics #input #validation
Previous snippet
Model Meta Options
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.