I am trying to make a website which has solutions of a book (5 chapters). Firstly, I want to open
chapters.html with route
/chapters
which displays five submit buttons and chapter no. as their values.
And when the button is clicked, questions.html must be rendered with route as respective chapter number, like if "Chapter 2" is clicked, the route should be
/chapter2
. I have followed these SO posts Multiple submit Buttons in Flask and use many submit buttons in the same form to get some help.
I am getting Error 405 (Method not allowed) when I click on chapters button but it works well when I manually type the route
/chapter1
or
/chapter5
. How can I solve this problem? Also, do I require any AJAX script to do this?
What I have tried:
chapters.html
<form action="/{{ chapter }}" method="POST">
<input type="submit" value="Chapter 1">
<input type="submit" value="Chapter 2">
<input type="submit" value="Chapter 3">
<input type="submit" value="Chapter 4">
<input type="submit" value="Chapter 5">
</form>
app.py
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/chapters')
def chapters():
return render_template('chapters.html')
@app.route('/<chapter>', methods = ['POST', 'GET'])
def questions(chapter):
if 'Chapter 1' in request.form:
chapter = 'chapter1'
elif 'Chapter 2' in request.form:
chapter = 'chapter2'
elif 'Chapter 3' in request.form:
chapter = 'chapter3'
elif 'Chapter 4' in request.form:
chapter = 'chapter4'
elif 'Chapter 5' in request.form:
chapter = 'chapter5'
return render_template('questions.html', chapter = chapter)
if __name__ == '__main__':
app.run(debug = True)