2016-12-03 6 views
1

私のWebフォームを使用して新しいアイテムを追加しようとしています。NOT NULL制約は失敗しましたが、フィールドはNULLではありません

しかし、このエラーが発生します。電子メールはnullではありませんが、私はprintステートメントから検証しました。この行で

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テーブルはNOT NULLするemailフィールドを必要とし、あなたが新しいカテゴリを作成する場合:

category = Category(name=placeholder) 

emailフィールドのデフォルト値はNULLです。

これはINSERTためのクエリです:。

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

あなたが見ることができるように、(emailである)は、第2のparamenterはSQLでnullに変換なし(ありません

あなたは可能性がしたいですコードを次のように変更してください:

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

私はそれをupvoted。しかし、私はまだ答えを受け入れることはできません。もう6分待たなければならない。とても早く答えることに感謝します。 – John

関連する問題