此表单旨在从视图中的用户处获得答案,并且在提交表单时,用户答案应与correct_answer变量匹配以传递和更正。但即使用户输入正确答案,表格也会显示错误。我做错了什么?
Default.py
def practice_game():
import random
db_length = db(db.verb.id > 0).count()
verb = db().select(db.verb.ALL,orderby='<random>',limitby= (0,1))[0]
random_int = random.randint(1,6)
global correct_answer
tense = 'present'
if random_int == 1:
correct_answer = str(verb.verb_present_je)
elif random_int == 2:
correct_answer = str(verb.verb_present_tu)
elif random_int == 3:
correct_answer = str(verb.verb_present_il)
elif random_int == 4:
correct_answer = str(verb.verb_present_nous)
elif random_int == 5:
correct_answer = str(verb.verb_present_vous)
else:
correct_answer = str(verb.verb_present_ils)
form=FORM('Your answer:',
INPUT(_name='user_answer', requires=IS_EQUAL_TO(correct_answer)),
INPUT(_type='submit'))
if form.accepts(request,session):
response.flash = 'form accepted'
elif form.errors:
response.flash = 'form has errors'
else:
response.flash = 'please fill the form'
return dict(form=form, counter=session.counter, correct_answer=correct_answer, verb=verb, tense=tense, pronoun=pronoun, current_user=auth.user.first_name)
答案 0 :(得分:0)
表单是自提交的,因此操作被调用两次 - 一次加载空白表单时,再次提交表单时。在每次通话时,您都会生成一个新的随机正确答案。最初显示在页面上的正确答案(您最终输入表单并提交)不一定与提交表单时生成(和验证)的正确答案相同(它们应该匹配六分之一的时间)偶然)。
要避免此问题,您可以在会话中存储初始正确答案,并将其用于验证:
form=FORM('Your answer:',
INPUT(_name='user_answer',
requires=IS_EQUAL_TO(session.correct_answer)),
INPUT(_type='submit'))
if form.accepts(request,session):
response.flash = 'form accepted'
elif form.errors:
response.flash = 'form has errors'
else:
response.flash = 'please fill the form'
session.correct_answer = correct_answer