Как отправить данные из модели bootstrap в приложение flask, используя ajax? - PullRequest
0 голосов
/ 21 января 2020

Сообщение об ошибке гласит: werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: браузер (или прокси-сервер) отправил запрос, который этот сервер не может понять. KeyError: 'name'

Я написал следующий код

                   <form id='myform' action="{{url_for('process')}}" method='POST' enctype="multipart/form-data" >
                      <div class="form-group">
                        <label for="message-text" class="col-form-label">Write Comment</label>
                        <textarea class="form-control" id="message-text"></textarea>
                      </div>
                      <div class="modal-footer">
                        <button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
                        <button class="btn btn-warning" type="submit" id="post-btn">Comment</button>
                      </div>
                    </form>

$ (document) .ready (function () {$ ('# myform'). On ('# post -btn ', функция (событие) {

    $.ajax({
        data:{
            name : $('#message-text').val(),
        },
        type: 'POST',
        url : '/process'
    })
    .done(function(data){
        if (data.error){
            $('#TextOutPutId').text(data.error).show();
        }
        else{
            $('#TextOutPutId').text(data.name).show()
        }
        $('#TextOutPutId').text(data.name).show()
        $('#userImage').show()
    });
    // name.send()
    event.preventDefault();
});

});


@app.route('/process',methods=['POST','GET'])
def process():
    # instance of commnet form
    # form = Comments()
    # request form data from model
    if request.method == 'POST':
        recieve_comment =  request.form['name']
        if recieve_comment:
            # if form.validate_on_submit():
            secretsVal = randomString()
            newComment = Song_Comments(comments_text=recieve_comment,unique_val=secretsVal,comment_is_new=True,user_Posts_id=upload.id)
            db.session.add(newComment)
            db.session.commit()
            # writing comment to inerHTML
            jsonify({'name' : recieve_comment})
        else:
            flash(f'field is empty','success')
    return render_template('index.html',title='Home')

...