Python Flask:提交表单后重定向到同一页面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41270855/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 00:43:20  来源:igfitidea点击:

Flask: redirect to same page after form submission

pythonflask

提问by user3629892

I have two forms on in my template: one, to post something and the second, to activate file deletion on the server:

我的模板中有两种形式:一种是发布内容,另一种是在服务器上激活文件删除:

<div style="margin-bottom:150px;">
    <h4>Delete</h4>
    <form method="post" action="/delete">
        <div class="form-group">
            <input type="hidden" name="delete_input"></input>
        </div>
        <button type="submit" class="btn btn-danger" id="btnSignUp">Delete</button>
    </form>
</div>

<div style="margin-bottom:150px;">
    <h4>URLs</h4>
    <form method="post" action="/">
        <div class="form-group">
            <textarea class="form-control" rows="5" id="urls" name="url_area"></textarea>
        </div>
        <button type="submit" class="btn btn-primary" id="btnSignUp">Urls</button>
    </form>
</div>

My app.pylooks like this:

我的app.py看起来像这样:

@app.route("/")
def main():
    return render_template('index.html')


@app.route('/', methods=['POST'])
def parse_urls():
    _urls = request.form['url_area'].split("\n")
    image_list = get_images(_urls)
    return render_template('index.html', images=image_list)


@app.route('/delete', methods=['POST'])
def delete_images():
    file_list = [f for f in os.listdir("./static") if f.endswith(".png")]
    for f in file_list:
        os.remove("./static/" + f)
    image_list = []
    conn = sqlite3.connect('_db/database.db')

    curs = conn.cursor()
    sql = "DROP TABLE IF EXISTS images"
    curs.execute(sql)
    conn.commit()
    conn.close()
    return render_template('index.html', images=image_list)

Two issues:

两个问题:

  • I get the form resubmission message when I reload the page after submitting the form
  • I would like to have one url for everything
  • 我在提交表单后重新加载页面时收到表单重新提交消息
  • 我想要所有内容的 url

The way I see it, I need so use redirects to avoid the duplicate submission and after calling delete, I need to redirect to index.

在我看来,我需要使用重定向来避免重复提交,在调用 delete 后,我需要重定向到 index.html 。

How can I do this correctly?

我怎样才能正确地做到这一点?

I know about redirectand url_for, but how do I redirect to the same page?

我知道redirectand url_for,但是如何重定向到同一页面?

回答by metmirr

Change form action to action="{{url_for('delete_images')}}". And for redirection you can use code below:

将表单操作更改为action="{{url_for('delete_images')}}". 对于重定向,您可以使用以下代码:

@app.route('/delete', methods=['POST'])
def delete_images():
    if request.method == 'POST':
        # do your work here
        return redirect(url_for('delete_images'))

回答by Mahmoud

You can get the currently requested URL by request.url:

您可以通过以下方式获取当前请求的 URL request.url

So, to redirect to the same page use:

因此,要重定向到同一页面,请使用:

redirect(request.url)

回答by Jessie Danquah

As archer said below:

正如弓箭手在下面所说:

return redirect(request.referrer)

This is useful when you have a button that uses a route to perform a given function when it is clicked - you don't want to return the user to the URL for that button - you want to return the user to the URL that the button route was referred by, i.e. the page the user was on when they clicked the button.

当您有一个按钮在单击时使用路由执行给定功能时,这很有用 - 您不想将用户返回到该按钮的 URL - 您想将用户返回到该按钮的 URL路由被引用,即用户单击按钮时所在的页面。

However, as Mahmoud said:

然而,正如马哈茂德所说:

redirect(request.url)

This is perfect if you perform a function on a page that doesn't use routes or special URLs or anything like that. It essentially just refreshes the page.

如果您在不使用路由或特殊 URL 或类似内容的页面上执行功能,这将是完美的。它本质上只是刷新页面。

回答by tim

One way is set the current url by Javascript in your form. like:

一种方法是在表单中通过 Javascript 设置当前 url。喜欢:

<form method="post" action="/delete">
    <div class="form-group">
        <input type="hidden" name="delete_input"></input>
    </div>
    <input type=hidden class=current_url value="" name=current_url>
    <button type="submit" class="btn btn-danger" id="btnSignUp">Delete</button>
</form>

And set the hidden input value by JS, like,

并通过 JS 设置隐藏的输入值,例如,

function get_current_url() {
    var url=window.location.href;
    return url
}

$(window).on('load',function(){
    var current_url=document.getElementsByClassName('current_url')[0];
    current_url.value=get_current_url();

})

At server, redirectto the url that post data

在服务器上,redirect到发布数据的 url

回答by archer

This worked perfectly for me, in last line:

这对我来说非常有效,在最后一行:

return redirect(request.referrer)