代码之家  ›  专栏  ›  技术社区  ›  XJTLU media

在python中的HTML文件之间跳转

  •  0
  • XJTLU media  · 技术社区  · 3 年前

    我在一页上有一个表格,我想提交到另一页。我不知道如何创建指向第二个页面的链接。

    项目布局:

    Fileserver/
        config.py
        requirements.txt
        run.py
        setup.py
        app/
            __init__.py
            static/
                css/
                img/
                js/
            templates/
                formAction.html
                formSubmit.html
                index.html
    

    __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)
    

    index.html :

    <!DOCTYPE html>
    <html lang="en">
    <body>
        <ul>
            <li><a href="/formSubmit.html">Check Out This Form!</a>
        </ul>
    </body>
    </html>
    

    我可以在localhost上看到这个页面:5000/没有问题。

    我也尝试过:

    <a href="{{ url_for('templates', 'formSubmit") }}"></a>
    

    以及:

    <a href="{{ url_for('formSubmit') }}"></a>
    

    我错过了什么?

    0 回复  |  直到 10 年前
        1
  •  70
  •   davidism    6 年前

    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')
    

    templates/index.html :

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

    templates/cool_form.html :

    <!doctype html>
    <html>
    <body>
        <form method="post">
            <button type="submit">Do it!</button>
        </form>
    </html>
    

    我不知道你的表单和路由实际上是做什么的,所以这只是一个例子。


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

    url_for('static', filename='a_picture.png')
    
        2
  •  0
  •   Michael mikey McLean    4 年前

    所以我刚刚发现,如果我不将href括在括号中,它就会工作,我还创建了一个链接返回页面

    @app.route('/blog')
    def blog():
        return '<h1>These are my thoughts on <a href=blog/2020/dogs>dogs</a></h1>'
    
    @app.route('/blog/2020/dogs')
    def blog2():
        return '<h3>these are my dogs <a href=../../blog>home</a></h3>'