简体   繁体   中英

How to allow multiple form submissions in web2py?

Gratefully web2py automatically prevents multiple form submission by using a hidden _formkey value. In most cases, when the form is submitted the page is loaded again so a new key is generated. However, since I'm submitting my form using web2py's ajax function, I get the result without refreshing the page, thus the form key remains the same and later submissions are not possible.

How should I address this situation?

You might consider creating a separate action for the form and loading the entire form into the page via an Ajax component:

def index():
    form_component = LOAD('default', 'form.load', ajax=True)
    return dict(form_component=form_component)

def form():
    form = FORM(...).process()
    return dict(form=form)

In the index.html view, you would then include the component via {{=form_component}} , and in the form.load view, you would include the form itself via {{=form}} (note, the form.load view should not extend the layout, as it is will ultimately be inserted inside the index.html page via Ajax).

Now the entire form will be loaded via Ajax, and it will automatically be submitted via Ajax, with a new form also returned via Ajax (so you don't need to write any Javascript code at all).

Alternatively, if you want to stick with your current approach, you can have the controller return the entire form in response to the Ajax request, and set the target argument of the ajax() function to the id of the div that contains the form. In that case, upon completion of the Ajax request, the entire form will be replaced by a new form (which will have a new _formkey).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM