如何创建指向另一个html页面的链接?

Ric*_*ael 12 python flask

我在一个页面上有一个表单,我想提交到另一个页面.我无法弄清楚如何创建到第二页的链接.

项目布局:

Fileserver/
    config.py
    requirements.txt
    run.py
    setup.py
    app/
        __init__.py
        static/
            css/
            img/
            js/
        templates/
            formAction.html
            formSubmit.html
            index.html
Run Code Online (Sandbox Code Playgroud)

__init__.py:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
    ip = request.remote_addr
    return render_template('index.html', user_ip=ip)
Run Code Online (Sandbox Code Playgroud)

index.html:

<!DOCTYPE html>
<html lang="en">
<body>
    <ul>
        <li><a href="/formSubmit.html">Check Out This Form!</a>
    </ul>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

我可以在localhost:5000 /看到页面没有问题.

我也尝试过:

<a href="{{ url_for('templates', 'formSubmit") }}"></a>
Run Code Online (Sandbox Code Playgroud)

以及:

<a href="{{ url_for('formSubmit') }}"></a>
Run Code Online (Sandbox Code Playgroud)

我错过了什么?

dav*_*ism 29

url_for生成应用程序中定义的路由的URL.没有(或者可能不应该是)提供的原始html文件,特别是在templates文件夹之外.每个模板都应该是Jinja呈现的内容.您要显示或发布表单的每个位置都应由应用程序上的路径处理和生成.

在这种情况下,您可能希望有一个路由同时在GET上呈现表单并在POST上处理表单提交.

__init__.py:

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

app = Flask(__name__)

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

@app.route('/cool_form', methods=['GET', 'POST'])
def cool_form():
    if request.method == 'POST':
        # do stuff when the form is submitted

        # redirect to end the POST handling
        # the redirect can be to the same route or somewhere else
        return redirect(url_for('index'))

    # show the form, it wasn't submitted
    return render_template('cool_form.html')
Run Code Online (Sandbox Code Playgroud)

templates/index.html:

<!doctype html>
<html>
<body>
    <p><a href="{{ url_for('cool_form') }}">Check out this cool form!</a></p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

templates/cool_form.html:

<!doctype html>
<html>
<body>
    <form method="post">
        <button type="submit">Do it!</button>
    </form>
</html>
Run Code Online (Sandbox Code Playgroud)

我不知道你的表格和路线实际上做了什么,所以这只是一个例子.


如果需要链接静态文件,请将它们放在static文件夹中,然后使用:

url_for('static', filename='a_picture.png')
Run Code Online (Sandbox Code Playgroud)