Answer the question
In order to leave comments, you need to log in
How to redirect to URL from HTML form?
Programmatically created dictionary of dictionaries:
from flask import Flask, jsonify,abort,render_template,request,redirect,url_for
app = Flask(__name__)
tasks = [
{
'id': 1,
'title': 'Buy groceries',
'description': 'Milk, ,Pizza,,Cheese,Fruit, Tylenol',
'done': False
},
{
'id': 2,
'title': 'Learn Python',
'description': 'Need to find a good Python tutorial on the web',
'done': False
}
]
<html>
<head>
<title>Search page</title>
</head>
<body>
<div id="container">
<div class="title">
<h1>GET request with Flask</h1>
</div>
<form method="GET" action="{{ url_for('get_task',task_id=TaskID) }}">
<label for="TaskID">Please enter Task ID:</label>
<input type="text" name="TaskID" value="0"/><br />
<input type="submit">
</form>
</div>
</div>
</body>
</html>
that is, depending on the entered Id , redirect to the page with the task@app.route('/tasks/<int:task_id>', methods=['GET'])
def get_task(task_id=None):
if(task_id!=None):
task_id=int(task_id)
task = filter(lambda t: t['id'] == task_id, tasks)
if len(task) == 0:
abort(404)
return jsonify({'task': task[0]})
else:return jsonify({'tasks': tasks})
action="{{ url_for('get_task',task_id=TaskID) }}"
href=" 127.0.0.1:5000/search_page ">
jinja2.exceptions.UndefinedError
UndefinedError: 'TaskID' is undefined
<form action="{{ url_for('get_task') }}">
<label for="TaskID">Please enter Task ID:</label>
<input type="text" name="task_id"/><br />
<input type="submit">
</form>
werkzeug.routing.BuildError
BuildError: ('get_task', {}, None)
Answer the question
In order to leave comments, you need to log in
Or maybe you should use the POST method just on '/tasks/'?
Otherwise, it's a double-edged sword. You do not know in advance what the TaskID will be, but you are trying to form a url for it.
The POST method is done like this.
In html code:
In python code:
@app.route('/tasks/', methods=['POST'])
def get_task():
task_id = request.form['task_id']
'TaskID' is undefined
{{ url_for('get_task') }}
, and change the name attribute of the input element to name="task_id" . The form will send this parameter (input: name => value) to the address specified in action .
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question