Sobes.tech
Junior — Middle

What is the key difference between a standard form and a model-based form in Django?

sobes.tech AI

Answer from AI

A standard form in Django (forms.Form) is created manually, where you explicitly define all fields and their validation. It is not directly linked to database models.

A model-based form (forms.ModelForm) is automatically generated based on a Django model. This simplifies creating forms for creating and editing database records, as fields and validation are inherited from the model.

Example:

from django import forms
from myapp.models import Product

# Standard form
class ContactForm(forms.Form):
    name = forms.CharField(max_length=100)
    message = forms.CharField(widget=forms.Textarea)

# Model-based form
class ProductForm(forms.ModelForm):
    class Meta:
        model = Product
        fields = ['name', 'price', 'description']

Thus, ModelForm saves time and reduces the likelihood of errors when working with models.