sqlalchemy.exc.IntegrityError:(sqlite3.IntegrityError)NOT NULL约束失败:profile.user_id

时间:2019-02-02 18:36:30

标签: python sqlalchemy

我是数据库和SQLAlchemy的新手。我目前正在制作一个网络应用程序,其中有用户,每个用户都有可以创建的个人资料。据我所知,这是一对多的关系。问题是,当我试图作一简介我得到的完整性错误,我不知道为什么。这是在我的模型文件中的代码

class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key = True, autoincrement = True)
    username = db.Column(db.String(20), unique = True, nullable = False)
    email = db.Column(db.String(120), unique = True, nullable = False)
    password = db.Column(db.String(60), nullable = False)
    profiles = db.relationship('Profile', backref = 'creator', lazy = True)

    def __repr(self):
        return f"User('{self.username}', '{self.email}')"

class Profile(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    profileName = db.Column(db.String(), nullable = False)
    firstName = db.Column(db.String(20), nullable = False)
    lastName = db.Column(db.String(30), nullable = False)
    email = db.Column(db.String(), nullable = False)
    phone = db.Column(db.String(), nullable = False)
    address = db.Column(db.String(), nullable = False)
    address1 = db.Column(db.String(), nullable = True)
    city = db.Column(db.String(), nullable = False)
    state = db.Column(db.String(), nullable = False)
    zipCode = db.Column(db.String(), nullable = False)
    country = db.Column(db.String(), nullable = False)
    cc = db.Column(db.String(16), nullable = False)
    expMonth = db.Column(db.String(2), nullable = False)
    expYear = db.Column(db.String(2), nullable = False)
    cvv = db.Column(db.String(4), nullable = False)
    url = db.Column(db.String(), nullable = False)
    user_id = db.Column(db.Integer(), db.ForeignKey('user.id'), nullable = False)

这是在我的路由文件中的代码

@login_required
def newProfile():  
    form = CheckoutForm()
    if form.validate_on_submit():
        profile = Profile(profileName = form.profileName.data, firstName = form.firstName.data, lastName = form.lastName.data, 
        email = form.email.data, phone = form.phone.data, address = form.address.data, address1 = form.address1.data, city = form.city.data,
        state = form.state.data, zipCode = form.zipCode.data, country = form.country.data, cc = form.cc.data, expMonth = form.expMonth.data,
        expYear = form.expYear.data, cvv = form.cvv.data, url = form.url.data, creator = current_user)
        db.session.add(profile)
        db.session.commit()
        flash(f"Profile Created!")
        return redirect(url_for('profiles'))
    return render_template('newProfile.html', title="New Profile", form = form)

我假设它是一些与我的个人资料和user_ID的变量,但我想不出什么。我看了看文档和看了一些关于堆栈溢出的解决方案,但仍想不出搞不定。再次抱歉如果这是一个的n00b问题。我是新来制作网络应用等方面有很多事情我还在学习,并试图了解使用数据库!

0 个答案:

没有答案