2016-12-03 75 views
1

我正在嘗試使用我的Web窗體添加一個新項目。NOT NULL約束失敗,但字段不爲空

但我得到這個錯誤。雖然我從打印聲明中驗證了電子郵件,但它並非空白。

在該行

File "/Users/j/udacity/item_catalog/item-catalog-190/application.py", line 131, in newItem 
    session.commit() 


IntegrityError: (sqlite3.IntegrityError) NOT NULL constraint failed: category.email [SQL: u'INSERT INTO category (name, email) VALUES (?, ?)'] [parameters: (u'Pilates', None)] 


@app.route('/catalog/new', methods=['GET','POST']) 
def newItem(): 
    if request.method == 'POST': 
     placeholder=request.form['category'] 
     category = Category(name=placeholder) 
     print "**********", login_session['email'] 
     email = login_session['email'] 
     newThing = Item(name=request.form['name'], description=request.form['description'], price=request.form['price'],category=category, email=email) 
     session.add(newThing) 
     session.commit() 
     return redirect('/catalog') 
    else: 
     return render_template('newitem.html') 

這些是我的兩個表。

class Item(Base): 
__tablename__ = 'item' 

name = Column(String(80), nullable=False) 
id = Column(Integer, primary_key=True) 
description = Column(String(250)) 
price = Column(String(8)) 
category_id = Column(Integer, ForeignKey('category.id')) 
email = Column(String(250),nullable=False) 
category = relationship(Category) 


class Category(Base): 
__tablename__ = 'category' 

id = Column(Integer, primary_key=True) 
name = Column(String(250), nullable=False) 
email = Column(String(250), nullable=False) 

回答

4

category表需要email場是NOT NULL,當你創建一個新的類別:

category = Category(name=placeholder) 

email字段的默認值是NULL

這是INSERT查詢:

SQL: u'INSERT INTO category (name, email) VALUES (?, ?)'] [parameters: (u'Pilates', None) 

正如你所看到的,第二paramenter(這是email)是無(這相當於null在SQL

你可能想。改變你的代碼:

if request.method == 'POST': 
    placeholder=request.form['category'] 
    email = login_session['email'] # moved the email here 
    print "**********", login_session['email'] 
    category = Category(name=placeholder, email=email) # here you have the email variable so you can use it 
+0

感謝我意識到我的也是錯誤的是,我不是要創建一個新的類別,而我希望用戶。從現有的類別中選擇,所以我必須進行這些更改。感謝您向我解釋。我也意識到這是因爲我之後添加了電子郵件字段,並忘記在該位置添加電子郵件字段。 – John

+0

不客氣! – Dekel

+0

我投了票。但我還不能接受答案。我必須再等六分鐘。感謝您回答如此之快。 – John

相關問題