I am new to Flasks and Jinja templates. I am trying to pass two parameters from my html file to a blueprint route. I am passing the unique ID that I can use to query the database and a location field. I only want the location field to show up in the 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)}}">
When I run this, it says TypeError: show_details() missing 1 required positional argument: 'selected_trip_id'
Any ideas how I can get around that and not display the unique id in the URL?
CodePudding user response:
The Flask documentation says the following for url_for
:
Variable arguments that are unknown to the target endpoint are appended to the generated URL as query arguments.
Therefore, selected_trip_id
will be a query argument in the generated URL (not a parameter sent to show_details
).
If you don't want selected_trip_id
to show in the URL, you have to send it in a POST request, as follows:
Remove
selected_trip_id
from the parameters of the view functionshow_details
(as this expectsselected_trip_id
to be included in the URL).Include the following code in your 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>
- Receive
selected_trip_id
in your view function:
@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)
...