Я пытаюсь протестировать свой веб-сайт с помощью кнопок, которые я кодировал, одна из которых должна вернуть меня на домашнюю страницу моего сайта. Однако, когда я нажимаю эту кнопку, страница, кажется, просто обновляется и остается там, где она есть (я не возвращаюсь на домашнюю страницу).
Я проверил имена всех предоставленных функций / ссылок, чтобы убедиться, что я указываю кнопке правильный пункт назначения.
Ниже приведен код моей страницы «загрузки», которая должна позволять пользователю загружать имя и файл.
<div id="form">
<form action="{{ url_for('algorithm') }}" method="POST" enctype="multipart/form-data">
<div id="algo-header"><h1><u>New Algorithm:</u></h1></div>
<div id="field-names">
User Name:
<br><br><br>
Algorithm:
</div>
<div id="fields">
<input class="text" type = "text" name = "usr" />
<br><br><br>
<input class="text" type="file" id="file" name="file" />
</div>
<div id="buttons">
<br>
<input class="submit" type="submit" style="width: 60px" value="Submit" />
<button id="home-button" class="submit" style="width: 130px">Return to Homepage</button>
</div>
</form>
</div>
<br>
<script type="text/javascript">
document.getElementById("home-button").onclick =
function() {
location.href = "{{ url_for('welcome') }}";
};
</script>
И ниже моя "приветственная" функция в главном приложении моего сайта:
@app.route("/")
def welcome():
rows = get_all_algos()
return render_template("index.html", rows=rows)
А вот функция «алгоритм», которая выводит меня на страницу «/ алгоритм»:
@app.route("/algorithm", methods=["GET", "POST"])
def algorithm():
print('entrypoint')
if request.method == "POST":
if request.form["file"] != "":
try:
print('link-friend')
usr = request.form["usr"]
ln = request.form["file"]
with sql.connect("database.db") as con:
c = con.cursor()
c.execute("INSERT INTO algorithms (user, source) VALUES (?,?)", (usr, ln))
con.commit()
msg = "Algorithm Added Successfully"
except:
con.rollback()
msg = "Error in adding algorithm"
finally:
return render_template("results.html", msg=msg)
con.close()
else:
if "file" not in request.files:
flash("No file part")
return redirect(request.url)
file = request.files["file"]
if file.filename == "":
flash("No selected file")
return redirect(request.url)
if file and allowed_file(file.filename):
usr = request.form["usr"]
filename = secure_filename(file.filename)
print(file.filename)
print(filename)
file.save(os.path.join(app.config["UPLOAD_FOLDER"], filename))
c = con.cursor()
c.execute("INSERT INTO algorithms (user, source) VALUES (?,?)", (usr, filename))
con.commit()
msg = "Algorithm Added Successfully"
return render_template("results.html", msg=msg)
con.close()
# return redirect(url_for("uploaded_file",
# filename=filename))
return render_template("new_algo.html")
Когда я нажимаю на кнопку (которая находится на веб-странице с маршрутом "/ алгоритм"), я должен вернуться на главную / главную страницу ("/"), однако я остаюсь на "/ алгоритм" .
* Примечание: я использую Flask, поэтому я использую формат {{ url_for() }}
для ссылок.