Joshua
Joshua

Reputation: 547

What is going wrong during web2py form validation?

I have a fairly simple web2py form with a few validators like, IS_FLOAT_IN_RANGE(...) on its fields. When I try to submit the form when it has fields which don't pass validation the form will fail the first validation, but will not report there were any errors. If I then resubmit the same form, validation will fail once again.

Worse, if I submit valid information, it will not submit unless I submit the same form twice. The view is simply {{=form}}

The controller looks like this:

@auth.requires_login()
def addpipelines():
    form = FORM(INPUT(_name="type", _value="insert", _type="hidden"),
            INPUT(_name="project", _value="Project", requires=IS_NOT_EMPTY()),
            INPUT(_name="value", _value="Value", requires=IS_FLOAT_IN_RANGE(-1e100, 1e100)),
            BR(), BR(),
            INPUT(_type="submit", _value="Add"),
           _method="POST")

    if request.post_vars.type == "insert" and form.process().accepted:
       request.post_vars["blub"] = "blargh"

    return dict(form=form)

```

Upvotes: 0

Views: 943

Answers (1)

Anthony
Anthony

Reputation: 25536

if request.post_vars.type == "insert" and form.process().accepted:

Note, in Python, the part of the above expression after the and will not be evaluated when the part before the and is false, so form.process() will only get called when the form is submitted. However, for form processing to work properly, form.process() must also be called when the form is first created (because it adds a hidden _formkey field and checks its value with a copy of the formkey placed in the session in order to protect against CSRF attacks and double submission). Instead, try switching the order of the conditions:

if form.process().accepted and request.post_vars.type == "insert":

Upvotes: 3

Related Questions