2015-04-12 102 views
-1

此表單旨在從視圖中的用戶處獲得答案,並且在提交表單時,用戶的答案應該與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

什麼實際的'form.errors'?它爲什麼炸燬?您的表單中至少有一項驗證檢查;也許驗證失敗了? – Makoto

+0

伊夫只是改變了驗證,以IS_NOT_EMPTY並寫入新的代碼行: 「如果form.accepts(請求,會話): 如果request.vars.user_answer == correct_answer: response.flash =‘形式接受’ 別的: response.flash = '錯誤' ELIF form.errors: response.flash = '的形式有錯誤' 其他: response.flash ='請填寫表格」 它現在顯示 「錯誤」 每次。比較user_answer和correct_answer時出錯。 –

+0

...對。但是這並不能回答我的問題 - 「form.errors」中有什麼? – Makoto

回答

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 
相關問題