← Back to Chapters

Creating Forms Using forms.Form & forms.ModelForm

? Creating Forms Using forms.Form & forms.ModelForm

? Quick Overview

Django provides two primary ways to create forms: using forms.Form for custom forms and forms.ModelForm for forms tied to Django models. These forms simplify validation, rendering, and data handling in Django applications.

? Key Concepts

  • forms.Form – Fully custom, not connected to models
  • forms.ModelForm – Auto-generated from Django models
  • Built-in validation and clean data handling
  • Separation of logic and presentation

? Syntax & Theory

forms.Form is ideal when you need complete control over fields and validation logic. forms.ModelForm is preferred when working directly with database models, reducing boilerplate code.

? Code Examples

? View Code Example — forms.Form
# Import Django forms module
from django import forms

# Define a custom contact form
class ContactForm(forms.Form):
name = forms.CharField(max_length=100)
email = forms.EmailField()
message = forms.CharField(widget=forms.Textarea)

# Use this form in a view with validation
? View Code Example — forms.ModelForm
# Import Django forms and model
from django import forms
from .models import Product

# Create a ModelForm linked to Product model
class ProductForm(forms.ModelForm):
class Meta:
model = Product
fields = ['name','price','stock']

# form.save() persists data to database

? Live Output / Explanation

What Happens?

  • Form fields render automatically in templates
  • Validation occurs via form.is_valid()
  • Cleaned data is accessible securely
  • ModelForm saves data directly to database

? Interactive Example

Click the button below to simulate Django form validation:

? Simulated Form Validation
// Simulated client-side validation example
function validateForm() {
    // Logic handles input validation
    alert("Django form validated successfully!");
}
 

? Use Cases

  • Contact forms and surveys
  • Product and order management
  • User profile updates
  • Admin dashboards

? Tips & Best Practices

  • Use ModelForm whenever working with models
  • Always call is_valid() before accessing data
  • Use custom clean_* methods for validation

? Try It Yourself

  • Create a contact form using forms.Form
  • Build a product entry form with ModelForm
  • Add custom field validation logic