Sobes.tech
Junior — Middle

What is the difference between a regular form and a ModelForm in Django?

sobes.tech AI

Answer from AI

In Django, a regular form (forms.Form) is used to create forms with arbitrary fields that are not necessarily linked to database models. It is suitable when you need to collect data that is not directly related to models.

ModelForm (forms.ModelForm) is a form that is automatically generated based on a Django model. It simplifies the creation and validation of forms related to models by automatically creating fields that correspond to the model's fields and allowing easy saving of data to the database.

Example:

from django import forms
from myapp.models import Book

class BookForm(forms.Form):
    title = forms.CharField(max_length=100)
    author = forms.CharField(max_length=100)

class BookModelForm(forms.ModelForm):
    class Meta:
        model = Book
        fields = ['title', 'author']

Thus, ModelForm saves time and reduces the amount of code when working with models.