[Answered ]-When a form clean() method detects an error, how do I redisplay empty fields instead of the user's input?

2👍

You need to set the data attribute of the field to ” in your clean method:

class MyForm(forms.Form):
    name = forms.CharField(max_length=50)

    def clean_name(self):
        name = self.cleaned_data['name']
        if name == 'Bob':
            raise forms.ValidationError(u'Name cannot be "Bob"')
            self.data['name'] = ''
        return name

Hope that helps you out.

[Edit]

Here’s an expanded example that is working for me in Django 1.3.

#models.py
from django.db import models

class ContactRequest(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField()
    subject = models.CharField(max_length=255)
    message = models.TextField()
    response_returned = models.BooleanField(default=False)

    def __unicode__(self):
        return self.name


#forms.py
class ContactRequestForm(forms.ModelForm):
    class Meta:
        model = ContactRequest
        exclude = ('response_returned',)

    def clean_email(self):
        email = self.cleaned_data['email']
        if email != 'test@test.com':
            self.data['email'] = ''
            raise forms.ValidationError(u'Email is not test@test.com')
        return email

[Edit]
Here’s an additional example that clears all fields if a condition isn’t met in a clean method. This works for me in Django 1.1.4.

#forms.py
from django import forms

class ContactForm(forms.Form):
    name = forms.CharField(max_length=50)
    email = forms.EmailField()

    def clean(self):
        cleaned_data = self.cleaned_data
        name = cleaned_data.get('name')
        email = cleaned_data.get('email')

        if email == 'test@test.com' and name == 'test':
            for k, _ in self.fields.iteritems():
                self.data[k] = ''
            raise forms.ValidationError(u'Email cannot be "test@test.com" and name cannot be "test"')
        return cleaned_data

Leave a comment