Liz Douglass

Posts Tagged ‘Python

Django form validation – why does the error message always appear?

leave a comment »

Recently I’ve been working on a piece of functionality involving a Django form. The form was defined like this:

class FooForm(forms.Form):
    recipient = forms.CharField(widget=forms.HiddenInput)
    text = forms.CharField(widget=forms.Textarea)

    def clean_message(self):
       data = self.cleaned_data['text']
       message = data.strip(' \t\n\r')
       if (len(message) == 0):
           raise forms.ValidationError("You need to provide some text")
       return data

It was instantiated in a handler method like so:

def bar(request):
    form = FooForm({'recipient' : some.name})
    return render_to_response('my.html', RequestContext(request, {'form': form}))

The validation was working a little too well in that the error message for the text field was appearing when the form was first loaded. The response to a question posted here explains why this was happening. As the Django documentation says, the form has been data bound. This has happened because a data dictionary has been provided as the first argument to the form constructor. This “trigger(s) validation of this input” (Lott, March 17 2009). So the error message is appearing because the text field was not bound with a value that passes validation. As it also says in the Django documentation, the alternative to binding data is to provide dynamic initial values like so:

def bar(request):
    form = FooForm(initial={'recipient' : some.name})
    return render_to_response('my.html', RequestContext(request, {'form': form}}))

Using this, the validation is not immediately triggered and the message only appears if an invalid form has been submitted.

Written by lizdouglass

November 1, 2010 at 9:49 pm

Posted in Uncategorized

Tagged with ,