在Flask应用程序中将多个值添加到表时发生SQL完整性错误



我正在使用MYSQL数据库创建一个Flask应用程序。代码似乎是合法的,从教程和在线搜索我正在关注,但";创建用户功能无法正常工作。尽管我正在添加user_id值,但错误总是会返回。请帮助我解决这个问题,我已经被这个错误困扰了5天以上

db = SQLAlchemy(app)
#database connection 
class friends(db.Model):
__tablename__ = 'user'
user_id = db.Column(db.String, primary_key=True)
user_name = db.Column(db.String)
age = db.Column(db.Integer)
email = db.Column(db.String)
gender = db.Column(db.String)
def __init__(self, user_id, user_name, age, email,gender):
self.id = user_id
self.name = user_name
self.age = age
self.email = email
self.gender = gender
#route
@app.route('/add', methods=['GET', 'POST'])
def add():
if request.method == 'POST':
add_usr_id = request.form['new_usr_id']
add_usr_name = request.form['new_usr_name']
add_usr_age = request.form['new_usr_age']
add_usr_email = request.form['new_usr_email']
add_usr_gender = request.form['new_usr_gender']
commit_user = friends(user_id = add_usr_id, user_name = add_usr_name, age = add_usr_age, email = add_usr_email, gender = add_usr_gender)
db.session.add(commit_user)
db.session.commit()
message = "The record was added."
return render_template('add.html', message=message)
else:
return render_template('add.html')
@app.route('/show')
def read():
show_friend = friends.query.all()
return render_template('show.html', show_friend = show_friend)   

这是完整的错误追溯:

sqlalchemy.exc.IntegrityError: (pymysql.err.IntegrityError) (1048, "Column 'user_name' cannot be null")
[SQL: INSERT INTO user (user_name, age, email, gender) VALUES (%(user_name)s, %(age)s, %(email)s, %(gender)s)]
[parameters: {'user_name': None, 'age': '32', 'email': 'dfak@ekfl.com', 'gender': 'male'}]
(Background on this error at: https://sqlalche.me/e/14/gkpj)
>         add_usr_id = request.form['new_usr_id']

在那里添加调试print或日志记录语句。这将揭示None被传入。

要么安排一个更好的价值呈现或破解某些默认值。

这里有一种默认方式:

add_usr_id = request.form['new_usr_id'] or 'default_user'

相关内容

  • 没有找到相关文章

最新更新