What is the difference between a Django Form and a ModelForm, and how does validation work?
A Form defines its fields explicitly and is not tied to a model — a search box or a contact form. A ModelForm generates its fields from a model, and gains a save() method that creates or updates the instance.
class BookForm(forms.ModelForm):
class Meta:
model = Book
fields = ['title', 'author', 'published_on']Note: Always list fields explicitly. Using __all__ means that any field added to the model later becomes editable through this form, which is a real and frequently exploited security hole.
Validation runs in a fixed order when you call is_valid():
to_pythonconverts the raw string to the right Python type.validateapplies field-level rules such as required and choices.- Validators attached to the field run next.
clean_<fieldname>— your per-field logic. It must return the cleaned value.clean()— form-wide logic, the only place you can compare two fields, such as checking that an end date is after a start date. RaiseValidationErrorhere for cross-field errors.
Errors collect in form.errors rather than raising, so all problems are shown to the user at once.





