2014-11-05 42 views
0

我有一個表名叫「代碼」和3列:ID(主),碼號(串)和激活(布爾值,默認值= FALSE)如何檢查數據庫中的現有值並更改它?

,我已經在這裏我要檢查值的形式,如果它存在,使其激活== False。

我想: myform.py:

#all imports here 
class CheckForm(Form): 
    some_code = StringField('Code: ',validators=[Required()]) 
    submit = SubmitField('Check it!') 

我views.py:

#all imports here 
@some.route('/sometest', methods=['GET', 'POST'] 
def check_function(): 
    form = CheckForm() 
    code=form.some_code.data 
    check_code = Codes.query.filter_by(code=code).first() 
    if check_code.activated == False: 
     check_code.activated = True 
     db.session.add(check_code) 
     db.session.commit() 
    elif check_code.activated == True: 
     print 'Code already used' 
    else: 
     print 'Code not found') 
return render_template('test.html') 

但我發現了錯誤:

AttributeError: 'NoneType' object has no attribute 'activated' 

我m使用燒瓶和sqlalchemy

+1

您的對象'check_code'爲空,這意味着數據庫中沒有包含您的條件的行。 – badc0re 2014-11-05 10:46:42

回答

0

只需爲check_code添加一個條件,以防在數據庫中找不到結果。

提示:處理上面的失敗條件和從函數返回時總是更具可讀性。

def check_function(): 
    form = CheckForm() 
    code=form.some_code.data 
    check_code = Codes.query.filter_by(code=code).first() 
    if not check_code: 
     print 'Code not found' 
     return # You don't have to worry about that again 

    if check_code.activated == True: 
     print 'Code already used' 
     return # Second case is already covered 

    # That's the only case left, no need for an `if` condition 
    check_code.activated = True 
    db.session.add(check_code) 
    db.session.commit() 
+0

小問題在這裏。現在,如果我第一次檢查代碼,它會打印'未找到代碼',並且如果我再次執行此操作(打印'已使用的代碼')。爲什麼我第一次收到'code not founds'? – bartezr 2014-11-05 11:20:39

+0

確保沒有代碼在每次訪問時創建一個新條目。因爲它聽起來像你先調用這個函數(打印代碼沒有找到),那麼你需要做一個form.save()或者在數據庫中創建一個新條目的東西。 – Emam 2014-11-05 12:09:55

相關問題