【问题标题】:Flask url_for() pass multiple parameters but only show one in the blueprint route?Flask url_for() 传递多个参数但在蓝图路由中只显示一个?
【发布时间】:2021-11-02 21:23:23
【问题描述】:

我是 Flasks 和 Jinja 模板的新手。我正在尝试将我的 html 文件中的两个参数传递给蓝图路由。我正在传递可用于查询数据库和位置字段的唯一 ID。我只希望位置字段显示在 url 中。

@trips_blueprint.route('/mytrips/<selected_trip_location>',methods=['GET','POST'])
@login_required
def show_details(selected_trip_location, selected_trip_id):
    selected_trip = Trip.query.filter_by(id=selected_trip_id)

    return render_template('trip_detail.html')
  <a href="{{url_for('trips.show_details', selected_trip_location=mytrip.location, selected_trip_id=mytrip.id)}}">

当我运行它时,它显示 TypeError: show_details() missing 1 required positional argument: 'selected_trip_id'

有什么想法可以解决这个问题而不在 URL 中显示唯一 ID?

【问题讨论】:

    标签: flask jinja2 flask-sqlalchemy url-for


    【解决方案1】:

    Flask 文档对url_for 说如下:

    目标端点未知的变量参数是 附加到生成的 URL 作为查询参数。

    因此,selected_trip_id 将是生成的 URL 中的查询参数(而不是发送到 show_details 的参数)。

    如果你不想selected_trip_id出现在URL中,你必须在POST请求中发送,如下:

    1. 从视图函数show_details 的参数中删除selected_trip_id(因为这需要selected_trip_id 包含在URL 中)。

    2. 在您的 HTML 中包含以下代码:

    <form action="{{ url_for('trips.show_details', selected_trip_location=mytrip.location) }}" method="POST">
        <input type="hidden" name="selected_trip_id" value="{{ mytrip.id }}">
        <input type="submit" value="Submit">
    </form>
    
    1. 在您的视图函数中接收selected_trip_id
    @trips_blueprint.route('/mytrips/<selected_trip_location>', methods=['GET','POST'])
    @login_required
    def show_details(selected_trip_location):
        
        if request.method == "POST":
    
            selected_trip_id = request.form.get("selected_trip_id")
            selected_trip = Trip.query.filter_by(id=selected_trip_id)
    
        ...
    

    【讨论】:

    • 这真的很有帮助,但我上周一直在试图弄清楚如何将表单/隐藏输入合并到 for 循环和 ul 标记中。你有没有机会知道这将如何运作?请在此处查看问题:stackoverflow.com/questions/69890111/…
    猜你喜欢
    • 1970-01-01
    • 2017-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-16
    • 1970-01-01
    • 2022-01-05
    • 1970-01-01
    相关资源
    最近更新 更多