我正在尝试使用我的 Web 表单添加新项目。
但是我得到了这个错误。电子邮件不为空,但我从打印声明中验证了这一点。
在这一行
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)
最佳答案
您的 category
表要求 email
字段为 NOT NULL
,并且当您创建新类别时:
category = Category(name=placeholder)
email
字段的默认值为 NULL
。
这是对 INSERT
的查询:
SQL: u'INSERT INTO category (name, email) VALUES (?, ?)'] [parameters: (u'Pilates', None)
如您所见,第二个参数(即 email
)为 None(在 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
关于python - NOT NULL 约束失败但字段不为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40943464/