Flask url_for() 传递多个参数但只在蓝图路由中显示一个?

Flask url_for() pass multiple parameters but only show one in the blueprint route?

我是 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 文档对 url_for 的说明如下:

Variable arguments that are unknown to the target endpoint are appended to the generated URL as query arguments.

因此,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)

    ...