简体   繁体   English

如何使用Flask为POST请求添加确认对话框?

[英]How to add confirmation dialog for POST request with Flask?

First time with Flask. 第一次使用Flask。 I am trying to add a confirmation dialog for a form but only on certain conditions. 我正在尝试为表单添加确认对话框,但仅在某些条件下才可以。 So I am not able to do this on the client side. 因此,我无法在客户端执行此操作。 I was able to add it for the GET request but I wasn't able to do it for POST requests because I need to pass around the form data. 我能够为GET请求添加它,但无法为POST请求添加它,因为我需要传递表单数据。 Here is what I have done. 这是我所做的。

This is the form submit of the main form. 这是主表单的表单提交。 On Cancel, it just refreshes the data on the current page by doing get request for config. 在“取消”上,它只是通过获取配置请求来刷新当前页面上的数据。 But on Apply, it issues a POST request to /confirm route 但是在Apply上,它向/ confirm路由发出POST请求

main.html main.html

<form class="module-form pure-form pure-form-aligned" autocomplete="off" id="uguu">
<fieldset>
   <div id="export-settings" class="module-block insight-border">
         <div class="pure-control-group">
            {{ form.export_server.label }}
            {{ form_input(form.export_server, maxlength=255) }}
         </div> 
         <div class="pure-control-group">
            {{ form.export_port.label }}
            {{ form_input(form.export_port) }}
         </div>
         <div class="submit-button-group">
            <button class="pure-button pure-button-primary" type="submit" 
                    formaction="confirm" formmethod="post">Apply</button>
            <button class="pure-button pure-button-primary cancel" type="submit"
                    formaction="config" formmethod="get">Cancel</button>
          </div>
    </div>
</fieldset>
</form>

This is the code segment in the flask server 这是烧瓶服务器中的代码段

@config_page.route("/config", methods=["GET", "POST"])
def config():
    if request.method == "POST":
         return post_config() #Uses request.form
    return get_config()


@config_page.route("/confirm", methods=["POST"])
def confirm():
    with ClassA() as class_a:
        class_a.load()
        #Need to show the confirmation only on this condition
        if class_a.is_val_x and request.form['is_val_x'] == 'on':
            #Is this the right way to go about it?
            return render_template('confirm.html', form=request.form ) 

    return redirect(url_for('.config',form=request.form),code=307) 

An finally the code segment in confirm.html. 最后是Confirm.html中的代码段。 The get request works fine but I am not sure how to post the form data from the flask /confirm route to /config. get请求工作正常,但是我不确定如何将烧瓶中的表单数据/确认路由发布到/ config。 I am not even sure if this is the right way to do it. 我什至不确定这是否是正确的方法。 Any help would be really welcome? 真的会有任何帮助吗? Any solution possible in jQuery or javaScript is also welcome. 也欢迎使用jQuery或javaScript中的任何解决方案。

<div> Are you sure kind of dialog? </div>
<form>
   <button class="pure-button pure-button-primary deny" type="submit"  
                formaction="config" formmethod="get">Cancel</button>

   <button class="pure-button button-warning confirm" type="submit" 
                formaction="config" formmethod="post">Confirm</button>
</form>

As you have said the get request works fine. 正如您所说的,get请求工作正常。 So you must be seeing the template confirm.html. 因此,您必须看到模板confirm.html。 Edit the form tag. 编辑表单标签。

<form method="POST" action="./config">
<button class="pure-button pure-button-primary deny" type="submit"  
            formaction="config" formmethod="get">Cancel</button>

<button class="pure-button button-warning confirm" type="submit" 
            formaction="config" formmethod="post">Confirm</button>
</form>

Now once you click confirm on code segment , you can by printing request data debug the form fields. 现在,一旦在代码段上单击“确认”,就可以通过打印请求数据来调试表单字段。

@config_page.route("/config", methods=["GET", "POST"])
def config():
if request.method == "POST":
 print(request)
 return post_config() #Uses request.form
return get_config()

If you want to submit form using ajax/jquery, you can do this. 如果要使用ajax / jquery提交表单,可以执行此操作。

