Python Flask SQLAlchely更新而不是插入

Python Flask SQLAlchely更新而不是插入,python,sqlite,flask,sqlalchemy,Python,Sqlite,Flask,Sqlalchemy,我正在关注Corey Schafer制作Flask Web应用程序的系列教程,但我做错了什么。因此,当涉及到从用户到数据库的新帖子时,它会使用表单中的数据写入数据库,但当我尝试从相同的用户添加另一篇帖子时,我会得到错误: [SQL: UPDATE post SET user_id=? WHERE post.id = ?] [parameters: (None, 1)] 我在我的models.py中有这个,它不应该让用户id为None: @login_manager.user_loader de

我正在关注Corey Schafer制作Flask Web应用程序的系列教程,但我做错了什么。因此,当涉及到从用户到数据库的新帖子时,它会使用表单中的数据写入数据库,但当我尝试从相同的用户添加另一篇帖子时,我会得到错误:

[SQL: UPDATE post SET user_id=? WHERE post.id = ?]
[parameters: (None, 1)]
我在我的
models.py中有这个,它不应该让用户id为
None

@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))
登录路径:

@app.route('/login', methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated:
        return redirect(url_for('home'))
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if user and bcrypt.check_password_hash(user.password, form.password.data):
            login_user(user, remember=form.remember.data)
            flash(f'Success.', category='success')
            next_page = request.args.get('next')
            return redirect(next_page) if next_page else redirect(url_for('home'))
        else:
            flash('Unsuccessful!', category='danger')
    return render_template('login.html', title='Log In', form=form)
这是添加新邮件的路线:

@app.route('/post/new', methods=['GET', 'POST'])
@login_required
def new_product():
    form = PostForm()
    if form.validate_on_submit():
        post = Post(name=form.name.data, content=form.content.data, author=current_user)
        db.session.add(post)
        db.session.commit()
        flash('Created!', category='success')
        return redirect(url_for('home'))
    return render_template('new.html', title='Add Post', form=form, legend='New Post')
以下是表格:

class PostForm(FlaskForm):
    name = StringField('Name', validators=[DataRequired()])
    content = StringField('Content', validators=[DataRequired()])
在视频中,他通过另一个用户帐户发布了一篇新帖子。我怎么能逃脱呢

整个错误是这样的:

127.0.0.1 - - [26/Apr/2021 15:00:34] "POST /post/new HTTP/1.1" 500 -
Traceback (most recent call last):
  File "D:\Python\HTML\venv\Lib\site-packages\sqlalchemy\engine\base.py", line 1705, in _execute_context
    self.dialect.do_execute(
  File "D:\Python\HTML\venv\Lib\site-packages\sqlalchemy\engine\default.py", line 716, in do_execute
    cursor.execute(statement, parameters)
sqlite3.IntegrityError: NOT NULL constraint failed: post.user_id

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "D:\Python\HTML\venv\Lib\site-packages\flask\app.py", line 2464, in __call__
    return self.wsgi_app(environ, start_response)
  File "D:\Python\HTML\venv\Lib\site-packages\flask\app.py", line 2450, in wsgi_app
    response = self.handle_exception(e)
  File "D:\Python\HTML\venv\Lib\site-packages\flask\app.py", line 1867, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "D:\Python\HTML\venv\Lib\site-packages\flask\_compat.py", line 39, in reraise
    raise value
  File "D:\Python\HTML\venv\Lib\site-packages\flask\app.py", line 2447, in wsgi_app
    response = self.full_dispatch_request()
  File "D:\Python\HTML\venv\Lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "D:\Python\HTML\venv\Lib\site-packages\flask\app.py", line 1821, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "D:\Python\HTML\venv\Lib\site-packages\flask\_compat.py", line 39, in reraise
    raise value
  File "D:\Python\HTML\venv\Lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
    rv = self.dispatch_request()
  File "D:\Python\HTML\venv\Lib\site-packages\flask\app.py", line 1936, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "D:\Python\HTML\blog\Lib\site-packages\flask_login\utils.py", line 272, in decorated_view
    return func(*args, **kwargs)
  File "D:\Python\HTML\store\routes.py", line 101, in new_product
    db.session.commit()
  File "<string>", line 2, in commit

  File "D:\Python\HTML\venv\Lib\site-packages\sqlalchemy\orm\session.py", line 1423, in commit
    self._transaction.commit(_to_root=self.future)
  File "D:\Python\HTML\venv\Lib\site-packages\sqlalchemy\orm\session.py", line 829, in commit
    self._prepare_impl()
  File "D:\Python\HTML\venv\Lib\site-packages\sqlalchemy\orm\session.py", line 808, in _prepare_impl
    self.session.flush()
  File "D:\Python\HTML\venv\Lib\site-packages\sqlalchemy\orm\session.py", line 3255, in flush
    self._flush(objects)
  File "D:\Python\HTML\venv\Lib\site-packages\sqlalchemy\orm\session.py", line 3395, in _flush
    transaction.rollback(_capture_exception=True)
  File "D:\Python\HTML\venv\Lib\site-packages\sqlalchemy\util\langhelpers.py", line 70, in __exit__
    compat.raise_(
  File "D:\Python\HTML\venv\Lib\site-packages\sqlalchemy\util\compat.py", line 211, in raise_
    raise exception
  File "D:\Python\HTML\venv\Lib\site-packages\sqlalchemy\orm\session.py", line 3355, in _flush
    flush_context.execute()
  File "D:\Python\HTML\venv\Lib\site-packages\sqlalchemy\orm\unitofwork.py", line 453, in execute
    rec.execute(self)
  File "D:\Python\HTML\venv\Lib\site-packages\sqlalchemy\orm\unitofwork.py", line 627, in execute
    util.preloaded.orm_persistence.save_obj(
  File "D:\Python\HTML\venv\Lib\site-packages\sqlalchemy\orm\persistence.py", line 234, in save_obj
    _emit_update_statements(
  File "D:\Python\HTML\venv\Lib\site-packages\sqlalchemy\orm\persistence.py", line 998, in _emit_update_statements
    c = connection._execute_20(
  File "D:\Python\HTML\venv\Lib\site-packages\sqlalchemy\engine\base.py", line 1520, in _execute_20
    return meth(self, args_10style, kwargs_10style, execution_options)
  File "D:\Python\HTML\venv\Lib\site-packages\sqlalchemy\sql\elements.py", line 313, in _execute_on_connection
    return connection._execute_clauseelement(
  File "D:\Python\HTML\venv\Lib\site-packages\sqlalchemy\engine\base.py", line 1389, in _execute_clauseelement
    ret = self._execute_context(
  File "D:\Python\HTML\venv\Lib\site-packages\sqlalchemy\engine\base.py", line 1748, in _execute_context
    self._handle_dbapi_exception(
  File "D:\Python\HTML\venv\Lib\site-packages\sqlalchemy\engine\base.py", line 1929, in _handle_dbapi_exception
    util.raise_(
  File "D:\Python\HTML\venv\Lib\site-packages\sqlalchemy\util\compat.py", line 211, in raise_
    raise exception
  File "D:\Python\HTML\venv\Lib\site-packages\sqlalchemy\engine\base.py", line 1705, in _execute_context
    self.dialect.do_execute(
  File "D:\Python\HTML\venv\Lib\site-packages\sqlalchemy\engine\default.py", line 716, in do_execute
    cursor.execute(statement, parameters)
sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) NOT NULL constraint failed: post.user_id
[SQL: UPDATE post SET user_id=? WHERE post.id = ?]
[parameters: (None, 1)]
(Background on this error at: http://sqlalche.me/e/14/gkpj)
127.0.0.1 - - [26/Apr/2021 15:00:34] "GET /product/new?__debugger__=yes&cmd=resource&f=style.css HTTP/1.1" 200 -
127.0.0.1 - - [26/Apr/2021 15:00:34] "GET /product/new?__debugger__=yes&cmd=resource&f=jquery.js HTTP/1.1" 200 -
127.0.0.1 - - [26/Apr/2021 15:00:34] "GET /product/new?__debugger__=yes&cmd=resource&f=debugger.js HTTP/1.1" 200 -
127.0.0.1 - - [26/Apr/2021 15:00:35] "GET /product/new?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 200 -
127.0.0.1 - - [26/Apr/2021 15:00:35] "GET /product/new?__debugger__=yes&cmd=resource&f=ubuntu.ttf HTTP/1.1" 200 -
127.0.0.1 - - [26/Apr/2021 15:00:35] "GET /product/new?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 200 -
它必须重新制作成这样:

from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileAllowed
from flask_login import current_user
from wtforms import StringField, PasswordField, SubmitField, BooleanField, TextAreaField
from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError
from store.models import User

感谢大家的回答。

更新:感谢@IljaEverilä,我错了,
backref
可以用于作业,而不仅仅是检索。我的回答解决了作者的问题,但我对教程代码中错误的评论是不正确的,实际问题在另一个地方。有关
backref
(带赋值示例)的更多信息-

我把它放在那里是因为上面提到的教程中的代码似乎有错误


问题是您没有传递任何
用户id
,但传递了
作者
。我检查了本教程中的代码,注意到Django模型中存在
author
字段,而不是Flask。因此,只要用
user\u id=current\u user.id
替换
author=current\u user
,它就应该可以工作了。current\u user是否经过身份验证?我的意思是用户是否真的登录了?请参见签入
注册
登录
路由。此外,对于您的帖子,您只需要user\u id,因此没有理由传递所有对象,只需传递当前的\u user.id即可。您确定生成此错误消息的路径相同吗?进行一些调试,在代码中添加一些打印以确保。看起来是PUT而不是POSCAN。您从控制台发出整个错误消息?会话中是否为当前用户?db.session中的当前用户显示什么?是的,谢谢,这是可行的,但是
author
user
模型中是backref,如图所示是的,但是
backref
是用于获取相关对象的属性,而不是用于设置它谢谢。这是有用的信息。不,
relationship
backref用于在另一端创建镜像
relationship
属性,通常也应支持分配。“backref是一个用来获取相关对象的属性,而不是用来设置它”为false。@IljaEverilä,你是对的,谢谢你的更正,我更新了我的答案
from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileAllowed
from flask_login import current_user
from wtforms import StringField, PasswordField, SubmitField, BooleanField, TextAreaField
from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError
from store.models import User