python-3.7web2py

Form defined outside "index" function is not accepted (Web2py)


I'm trying to create a form that submits pictures to database using Ajax. The form is defined in function "new_pic" that is neither accepted nor returning errors when a picture is submitted. After clicking submit button the flash message "please fill the form" is returned. Please tell what did I do wrong?

db.py:

db.define_table('input_images', \
Field('action_id', type='string', unique=False, compute=lambda r: action_id ),\
Field('picture', 'upload', uploadfield='picture_file')),\
Field('picture_file', 'blob'),\
primarykey=['action_id']\
)

default.py:

import uuid
action_id = str(uuid.uuid4())
def index:
    return dict()

def new_pic():
    form = SQLFORM(db.input_images, buttons=[])
    if form.process(session=None, formname='test').accepted:
        response.flash = 'form accepted'
    elif form.errors:
        response.flash = 'form has errors'
    else:
        response.flash = 'please fill the form' 
    return dict(form=form)

index.html:

<div class="inner">
    <form id="myform" action="#" enctype="multipart/form-data" method="post">
        {{=LABEL('Upload picture', _for='picture', _class='button-25')}}
        {{=INPUT(_id='picture', _name='picture', _type='file')}}
        <div id="sbmt_picture">
            {{=INPUT(_id='submit_btn', _name='submit_btn', _type='submit', _class='button-25')}}
        </div>
        <input type="hidden" name="_formname" value="test" />
    </form>
</div>
<script>
    jQuery('#myform').submit(function() {
        ajax('{{=URL('new_pic')}}', ['picture'], 'trgt');
        return false;
    });
</script>
<div id="trgt"></div>

Solution

  • The problem was in the JS. I just found another kind of this element here: https://stackoverflow.com/a/28386477/13128766

    That works for me:

    <script>
        jQuery(document).on("submit", "form", function(event)
        {
            event.preventDefault();
            jQuery.ajax({
                url: "{{=URL('new_pic')}}",
                type: jQuery(this).attr("method"),
                dataType: "JSON",
                data: new FormData(this),
                processData: false,
                contentType: false,
                success: function (data, status)
                {
                },
                error: function (xhr, desc, err)
                {
                }
            });
        });
    </script>