clear a newforms error indicator

0 views
Skip to first unread message

Robin Becker

unread,
Nov 24, 2008, 7:45:50 AM11/24/08
to django...@googlegroups.com
We have some legacy code that wants to display a partially filled form. One of
the fields is required to be non-empty (it's a captcha) so when re-issuing the
form partially filled I've been doing this

class EmailForm(forms.Form):
.....
vericode = forms.CharField(max_length=5, required=True, label='CODE')


.......

nparams= params.copy()
nparams['vericode'] = ''
ef = EmailFormPangea(nparams)


but I find then that the vericode field is marked as in error when I come to render.

To fix this I tried

ef = EmailFormPangea(nparams)
ef.full_clean()
del ef._errors['vericode']

but this looks fairly clunky. Is there a better way to clear errors or to
indicate that something is not in error during rendering, but should be
considered erroneous on submission?
--
Robin Becker

Malcolm Tredinnick

unread,
Nov 24, 2008, 8:01:58 AM11/24/08
to django...@googlegroups.com
Hi Robin,

Aren't you approaching this from the wrong end. If I understand your
problem correctly, it sounds like you want normal processing except that
the existing value should not be rendered if the form is redisplayed (in
the error processing path). You still want the captcha field to be
validated and everything, right? So blanking it out from the parameters
doesn't sound right.

Instead, you can use a widget for that field that doesn't render its
initial data. django.forms.PasswordInput(render_value=False) is almost
right, except it used an input type of password and not text. But it
gives us the right start. Thinking out loud (thinking in type?), I
suspect something like this will work:

class NoRenderWidget(forms.PasswordInput):
input_type = "text"

class EmailForm(forms.Form):
vericode = forms.CharField(max_length=5, required=True,
label='CODE',
widget=NoRenderWidget(render_value=False))

It's almost midnight here, so my brain's only at about 25%, but that
should give you some clues even if it's not quite right out of the box.
In that way, you don't have to mess around with the parameters and
email_form.is_valid(), etc, will still work as normal. But if you
display the form with anything in the data['vericode'] slot, it won't be
rendered.

An alternative solution, in case the above is really wrong, is to
remember that you can use multiple Form classes in one HTML form. So
create one form class that contains all your normal data that will be
redisplayed and another form class for the vericode. Then, when it comes
time to render, *always* pass in a new (empty) instance of the second
form. Okay, that's only slightly less crufty than your current solution,
but it contains no diving around under the covers.

Best wishes,
Malcolm

Reply all
Reply to author
Forward
0 new messages