Skip to content

Latest commit

 

History

History
23 lines (12 loc) · 2.43 KB

forms.md

File metadata and controls

23 lines (12 loc) · 2.43 KB

Django Forms

This document collects best practices for working with the Django Forms API.

Contents

HTML5 form validation

Guidance

When using custom Django validators that contradict client-side HTML5 validation, set use_required_attribute to False on your Form.

Background

Most modern browsers now support client-side form validation. They do this by reading the attributes of input elements and providing corresponding feedback to the user when the form is submitted, before a request is sent to the server. For example, if you have a first_name input with the attribute required, most browsers will prevent the form from being submitted to the server until first_name has a value.

The instantaneous feedback provided by client-side validation can be nice for users, but it has the potential to interfere with Django's server-side form validation because it means the automatic client-side validation will happen before any custom server-side validation has a chance to run. To extend the required example, if you have a custom validator that allows first_name to be empty if another field (like last_name) has a value instead, your validator may never run because most browsers will prevent the form from ever being submitted with an empty value for first_name.

This behavior can be particularly confusing because Django will automatically translate form attributes defined in Python into HTML input attributes by default. If the first_name field has the required=True keyword argument set in Python, the corresponding HTML input will have its required attribute set by default.

In general, we recommend that you preserve HTML5 validation wherever possible, since it's more convenient for users. However, if you need to do custom server-side validation that contradicts the default HTML5 validation, you can set use_required_attribute to False on your Form class in order to disable HTML5 form validation.