Django Form Non Field Errors
August 29, 2010
You can add errors to a Django form without attaching them to a field. This example is taken from the django-registration source:
def clean(self): if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data: if self.cleaned_data['password1'] != self.cleaned_data['password2']: raise forms.ValidationError('You must type the same password each time') return self.cleaned_data
In order for this field to be shown on the form, you need to add {{form.non_field_errors}} to the template:
<form method="post" action="."> <h1>Account Registration</h1> <p>Please fill in the details below to create your new account.</p> <table> <tr><th>Username:</th><td>{{form.username.errors}} {{form.username}} (spaces not allowed)</td></tr> <tr><th>Email Address:</th><td>{{form.email.errors}} {{form.email}}</td></tr> <tr><th>Password:</th><td>{{form.password1.errors}} {{form.password1}}</td></tr> <tr><th>Password (again):</th><td>{{form.password2.errors}} {{form.password2}}</td></tr> <tr><td> </td><td>{{form.non_field_errors}}<input type="submit" value="Register" /></td></tr> </table> </form>
This example will show the non field errors just above the submit message.