Episode 10 of 13

Form Errors

Learn about Form Errors

How Django Validates Forms

When you call form.is_valid() in your view, Django runs all built-in field validators (required, max_length, email format) and any custom validation methods you have defined. If validation fails, the form object is populated with error messages for each field that has a problem.

Displaying Field-Level Errors

In your form template, check each field for errors using the field.errors attribute. If errors exist, display them in a small text element below the input field. Style these error messages with a red or error color so they stand out visually. Each error is a list, so loop through them in case a field has multiple validation issues.

Non-Field Errors

Some validation errors are not specific to a single field. For example, a custom clean() method might validate that a combination of fields is correct. These errors live in form.non_field_errors and should be displayed at the top of the form, above all the individual fields.

Returning the Form with Errors via HTMX

When the HTMX POST request submits invalid data, the view should return the form template with the form object that now contains error messages. HTMX will swap this HTML into the modal, replacing the original form. The user sees the same form they submitted, but now with inline error messages next to the fields that need attention.

Styling Error States

Use DaisyUI's "input-error" class to add a red border to fields that have validation errors. Add "text-error" class to the error message text. This provides a clear visual hierarchy that draws the user's eye to exactly what needs to be fixed.

Preserving User Input

When Django re-renders a form with errors, it automatically preserves the data the user originally entered. This means users do not have to retype their information. They can simply correct the specific fields that were flagged and resubmit.