Menu

Django Forms

Django Forms

Creating Forms

At the intermediate level, users start submitting data back to your application — and that means forms. Django has two approaches:

  • forms.Form — you define every field manually.
  • forms.ModelForm — fields are generated directly from a model. This is what you'll use most often.

ModelForms are preferred because they stay in sync with your model automatically. If you add a field to the model, you only need to add it to the form's fields list — the validation and save logic updates itself.

Form Validation

Django runs validation in a specific order: field-level validation first, then cross-field validation. You can hook into either stage.

Built-in validation happens automatically based on field type — an EmailField rejects non-email strings, a CharField with max_length=100 rejects longer strings.

Handling User Input

A view needs to handle two scenarios: displaying a blank form on GET, and processing a submitted form on POST.

output: