烧瓶表格提交不执行任何操作

时间:2018-06-22 16:47:19

标签: python jquery flask flask-wtforms

单击提交按钮实际上没有任何作用。提交空白表单将触发对必填字段的验证,但是按要求填写表单会导致表单不提交/提交按钮不起作用。模板具有CSRF_Token,“提交”按钮位于form标记中,并且form标记具有指向正确方向的action属性。 Chrome不会发出任何错误,因此我只能继续操作。

views.py

@blueprint.route("register/", methods=['GET', 'POST'])
def register():
    """Renders register page."""
    form = RegisterForm()
    if request.method == 'POST':
        if not form.validate_on_submit():
            return render_template('main/register.html', page_title="Service Registration",
                                   form=form, form_success=False, media_types=current_app.config["ACCEPTED_"
                                                          "MEDIA_TYPE"])
        company, err = get_company(form.organization.data)
        if err:
            company, err = create_company(form.organization.data)
            if err:
                return render_template('main/register.html', page_title="Service Registration",
                                       form=form, form_success=False, message=err, media_types=current_app.config["ACCEPTED_"
                                                          "MEDIA_TYPE"])
        customer, err = get_or_create_customer(
            form.first_name.data + " " + form.last_name.data, form.email.data,
            company_id, form.position.data, phone_number
        )
        if err:
            return render_template('main/register.html', page_title="Service Registration",
                                   form=form, form_success=False, message=err, media_types=current_app.config["ACCEPTED_"
                                                          "MEDIA_TYPE"])
        if err:
            return render_template('main/register.html', page_title="Service Registration",
                                   form=form, form_success=False, message=err, media_types=current_app.config["ACCEPTED_"
                                                          "MEDIA_TYPE"])
        else:
            return render_template('main/register.html', page_title="Service Registration",
                                   form=form, form_success=True, message=success_msg, media_types=current_app.config["ACCEPTED_"
                                                          "MEDIA_TYPE"])
    return render_template('main/register.html', page_title="Service Registration",
                           form=form, media_types=current_app.config["ACCEPTED_"
                                                          "MEDIA_TYPE"])


@blueprint.route("register/", methods=['POST'])
def upload_register():
    """Handles file upload POSTs."""
    first_name = request.form.get("first_name")
    last_name = request.form.get("last_name")
    name = request.form.get("first_name") + " " + request.form.get("last_name")
    email = request.form.get("email")
    filename = request.form.get("filename")
    file_type = request.form.get("file_type")

    if filename == '':
        response = make_response("No selected file")
        return response, 400
    if check_file_type(file_type):
        filename = clean_filename(filename)
        filename = secure_filename(filename)
        filename = unique_filename(filename)
        response = generate_presigned_post(filename, file_type)
        # CREATE DB REFERENCE
        url = "http://nevcodocs.s3.amazonaws.com/Uploads/{}".format(filename)
        instance = CustomerFileUpload.query.filter_by(url=url).first()
        if not instance:
            instance = CustomerFileUpload(url=url, email=email, name=name)
            db.session.add(instance)
            db.session.commit()
        else:
            instance.update(created_at=datetime.utcnow())
        return response, 200
    else:
        response = make_response("Invalid file type")
        return response, 500

javascript / jquery

// Enables/disables form submission and colors button accordingly
        var enableSubmit = function(enabled) {
            if (enabled) {
                $('#submit_ticket').removeAttr('disabled');
                $('#submit_ticket').removeAttr('style');
            } else {
                $('#submit_ticket').attr('disabled', 'disabled');
                $('#submit_ticket').attr('style', 'background-color: rgba(244, 121, 32, 0.5) !important; border-color: rgba(244, 121, 32, 0.25) !important;');
            }
        };

$('#ticket-form').submit(function(event) {
            enableSubmit(false);
            showSpinner(true);
            var validated = true;

            var didSelectFile = true;
            didSelectFile = validateField('#upload') && validated;

            validated = didSelectFile && validated;

            if (didSelectFile && !validateContentType()) {
                $('invalid-upload-alert').show();
                validated = false;
            } else {
                $('#invalid-upload-alert').hide();
            }
            if (validated) {
                $('#filename').val($('#upload').val());
                $('#file_type').val($('#upload').prop('files')[0].type);
                $.ajax({
                    type: 'POST',
                    url: '/register/',
                    data: $('#ticket-form').serialize()
                }).done(function(data) {
                    var formData = new FormData();
                    for (var key in data.data.fields) {
                        formData.append(key, data.data.fields[key]);
                    }
                    formData.append('file', $('#upload').prop('files')[0]);
                    var req = new XMLHttpRequest();
                    req.onload = function() {
                        showSpinner(false);
                        $('#ticket-form-failed').removeClass("support-form-show");
                        $('#ticket-form-failed').addClass("support-form-hide");
                        $('#ticket-form').removeClass("support-form-show");
                        $('#ticket-form').addClass("support-form-hide");
                        $('#ticket-form-success').removeClass("support-form-hide");
                        $('#ticket-form-success').addClass("support-form-show");
                    };
                    req.onerror = function() {
                        showSpinner(false);
                        $('#ticket-form-failed').removeClass("support-form-hide");
                        $('#ticket-form-failed').addClass("support-form-show");
                    };
                    req.open('POST', data.url);
                    req.send(formData);
                }).fail(function(err) {
                    showSpinner(false);
                    $('#ticket-form-failed').removeClass("support-form-hide");
                    $('#ticket-form-failed').addClass("support-form-show");
                });
            } else {
                showSpinner(false);
                enableSubmit(true);
            }
            {% endif %}
            if (!validated) {
                event.preventDefault();
                showSpinner(false);
                enableSubmit(true);
            }
        });

1 个答案:

答案 0 :(得分:1)

您写的内容看起来真的很复杂,为什么不尝试简单的东西-

$request->header('User-Agent');

在您的 views.py connect.html 表单中,只需编写-

@app.route("/connect",methods=['GET','POST'])
def connect():
    if request.method=='GET':
        return render_template('connect.html')
    if request.method=="POST":
        return render_template('Thankyou.html',name=request.form['name])

最后一页 Thankyou.html 看起来像这样-

<form name="connect" method="post" action="{{ url_for('connect') }}">
        <input class="t1" type="text" id="email" name="email" placeholder="Your Email ID">
        <input class="t2" type="text"  id="name" name="name" placeholder="name">
        <button class="btn btn-primary but" type="submit">Send</button>
    </form>