I'm trying to make a language learning quiz in Flask and I'm really struggling to get the answers to work because of the way the routes execute
@views.route('/question', methods=['GET','POST'])
def question():
HorK = session.get("HorK", None)
images = []
lessonID = session.get("lessonChoice", None)
quizImages = getQuizImages(lessonID, images)
image = random.choice(quizImages)
# this part essentially generates a random image from a set of characters and then the user has to write down the correct sound of that character
# don't worry too much about the variables but the html page needs HorK and an image to run
if request.method == 'POST':
character = Character.query.filter_by(image=image).first()
answer = request.form.get("answer")
if answer.upper() == character.romaji:
flash('Correct', category='success')
else:
flash('Incorrect', category='error')
return render_template("question.html", HorK=HorK, image=image)
I think problem is that when the post request is made it runs the route code from the top so it chooses new image different from the one displayed and checks this against the users answer meaning that the user will always be looking at the wrong image. I've tried numerous things to get around this but nothing seems to be working, any ideas?
Thanks in advance :)
CodePudding user response:
I'm not sure, but every time your website reloads it generates new image. When you POST it goes through the code above. You pass the image to render template so try to make your form send also image that you have passed to html file and get image from request. You can do that without even showing any input field on website.
@views.route('/question', methods=['GET','POST'])
def question():
HorK = session.get("HorK", None)
images = []
lessonID = session.get("lessonChoice", None)
quizImages = getQuizImages(lessonID, images)
# this part essentially generates a random image from a set of characters and then the user has to write down the correct sound of that character
# don't worry too much about the variables but the html page needs HorK and an image to run
if request.method == 'POST':
character = Character.query.filter_by(image=request.form.get("image")).first()
answer = request.form.get("answer")
if answer.upper() == character.romaji:
flash('Correct', category='success')
else:
flash('Incorrect', category='error')
image = random.choice(quizImages)
return render_template("question.html", HorK=HorK, image=image)
Remember to add to form invisible input in which one you passes image
Here is example <input type="hidden" name="image" value="{{image}}">