Python NOT NULL约束失败,但字段不为NULL

Python NOT NULL约束失败,但字段不为NULL,python,python-2.7,sqlalchemy,Python,Python 2.7,Sqlalchemy,我正在尝试使用我的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: cate

我正在尝试使用我的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 = Category(name=placeholder)
email
字段的默认值为
NULL

这是对插入的
的查询:

SQL: u'INSERT INTO category (name, email) VALUES (?, ?)'] [parameters: (u'Pilates', None)
如您所见,第二个参数(即
电子邮件
)是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

谢谢。我还意识到我的错误是我没有尝试创建新类别。我希望用户从现有类别中进行选择,因此我也必须进行这些更改。感谢您向我解释。我还意识到这是因为我后来添加了电子邮件字段,而忘了在该位置添加电子邮件字段。我对其进行了升级。但我无法更改I don’我还不能接受答案。我还得再等六分钟。谢谢你这么快回答。当然:)没问题。