Bootstrap Modal with WTF

后端 未结 1 626
遥遥无期
遥遥无期 2021-02-06 15:51

I got several user input fields inside Bootstrap Modal and I\'m trying to do some validation before users can submit it.

I\'ve looked around several related articles and

相关标签:
1条回答
  • 2021-02-06 16:31

    First you need to prevent the default action of your submit button which would be to send a post request and close your modal form. You can do this in the click event of the submit button by using event.preventDefault(). Next you would serialize your form data and send the post request via Ajax. If the view function returns "ok" you hide the dialog and reload your current page. Otherwise you will display the hml code with the error messages. Take the following steps:

    1. Give your form an id:

    <form id="editForm" action="{{ url_for('.profile') }}" method="post" name="edit_user" class="form-horizontal">
    

    2. Add Javascript code (needs jQuery)

    $('#uform').click(function(event) {
      event.preventDefault();
      $.post(url, data=$('#editForm').serialize(), function(data) {
        if (data.status == 'ok') {
          $('#editModal').modal('hide');
          location.reload();
        }
        else {
          $('#editModal .modal-content').html(data);
        }
      });
    })
    

    3. Modify your view function

    @main.route('/yourroute', methods=['GET', 'POST'])
    def profile():
        form = YourForm()
        if form.validate_on_submit():
            user = UserEditForm()
            user.first_name = form.first_name.data
            user.last_name = form.last_name.data
            # ...
            db.session.add(user)
            db.session.commit()
            return jsonify(status='ok')
        return render_template('yourtemplate.html', form=form)
    
    0 讨论(0)
提交回复
热议问题