← Back to Django, page 1

django-0009 · Easy fresher

What is the difference between a Django Form and a ModelForm, and how does form validation work?

A Form declares its fields by hand; a ModelForm builds its fields from a model and can save an instance. Calling is_valid() runs each field's to_python and validators, then clean_<field>() methods, then clean() for cross-field rules. Valid data ends up in cleaned_data and errors in form.errors.

Full answer

Forms turn untrusted input (usually request.POST) into clean Python values and readable error messages.

forms.Form is for input that does not map directly to one model, such as a search box or a contact form. You declare each field yourself.

forms.ModelForm reads fields from a model:

python
class StudentForm(forms.ModelForm):
    class Meta:
        model = Student
        fields = ["name", "marks"]

It copies field types, max_length, choices and blank rules, and adds form.save() which creates or updates the instance. Always list fields explicitly; fields = "__all__" can expose fields you add later, such as is_admin.

Validation order when you call form.is_valid():

  1. For each field: to_python() converts the string ("85" to 85), then field validators run.
  2. clean_<fieldname>() runs for extra rules on one field. It must return the cleaned value.
  3. clean() runs once for rules involving several fields. Use self.add_error(field, msg) or raise ValidationError.
  4. For ModelForm, model validation (full_clean on the instance, including unique checks) runs too.

Results: form.cleaned_data holds valid values, form.errors holds messages per field, and form.non_field_errors() holds errors from clean().

Typical view: if POST and valid, save and redirect; otherwise render the form again with errors. form.save(commit=False) returns an unsaved instance so you can set extra fields (like the logged-in teacher) before saving.

python
import sys
import types

import django
from django.conf import settings

# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__

settings.configure(
    SECRET_KEY="demo-only-key-not-for-production",
    ALLOWED_HOSTS=["testserver"],  # the host name used by Django's test client
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

from django import forms
from django.db import models, connection


class Student(models.Model):
    name = models.CharField(max_length=30)
    marks = models.IntegerField()
    max_marks = models.IntegerField(default=100)

    class Meta:
        app_label = "school"


with connection.schema_editor() as editor:
    editor.create_model(Student)


class StudentForm(forms.ModelForm):
    class Meta:
        model = Student
        fields = ["name", "marks", "max_marks"]

    def clean_name(self):
        return self.cleaned_data["name"].strip().title()

    def clean(self):
        data = super().clean()
        if data.get("marks") is not None and data.get("max_marks") and data["marks"] > data["max_marks"]:
            self.add_error("marks", "Marks cannot be more than max marks.")
        return data


good = StudentForm({"name": "  neha singh ", "marks": "88", "max_marks": "100"})
print(good.is_valid(), good.cleaned_data)
saved = good.save()
print(saved.pk, saved.name)

bad = StudentForm({"name": "Arjun", "marks": "120", "max_marks": "100"})
print(bad.is_valid(), bad.errors.get_json_data())

Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): True {'name': 'Neha Singh', 'marks': 88, 'max_marks': 100} 1 Neha Singh False {'marks': [{'message': 'Marks cannot be more than max marks.', 'code': ''}]}

Key points

  • Form = fields by hand, ModelForm = fields from a model + save()
  • Order: to_python -> validators -> clean_<field> -> clean() -> model checks
  • cleaned_data has typed values; errors has messages
  • List fields explicitly in ModelForm Meta
  • save(commit=False) lets you set extra fields first

Common mistakes

  • Using fields = '__all__' and exposing sensitive fields
  • Forgetting to return the value from clean_<field>()
  • Reading request.POST directly after validation instead of cleaned_data
  • Rendering a success page on POST instead of redirecting

Follow-ups

  • How do you show a form with initial values for editing an existing record?
  • Where would you validate that a roll number is unique per class?
  • What are formsets used for?

Tips

  • Recite the validation order, it is a favourite follow-up
  • Mention commit=False with a concrete reason
  • Point out the security issue with __all__