Im currently taking the cs50 course and for my final project I wanted to create a simple application in which a random word from a sqlite db gets picked and than the user should input the same word as displayed.
Now I have a problem which Im not able to fix. When a user gets on the site I want to display the random word and when the user wants to correct the inputed word it should direct him to a new html file to "correct" the word and then redirect him to the mainpage.
Now Im not able to do that because when a user "submits" the word via POST a new random number gets generated and with that the words displayed are different and will never be the same. And I cant figure out how to fix it.
Please help thx.
my current code:
@app.route("/", methods=["GET", "POST"])
def mainpage():
for i in range(1):
randoms = random.randrange(1,10)
words = db.execute("SELECT WORD FROM words WHERE ID = ?", randoms)
word = str(words)
if request.method == "POST":
return render_template("check.html", counter=counter, input=input, word=word, random=randoms)
return render_template("mainpage.html", word=word, random=randoms)
I tried reading the words into a txt file and than read the word from the file into the programm but the displayed words are still different because a new random number is generated as im going down the POST route.
EDIT:
I have found a way to do it with the help of chatgpt (lol), the counter resets to 1 if it hits 10:
@app.route("/", methods=["GET", "POST"]) def mainpage(): if 'counter' not in session: session['counter'] = 1 # Initialize the counter if it doesn't exist in the session
return render_template("mainpage.html")
@app.route("/start", methods=["POST", "GET"]) def start(): if 'counter' not in session: session['counter'] = 1 # Initialize the counter if it doesn't exist in the session
result = db.execute("SELECT WORD FROM words WHERE ID = ?", session['counter'])
words = result[0]['WORD']
word = str(words)
if request.method == "POST":
input = request.form.get("input")
if word == input:
session['counter'] += 1
if session['counter'] > 10:
session['counter'] = 1 # Reset the counter when it reaches 10
return render_template("check.html")
else:
return render_template("wrong.html")
return render_template("start.html", word=word)