<script type="text/javascript">
  $('.confirm').click(function (e) {
    e.preventDefault();
    $.ajax({
        url: "./config",
        type: 'post',
        dataType: "json",
        data: {
            search: request.term, request: 1
        },
        success: function (data) {
            response(data);
        }
    });
   }
</script>

Well in the flask way of doing you should have separate forms.py file where you would build all your forms and use jinja2 templating. 按照烧瓶的方式,您应该有单独的forms.py文件,您可以在其中构建所有表单并使用jinja2模板。

How I would do something like that is by creating these things: 我将如何做这些事情是通过创建以下内容:

1. app/forms.py 1. app / forms.py

from flask_wtf import FlaskForm
from wtforms import StringField, BooleanField, SubmitField
from wtforms.validators import DataRequired

class ConfigForm:
    conf1 = StringField('Config 1', validators=[DataRequired()])
    conf2 = StringField('Config 2', validators=[DataRequired()])
    confirm = BooleanField('Cnfirm')
    submit = SubmitField('Submit')

2. app/templates/config.py 2. app / templates / config.py

<html>
<body>
    <h1>Config</h1>
    <p>
        {{ form.conf1.label }}<br>
        {{ form.conf1(size=(42) }}
        {% for error in form.conf1.errors %}
        <span style="color: red;">[{{ error }}]</span>
        {% endfor %}
    </p>
    <p>
        {{ form.conf2.label }}<br>
        {{ form.conf2(size=(42) }}
        {% for error in form.conf2.errors %}
        <span style="color: red;">[{{ error }}]</span>
        {% endfor %}
    </p>
    <p>{{ form.submit() }}</p>
</body>
</html>

3. app/routes.py 3. app / routes.py

from flask import Flask render_template, redirect, url_for, request
from forms import ConfigForm


app = Flask(__name__)

@app.route('/config/<confirm>', methods=['GET', 'POST'])
def config(confirm):
    form = ConfigForm()
    if form.validate_on_submit():
        if form.validate_on_submit():
            db.get.value1.for.form = form.conf1.data
            db.get.value2.for.form = form.conf2.data
            if confirm:
                db.get.value3.form = form.confim.data

            db.session.commit()

            flash('You\'r changes have been saved!')
            return redirect(url_for('config'))
        elif request.method == 'GET':
            form.conf1.data = db.get.value1.for.form
            form.conf2.data = db.get.value2.for.form

    return render_template('config.html', form=form)


@app.route('/')
def index():
    confirm = True
    return redirect(url_for('config', confirm))

What I'm doing here is that I'm creating config page where data is loaded from database and in case the user wishes to update the data in the post method I will update the data to the database. 我在这里所做的是,我正在创建配置页,该页上是从数据库加载数据的,如果用户希望使用post方法更新数据,我将把数据更新到数据库。

In my exaple if user enter to the /index page it redirects to cinfig page and passes the confim = True that will be updated together with post method without any user action needed. 在我的示例中,如果用户进入/ index页,它将重定向到cinfig页并传递confim = True,它将与post方法一起更新,而无需任何用户操作。

I hope this example might atleast put you on the road to the solution you need. 我希望这个示例至少能使您走上所需解决方案的道路。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 仅当用户选择特定单选按钮时,才显示确认/对话框并在该对话框中发送 POST 请求 - Show a confirmation/dialog and send POST request within that dialog box only if the user select specific radio button Ajax POST之前的确认对话框/ SweetAlert对话框 - Confirmation dialog/SweetAlert dialog before Ajax POST 如何添加确认对话框? 如果按是,则按钮将下载,如果不是,则按钮将取消 - How to add Confirmation dialog? If press yes, the button will download, if no, the button will cancel AJAX请求后的JQuery确认对话框 - JQuery confirmation dialog after AJAX request 如果确认对话框为“取消”,则中止Ajax请求 - Aborting an Ajax request if confirmation dialog is “Cancel” 如何做这种确认对话? - How to do this kind of confirmation dialog? Flask - 收听POST请求 - Flask - Listen to POST request 在将ajax请求发送到服务器之前,如何实现确认对话框/框? - How do i implement a confirmation dialog/box before ajax request is send to server? 如何在露天共享中批准工作流的审阅步骤之前添加确认对话框 - How to add a confirmation dialog before approving a review step of a workflow in alfresco share 如何以html5格式向提交按钮添加确认对话框? - How can I add confirmation dialog to a submit button in html5 form?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM