[英]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 請求中發送它,如下所示:
從視圖函數show_details
的參數中刪除selected_trip_id
(因為它期望selected_trip_id
包含在 URL 中)。
在您的 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>
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.