簡體   English   中英

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說明如下:

目標端點未知的變量參數作為查詢參數附加到生成的 URL 中。

因此, selected_trip_id將是生成的 URL 中的查詢參數(不是發送到show_details的參數)。

如果您不想在 URL 中顯示selected_trip_id ,則必須在 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)

    ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM